three.webgpu.nodes.js 1.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070
  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, 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, PointsMaterial, 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, VideoFrameTexture, 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( 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. /** @module TSLCore **/
  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.length > 1 ? 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. /**
  2200. * @function
  2201. * @deprecated since r168. Use {@link Fn} instead.
  2202. *
  2203. * @param {...any} params
  2204. * @returns {Function}
  2205. */
  2206. const tslFn = ( ...params ) => { // @deprecated, r168
  2207. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2208. return Fn( ...params );
  2209. };
  2210. //
  2211. addMethodChaining( 'toGlobal', ( node ) => {
  2212. node.global = true;
  2213. return node;
  2214. } );
  2215. //
  2216. const setCurrentStack = ( stack ) => {
  2217. currentStack = stack;
  2218. };
  2219. const getCurrentStack = () => currentStack;
  2220. const If = ( ...params ) => currentStack.If( ...params );
  2221. function append( node ) {
  2222. if ( currentStack ) currentStack.add( node );
  2223. return node;
  2224. }
  2225. addMethodChaining( 'append', append );
  2226. // types
  2227. const color = new ConvertType( 'color' );
  2228. const float = new ConvertType( 'float', cacheMaps.float );
  2229. const int = new ConvertType( 'int', cacheMaps.ints );
  2230. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2231. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2232. const vec2 = new ConvertType( 'vec2' );
  2233. const ivec2 = new ConvertType( 'ivec2' );
  2234. const uvec2 = new ConvertType( 'uvec2' );
  2235. const bvec2 = new ConvertType( 'bvec2' );
  2236. const vec3 = new ConvertType( 'vec3' );
  2237. const ivec3 = new ConvertType( 'ivec3' );
  2238. const uvec3 = new ConvertType( 'uvec3' );
  2239. const bvec3 = new ConvertType( 'bvec3' );
  2240. const vec4 = new ConvertType( 'vec4' );
  2241. const ivec4 = new ConvertType( 'ivec4' );
  2242. const uvec4 = new ConvertType( 'uvec4' );
  2243. const bvec4 = new ConvertType( 'bvec4' );
  2244. const mat2 = new ConvertType( 'mat2' );
  2245. const mat3 = new ConvertType( 'mat3' );
  2246. const mat4 = new ConvertType( 'mat4' );
  2247. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2248. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2249. addMethodChaining( 'toColor', color );
  2250. addMethodChaining( 'toFloat', float );
  2251. addMethodChaining( 'toInt', int );
  2252. addMethodChaining( 'toUint', uint );
  2253. addMethodChaining( 'toBool', bool );
  2254. addMethodChaining( 'toVec2', vec2 );
  2255. addMethodChaining( 'toIVec2', ivec2 );
  2256. addMethodChaining( 'toUVec2', uvec2 );
  2257. addMethodChaining( 'toBVec2', bvec2 );
  2258. addMethodChaining( 'toVec3', vec3 );
  2259. addMethodChaining( 'toIVec3', ivec3 );
  2260. addMethodChaining( 'toUVec3', uvec3 );
  2261. addMethodChaining( 'toBVec3', bvec3 );
  2262. addMethodChaining( 'toVec4', vec4 );
  2263. addMethodChaining( 'toIVec4', ivec4 );
  2264. addMethodChaining( 'toUVec4', uvec4 );
  2265. addMethodChaining( 'toBVec4', bvec4 );
  2266. addMethodChaining( 'toMat2', mat2 );
  2267. addMethodChaining( 'toMat3', mat3 );
  2268. addMethodChaining( 'toMat4', mat4 );
  2269. // basic nodes
  2270. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2271. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2272. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2273. addMethodChaining( 'element', element );
  2274. addMethodChaining( 'convert', convert );
  2275. /** @module UniformGroupNode **/
  2276. /**
  2277. * This node can be used to group single instances of {@link UniformNode}
  2278. * and manage them as a uniform buffer.
  2279. *
  2280. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2281. * will be used when defining the {@link UniformNode#groupNode} property.
  2282. *
  2283. * - `objectGroup`: Uniform buffer per object.
  2284. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2285. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2286. *
  2287. * @augments Node
  2288. */
  2289. class UniformGroupNode extends Node {
  2290. static get type() {
  2291. return 'UniformGroupNode';
  2292. }
  2293. /**
  2294. * Constructs a new uniform group node.
  2295. *
  2296. * @param {String} name - The name of the uniform group node.
  2297. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  2298. * @param {Number} [order=1] - Influences the internal sorting.
  2299. */
  2300. constructor( name, shared = false, order = 1 ) {
  2301. super( 'string' );
  2302. /**
  2303. * The name of the uniform group node.
  2304. *
  2305. * @type {String}
  2306. */
  2307. this.name = name;
  2308. /**
  2309. * Whether this uniform group node is shared or not.
  2310. *
  2311. * @type {Boolean}
  2312. * @default false
  2313. */
  2314. this.shared = shared;
  2315. /**
  2316. * Influences the internal sorting.
  2317. * TODO: Add details when this property should be changed.
  2318. *
  2319. * @type {Number}
  2320. * @default 1
  2321. */
  2322. this.order = order;
  2323. /**
  2324. * This flag can be used for type testing.
  2325. *
  2326. * @type {Boolean}
  2327. * @readonly
  2328. * @default true
  2329. */
  2330. this.isUniformGroup = true;
  2331. }
  2332. serialize( data ) {
  2333. super.serialize( data );
  2334. data.name = this.name;
  2335. data.version = this.version;
  2336. data.shared = this.shared;
  2337. }
  2338. deserialize( data ) {
  2339. super.deserialize( data );
  2340. this.name = data.name;
  2341. this.version = data.version;
  2342. this.shared = data.shared;
  2343. }
  2344. }
  2345. /**
  2346. * TSL function for creating a uniform group node with the given name.
  2347. *
  2348. * @function
  2349. * @param {String} name - The name of the uniform group node.
  2350. * @returns {UniformGroupNode}
  2351. */
  2352. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2353. /**
  2354. * TSL function for creating a shared uniform group node with the given name and order.
  2355. *
  2356. * @function
  2357. * @param {String} name - The name of the uniform group node.
  2358. * @param {Number} [order=0] - Influences the internal sorting.
  2359. * @returns {UniformGroupNode}
  2360. */
  2361. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2362. /**
  2363. * TSL object that represents a shared uniform group node which is updated once per frame.
  2364. *
  2365. * @type {UniformGroupNode}
  2366. */
  2367. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2368. /**
  2369. * TSL object that represents a shared uniform group node which is updated once per render.
  2370. *
  2371. * @type {UniformGroupNode}
  2372. */
  2373. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2374. /**
  2375. * TSL object that represents a uniform group node which is updated once per object.
  2376. *
  2377. * @type {UniformGroupNode}
  2378. */
  2379. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2380. /** @module UniformNode **/
  2381. /**
  2382. * Class for representing a uniform.
  2383. *
  2384. * @augments InputNode
  2385. */
  2386. class UniformNode extends InputNode {
  2387. static get type() {
  2388. return 'UniformNode';
  2389. }
  2390. /**
  2391. * Constructs a new uniform node.
  2392. *
  2393. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2394. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2395. */
  2396. constructor( value, nodeType = null ) {
  2397. super( value, nodeType );
  2398. /**
  2399. * This flag can be used for type testing.
  2400. *
  2401. * @type {Boolean}
  2402. * @readonly
  2403. * @default true
  2404. */
  2405. this.isUniformNode = true;
  2406. /**
  2407. * The name or label of the uniform.
  2408. *
  2409. * @type {String}
  2410. * @default ''
  2411. */
  2412. this.name = '';
  2413. /**
  2414. * The uniform group of this uniform. By default, uniforms are
  2415. * managed per object but they might belong to a shared group
  2416. * which is updated per frame or render call.
  2417. *
  2418. * @type {UniformGroupNode}
  2419. */
  2420. this.groupNode = objectGroup;
  2421. }
  2422. /**
  2423. * Sets the {@link UniformNode#name} property.
  2424. *
  2425. * @param {String} name - The name of the uniform.
  2426. * @return {UniformNode} A reference to this node.
  2427. */
  2428. label( name ) {
  2429. this.name = name;
  2430. return this;
  2431. }
  2432. /**
  2433. * Sets the {@link UniformNode#groupNode} property.
  2434. *
  2435. * @param {UniformGroupNode} group - The uniform group.
  2436. * @return {UniformNode} A reference to this node.
  2437. */
  2438. setGroup( group ) {
  2439. this.groupNode = group;
  2440. return this;
  2441. }
  2442. /**
  2443. * Returns the {@link UniformNode#groupNode}.
  2444. *
  2445. * @return {UniformGroupNode} The uniform group.
  2446. */
  2447. getGroup() {
  2448. return this.groupNode;
  2449. }
  2450. /**
  2451. * By default, this method returns the result of {@link Node#getHash} but derived
  2452. * classes might overwrite this method with a different implementation.
  2453. *
  2454. * @param {NodeBuilder} builder - The current node builder.
  2455. * @return {String} The uniform hash.
  2456. */
  2457. getUniformHash( builder ) {
  2458. return this.getHash( builder );
  2459. }
  2460. onUpdate( callback, updateType ) {
  2461. const self = this.getSelf();
  2462. callback = callback.bind( self );
  2463. return super.onUpdate( ( frame ) => {
  2464. const value = callback( frame, self );
  2465. if ( value !== undefined ) {
  2466. this.value = value;
  2467. }
  2468. }, updateType );
  2469. }
  2470. generate( builder, output ) {
  2471. const type = this.getNodeType( builder );
  2472. const hash = this.getUniformHash( builder );
  2473. let sharedNode = builder.getNodeFromHash( hash );
  2474. if ( sharedNode === undefined ) {
  2475. builder.setHashNode( this, hash );
  2476. sharedNode = this;
  2477. }
  2478. const sharedNodeType = sharedNode.getInputType( builder );
  2479. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2480. const propertyName = builder.getPropertyName( nodeUniform );
  2481. if ( builder.context.label !== undefined ) delete builder.context.label;
  2482. return builder.format( propertyName, type, output );
  2483. }
  2484. }
  2485. /**
  2486. * TSL function for creating a uniform node.
  2487. *
  2488. * @function
  2489. * @param {Any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2490. * @param {String?} arg2 - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2491. * @returns {UniformNode}
  2492. */
  2493. const uniform = ( arg1, arg2 ) => {
  2494. const nodeType = getConstNodeType( arg2 || arg1 );
  2495. // @TODO: get ConstNode from .traverse() in the future
  2496. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2497. return nodeObject( new UniformNode( value, nodeType ) );
  2498. };
  2499. /** @module PropertyNode **/
  2500. /**
  2501. * This class represents a shader property. It can be used
  2502. * to explicitly define a property and assign a value to it.
  2503. *
  2504. * ```js
  2505. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2506. *```
  2507. * `PropertyNode` is used by the engine to predefined common material properties
  2508. * for TSL code.
  2509. *
  2510. * @augments Node
  2511. */
  2512. class PropertyNode extends Node {
  2513. static get type() {
  2514. return 'PropertyNode';
  2515. }
  2516. /**
  2517. * Constructs a new property node.
  2518. *
  2519. * @param {String} nodeType - The type of the node.
  2520. * @param {String?} [name=null] - The name of the property in the shader.
  2521. * @param {Boolean} [varying=false] - Whether this property is a varying or not.
  2522. */
  2523. constructor( nodeType, name = null, varying = false ) {
  2524. super( nodeType );
  2525. /**
  2526. * The name of the property in the shader. If no name is defined,
  2527. * the node system auto-generates one.
  2528. *
  2529. * @type {String?}
  2530. * @default null
  2531. */
  2532. this.name = name;
  2533. /**
  2534. * Whether this property is a varying or not.
  2535. *
  2536. * @type {Boolean}
  2537. * @default false
  2538. */
  2539. this.varying = varying;
  2540. /**
  2541. * This flag can be used for type testing.
  2542. *
  2543. * @type {Boolean}
  2544. * @readonly
  2545. * @default true
  2546. */
  2547. this.isPropertyNode = true;
  2548. }
  2549. getHash( builder ) {
  2550. return this.name || super.getHash( builder );
  2551. }
  2552. /**
  2553. * The method is overwritten so it always returns `true`.
  2554. *
  2555. * @param {NodeBuilder} builder - The current node builder.
  2556. * @return {Boolean} Whether this node is global or not.
  2557. */
  2558. isGlobal( /*builder*/ ) {
  2559. return true;
  2560. }
  2561. generate( builder ) {
  2562. let nodeVar;
  2563. if ( this.varying === true ) {
  2564. nodeVar = builder.getVaryingFromNode( this, this.name );
  2565. nodeVar.needsInterpolation = true;
  2566. } else {
  2567. nodeVar = builder.getVarFromNode( this, this.name );
  2568. }
  2569. return builder.getPropertyName( nodeVar );
  2570. }
  2571. }
  2572. /**
  2573. * TSL function for creating a property node.
  2574. *
  2575. * @function
  2576. * @param {String} type - The type of the node.
  2577. * @param {String?} [name=null] - The name of the property in the shader.
  2578. * @returns {PropertyNode}
  2579. */
  2580. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2581. /**
  2582. * TSL function for creating a varying property node.
  2583. *
  2584. * @function
  2585. * @param {String} type - The type of the node.
  2586. * @param {String?} [name=null] - The name of the varying in the shader.
  2587. * @returns {PropertyNode}
  2588. */
  2589. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2590. /**
  2591. * TSL object that represents the shader variable `DiffuseColor`.
  2592. *
  2593. * @type {PropertyNode<vec4>}
  2594. */
  2595. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2596. /**
  2597. * TSL object that represents the shader variable `EmissiveColor`.
  2598. *
  2599. * @type {PropertyNode<vec3>}
  2600. */
  2601. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2602. /**
  2603. * TSL object that represents the shader variable `Roughness`.
  2604. *
  2605. * @type {PropertyNode<float>}
  2606. */
  2607. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2608. /**
  2609. * TSL object that represents the shader variable `Metalness`.
  2610. *
  2611. * @type {PropertyNode<float>}
  2612. */
  2613. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2614. /**
  2615. * TSL object that represents the shader variable `Clearcoat`.
  2616. *
  2617. * @type {PropertyNode<float>}
  2618. */
  2619. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2620. /**
  2621. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2622. *
  2623. * @type {PropertyNode<float>}
  2624. */
  2625. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2626. /**
  2627. * TSL object that represents the shader variable `Sheen`.
  2628. *
  2629. * @type {PropertyNode<vec3>}
  2630. */
  2631. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2632. /**
  2633. * TSL object that represents the shader variable `SheenRoughness`.
  2634. *
  2635. * @type {PropertyNode<float>}
  2636. */
  2637. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2638. /**
  2639. * TSL object that represents the shader variable `Iridescence`.
  2640. *
  2641. * @type {PropertyNode<float>}
  2642. */
  2643. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2644. /**
  2645. * TSL object that represents the shader variable `IridescenceIOR`.
  2646. *
  2647. * @type {PropertyNode<float>}
  2648. */
  2649. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2650. /**
  2651. * TSL object that represents the shader variable `IridescenceThickness`.
  2652. *
  2653. * @type {PropertyNode<float>}
  2654. */
  2655. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2656. /**
  2657. * TSL object that represents the shader variable `AlphaT`.
  2658. *
  2659. * @type {PropertyNode<float>}
  2660. */
  2661. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2662. /**
  2663. * TSL object that represents the shader variable `Anisotropy`.
  2664. *
  2665. * @type {PropertyNode<float>}
  2666. */
  2667. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2668. /**
  2669. * TSL object that represents the shader variable `AnisotropyT`.
  2670. *
  2671. * @type {PropertyNode<vec3>}
  2672. */
  2673. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2674. /**
  2675. * TSL object that represents the shader variable `AnisotropyB`.
  2676. *
  2677. * @type {PropertyNode<vec3>}
  2678. */
  2679. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2680. /**
  2681. * TSL object that represents the shader variable `SpecularColor`.
  2682. *
  2683. * @type {PropertyNode<color>}
  2684. */
  2685. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2686. /**
  2687. * TSL object that represents the shader variable `SpecularF90`.
  2688. *
  2689. * @type {PropertyNode<float>}
  2690. */
  2691. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2692. /**
  2693. * TSL object that represents the shader variable `Shininess`.
  2694. *
  2695. * @type {PropertyNode<float>}
  2696. */
  2697. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2698. /**
  2699. * TSL object that represents the shader variable `Output`.
  2700. *
  2701. * @type {PropertyNode<vec4>}
  2702. */
  2703. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2704. /**
  2705. * TSL object that represents the shader variable `dashSize`.
  2706. *
  2707. * @type {PropertyNode<float>}
  2708. */
  2709. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2710. /**
  2711. * TSL object that represents the shader variable `gapSize`.
  2712. *
  2713. * @type {PropertyNode<float>}
  2714. */
  2715. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2716. /**
  2717. * TSL object that represents the shader variable `pointWidth`.
  2718. *
  2719. * @type {PropertyNode<float>}
  2720. */
  2721. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2722. /**
  2723. * TSL object that represents the shader variable `IOR`.
  2724. *
  2725. * @type {PropertyNode<float>}
  2726. */
  2727. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2728. /**
  2729. * TSL object that represents the shader variable `Transmission`.
  2730. *
  2731. * @type {PropertyNode<float>}
  2732. */
  2733. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2734. /**
  2735. * TSL object that represents the shader variable `Thickness`.
  2736. *
  2737. * @type {PropertyNode<float>}
  2738. */
  2739. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2740. /**
  2741. * TSL object that represents the shader variable `AttenuationDistance`.
  2742. *
  2743. * @type {PropertyNode<float>}
  2744. */
  2745. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2746. /**
  2747. * TSL object that represents the shader variable `AttenuationColor`.
  2748. *
  2749. * @type {PropertyNode<color>}
  2750. */
  2751. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2752. /**
  2753. * TSL object that represents the shader variable `Dispersion`.
  2754. *
  2755. * @type {PropertyNode<float>}
  2756. */
  2757. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2758. /** @module AssignNode **/
  2759. /**
  2760. * These node represents an assign operation. Meaning a node is assigned
  2761. * to another node.
  2762. *
  2763. * @augments TempNode
  2764. */
  2765. class AssignNode extends TempNode {
  2766. static get type() {
  2767. return 'AssignNode';
  2768. }
  2769. /**
  2770. * Constructs a new assign node.
  2771. *
  2772. * @param {Node} targetNode - The target node.
  2773. * @param {Node} sourceNode - The source type.
  2774. */
  2775. constructor( targetNode, sourceNode ) {
  2776. super();
  2777. /**
  2778. * The target node.
  2779. *
  2780. * @type {Node}
  2781. */
  2782. this.targetNode = targetNode;
  2783. /**
  2784. * The source node.
  2785. *
  2786. * @type {Node}
  2787. */
  2788. this.sourceNode = sourceNode;
  2789. }
  2790. /**
  2791. * Whether this node is used more than once in context of other nodes. This method
  2792. * is overwritten since it always returns `false` (assigns are unique).
  2793. *
  2794. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2795. */
  2796. hasDependencies() {
  2797. return false;
  2798. }
  2799. getNodeType( builder, output ) {
  2800. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2801. }
  2802. /**
  2803. * Whether a split is required when assigning source to target. This can happen when the component length of
  2804. * target and source data type does not match.
  2805. *
  2806. * @param {NodeBuilder} builder - The current node builder.
  2807. * @return {Boolean} Whether a split is required when assigning source to target.
  2808. */
  2809. needsSplitAssign( builder ) {
  2810. const { targetNode } = this;
  2811. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2812. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2813. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2814. return assignDifferentVector;
  2815. }
  2816. return false;
  2817. }
  2818. generate( builder, output ) {
  2819. const { targetNode, sourceNode } = this;
  2820. const needsSplitAssign = this.needsSplitAssign( builder );
  2821. const targetType = targetNode.getNodeType( builder );
  2822. const target = targetNode.context( { assign: true } ).build( builder );
  2823. const source = sourceNode.build( builder, targetType );
  2824. const sourceType = sourceNode.getNodeType( builder );
  2825. const nodeData = builder.getDataFromNode( this );
  2826. //
  2827. let snippet;
  2828. if ( nodeData.initialized === true ) {
  2829. if ( output !== 'void' ) {
  2830. snippet = target;
  2831. }
  2832. } else if ( needsSplitAssign ) {
  2833. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2834. const sourceProperty = builder.getPropertyName( sourceVar );
  2835. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2836. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2837. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2838. const component = targetNode.components[ i ];
  2839. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2840. }
  2841. if ( output !== 'void' ) {
  2842. snippet = target;
  2843. }
  2844. } else {
  2845. snippet = `${ target } = ${ source }`;
  2846. if ( output === 'void' || sourceType === 'void' ) {
  2847. builder.addLineFlowCode( snippet, this );
  2848. if ( output !== 'void' ) {
  2849. snippet = target;
  2850. }
  2851. }
  2852. }
  2853. nodeData.initialized = true;
  2854. return builder.format( snippet, targetType, output );
  2855. }
  2856. }
  2857. /**
  2858. * TSL function for creating an assign node.
  2859. *
  2860. * @function
  2861. * @param {Node} targetNode - The target node.
  2862. * @param {Node} sourceNode - The source type.
  2863. * @returns {AssignNode}
  2864. */
  2865. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2866. addMethodChaining( 'assign', assign );
  2867. /**
  2868. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2869. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2870. * this logic.
  2871. *
  2872. * @augments TempNode
  2873. */
  2874. class FunctionCallNode extends TempNode {
  2875. static get type() {
  2876. return 'FunctionCallNode';
  2877. }
  2878. /**
  2879. * Constructs a new function call node.
  2880. *
  2881. * @param {FunctionNode?} functionNode - The function node.
  2882. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2883. */
  2884. constructor( functionNode = null, parameters = {} ) {
  2885. super();
  2886. /**
  2887. * The function node.
  2888. *
  2889. * @type {FunctionNode}
  2890. * @default null
  2891. */
  2892. this.functionNode = functionNode;
  2893. /**
  2894. * The parameters of the function call.
  2895. *
  2896. * @type {Object<String, Node>}
  2897. * @default {}
  2898. */
  2899. this.parameters = parameters;
  2900. }
  2901. /**
  2902. * Sets the parameters of the function call node.
  2903. *
  2904. * @param {Object<String, Node>} parameters - The parameters to set.
  2905. * @return {FunctionCallNode} A reference to this node.
  2906. */
  2907. setParameters( parameters ) {
  2908. this.parameters = parameters;
  2909. return this;
  2910. }
  2911. /**
  2912. * Returns the parameters of the function call node.
  2913. *
  2914. * @return {Object<String, Node>} The parameters of this node.
  2915. */
  2916. getParameters() {
  2917. return this.parameters;
  2918. }
  2919. getNodeType( builder ) {
  2920. return this.functionNode.getNodeType( builder );
  2921. }
  2922. generate( builder ) {
  2923. const params = [];
  2924. const functionNode = this.functionNode;
  2925. const inputs = functionNode.getInputs( builder );
  2926. const parameters = this.parameters;
  2927. const generateInput = ( node, inputNode ) => {
  2928. const type = inputNode.type;
  2929. const pointer = type === 'pointer';
  2930. let output;
  2931. if ( pointer ) output = '&' + node.build( builder );
  2932. else output = node.build( builder, type );
  2933. return output;
  2934. };
  2935. if ( Array.isArray( parameters ) ) {
  2936. for ( let i = 0; i < parameters.length; i ++ ) {
  2937. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  2938. }
  2939. } else {
  2940. for ( const inputNode of inputs ) {
  2941. const node = parameters[ inputNode.name ];
  2942. if ( node !== undefined ) {
  2943. params.push( generateInput( node, inputNode ) );
  2944. } else {
  2945. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  2946. }
  2947. }
  2948. }
  2949. const functionName = functionNode.build( builder, 'property' );
  2950. return `${functionName}( ${params.join( ', ' )} )`;
  2951. }
  2952. }
  2953. const call = ( func, ...params ) => {
  2954. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  2955. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  2956. };
  2957. addMethodChaining( 'call', call );
  2958. /** @module OperatorNode **/
  2959. /**
  2960. * This node represents basic mathematical and logical operations like addition,
  2961. * subtraction or comparisons (e.g. `equal()`).
  2962. *
  2963. * @augments TempNode
  2964. */
  2965. class OperatorNode extends TempNode {
  2966. static get type() {
  2967. return 'OperatorNode';
  2968. }
  2969. /**
  2970. * Constructs a new operator node.
  2971. *
  2972. * @param {String} op - The operator.
  2973. * @param {Node} aNode - The first input.
  2974. * @param {Node} bNode - The second input.
  2975. * @param {...Node} params - Additional input parameters.
  2976. */
  2977. constructor( op, aNode, bNode, ...params ) {
  2978. super();
  2979. if ( params.length > 0 ) {
  2980. let finalOp = new OperatorNode( op, aNode, bNode );
  2981. for ( let i = 0; i < params.length - 1; i ++ ) {
  2982. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  2983. }
  2984. aNode = finalOp;
  2985. bNode = params[ params.length - 1 ];
  2986. }
  2987. /**
  2988. * The operator.
  2989. *
  2990. * @type {String}
  2991. */
  2992. this.op = op;
  2993. /**
  2994. * The first input.
  2995. *
  2996. * @type {Node}
  2997. */
  2998. this.aNode = aNode;
  2999. /**
  3000. * The second input.
  3001. *
  3002. * @type {Node}
  3003. */
  3004. this.bNode = bNode;
  3005. /**
  3006. * This flag can be used for type testing.
  3007. *
  3008. * @type {Boolean}
  3009. * @readonly
  3010. * @default true
  3011. */
  3012. this.isOperatorNode = true;
  3013. }
  3014. /**
  3015. * This method is overwritten since the node type is inferred from the operator
  3016. * and the input node types.
  3017. *
  3018. * @param {NodeBuilder} builder - The current node builder.
  3019. * @param {String} output - The current output string.
  3020. * @return {String} The node type.
  3021. */
  3022. getNodeType( builder, output ) {
  3023. const op = this.op;
  3024. const aNode = this.aNode;
  3025. const bNode = this.bNode;
  3026. const typeA = aNode.getNodeType( builder );
  3027. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3028. if ( typeA === 'void' || typeB === 'void' ) {
  3029. return 'void';
  3030. } else if ( op === '%' ) {
  3031. return typeA;
  3032. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3033. return builder.getIntegerType( typeA );
  3034. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  3035. return 'bool';
  3036. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3037. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3038. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3039. } else {
  3040. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3041. return typeB;
  3042. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  3043. // matrix x vector
  3044. return builder.getVectorFromMatrix( typeA );
  3045. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  3046. // vector x matrix
  3047. return builder.getVectorFromMatrix( typeB );
  3048. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3049. // anytype x anytype: use the greater length vector
  3050. return typeB;
  3051. }
  3052. return typeA;
  3053. }
  3054. }
  3055. generate( builder, output ) {
  3056. const op = this.op;
  3057. const aNode = this.aNode;
  3058. const bNode = this.bNode;
  3059. const type = this.getNodeType( builder, output );
  3060. let typeA = null;
  3061. let typeB = null;
  3062. if ( type !== 'void' ) {
  3063. typeA = aNode.getNodeType( builder );
  3064. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3065. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  3066. if ( builder.isVector( typeA ) ) {
  3067. typeB = typeA;
  3068. } else if ( typeA !== typeB ) {
  3069. typeA = typeB = 'float';
  3070. }
  3071. } else if ( op === '>>' || op === '<<' ) {
  3072. typeA = type;
  3073. typeB = builder.changeComponentType( typeB, 'uint' );
  3074. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  3075. // matrix x vector
  3076. typeB = builder.getVectorFromMatrix( typeA );
  3077. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  3078. // vector x matrix
  3079. typeA = builder.getVectorFromMatrix( typeB );
  3080. } else {
  3081. // anytype x anytype
  3082. typeA = typeB = type;
  3083. }
  3084. } else {
  3085. typeA = typeB = type;
  3086. }
  3087. const a = aNode.build( builder, typeA );
  3088. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3089. const outputLength = builder.getTypeLength( output );
  3090. const fnOpSnippet = builder.getFunctionOperator( op );
  3091. if ( output !== 'void' ) {
  3092. if ( op === '<' && outputLength > 1 ) {
  3093. if ( builder.useComparisonMethod ) {
  3094. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3095. } else {
  3096. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3097. }
  3098. } else if ( op === '<=' && outputLength > 1 ) {
  3099. if ( builder.useComparisonMethod ) {
  3100. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3101. } else {
  3102. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3103. }
  3104. } else if ( op === '>' && outputLength > 1 ) {
  3105. if ( builder.useComparisonMethod ) {
  3106. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3107. } else {
  3108. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3109. }
  3110. } else if ( op === '>=' && outputLength > 1 ) {
  3111. if ( builder.useComparisonMethod ) {
  3112. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3113. } else {
  3114. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3115. }
  3116. } else if ( op === '!' || op === '~' ) {
  3117. return builder.format( `(${op}${a})`, typeA, output );
  3118. } else if ( fnOpSnippet ) {
  3119. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3120. } else {
  3121. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3122. }
  3123. } else if ( typeA !== 'void' ) {
  3124. if ( fnOpSnippet ) {
  3125. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3126. } else {
  3127. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3128. }
  3129. }
  3130. }
  3131. serialize( data ) {
  3132. super.serialize( data );
  3133. data.op = this.op;
  3134. }
  3135. deserialize( data ) {
  3136. super.deserialize( data );
  3137. this.op = data.op;
  3138. }
  3139. }
  3140. /**
  3141. * Returns the addition of two or more value.
  3142. *
  3143. * @function
  3144. * @param {Node} aNode - The first input.
  3145. * @param {Node} bNode - The second input.
  3146. * @param {...Node} params - Additional input parameters.
  3147. * @returns {OperatorNode}
  3148. */
  3149. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3150. /**
  3151. * Returns the subtraction of two or more value.
  3152. *
  3153. * @function
  3154. * @param {Node} aNode - The first input.
  3155. * @param {Node} bNode - The second input.
  3156. * @param {...Node} params - Additional input parameters.
  3157. * @returns {OperatorNode}
  3158. */
  3159. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3160. /**
  3161. * Returns the multiplication of two or more value.
  3162. *
  3163. * @function
  3164. * @param {Node} aNode - The first input.
  3165. * @param {Node} bNode - The second input.
  3166. * @param {...Node} params - Additional input parameters.
  3167. * @returns {OperatorNode}
  3168. */
  3169. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3170. /**
  3171. * Returns the division of two or more value.
  3172. *
  3173. * @function
  3174. * @param {Node} aNode - The first input.
  3175. * @param {Node} bNode - The second input.
  3176. * @param {...Node} params - Additional input parameters.
  3177. * @returns {OperatorNode}
  3178. */
  3179. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3180. /**
  3181. * Computes the remainder of dividing the first node by the second, for integer values.
  3182. *
  3183. * @function
  3184. * @param {Node} aNode - The first input.
  3185. * @param {Node} bNode - The second input.
  3186. * @returns {OperatorNode}
  3187. */
  3188. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3189. /**
  3190. * Checks if two nodes are equal.
  3191. *
  3192. * @function
  3193. * @param {Node} aNode - The first input.
  3194. * @param {Node} bNode - The second input.
  3195. * @returns {OperatorNode}
  3196. */
  3197. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3198. /**
  3199. * Checks if two nodes are not equal.
  3200. *
  3201. * @function
  3202. * @param {Node} aNode - The first input.
  3203. * @param {Node} bNode - The second input.
  3204. * @returns {OperatorNode}
  3205. */
  3206. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3207. /**
  3208. * Checks if the first node is less than the second.
  3209. *
  3210. * @function
  3211. * @param {Node} aNode - The first input.
  3212. * @param {Node} bNode - The second input.
  3213. * @returns {OperatorNode}
  3214. */
  3215. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3216. /**
  3217. * Checks if the first node is greater than the second.
  3218. *
  3219. * @function
  3220. * @param {Node} aNode - The first input.
  3221. * @param {Node} bNode - The second input.
  3222. * @returns {OperatorNode}
  3223. */
  3224. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3225. /**
  3226. * Checks if the first node is less than or equal to the second.
  3227. *
  3228. * @function
  3229. * @param {Node} aNode - The first input.
  3230. * @param {Node} bNode - The second input.
  3231. * @returns {OperatorNode}
  3232. */
  3233. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3234. /**
  3235. * Checks if the first node is greater than or equal to the second.
  3236. *
  3237. * @function
  3238. * @param {Node} aNode - The first input.
  3239. * @param {Node} bNode - The second input.
  3240. * @returns {OperatorNode}
  3241. */
  3242. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3243. /**
  3244. * Performs logical AND on two nodes.
  3245. *
  3246. * @function
  3247. * @param {Node} aNode - The first input.
  3248. * @param {Node} bNode - The second input.
  3249. * @returns {OperatorNode}
  3250. */
  3251. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3252. /**
  3253. * Performs logical OR on two nodes.
  3254. *
  3255. * @function
  3256. * @param {Node} aNode - The first input.
  3257. * @param {Node} bNode - The second input.
  3258. * @returns {OperatorNode}
  3259. */
  3260. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3261. /**
  3262. * Performs logical NOT on a node.
  3263. *
  3264. * @function
  3265. * @param {Node} aNode - The first input.
  3266. * @param {Node} bNode - The second input.
  3267. * @returns {OperatorNode}
  3268. */
  3269. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3270. /**
  3271. * Performs logical XOR on two nodes.
  3272. *
  3273. * @function
  3274. * @param {Node} aNode - The first input.
  3275. * @param {Node} bNode - The second input.
  3276. * @returns {OperatorNode}
  3277. */
  3278. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3279. /**
  3280. * Performs bitwise AND on two nodes.
  3281. *
  3282. * @function
  3283. * @param {Node} aNode - The first input.
  3284. * @param {Node} bNode - The second input.
  3285. * @returns {OperatorNode}
  3286. */
  3287. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3288. /**
  3289. * Performs bitwise NOT on a node.
  3290. *
  3291. * @function
  3292. * @param {Node} aNode - The first input.
  3293. * @param {Node} bNode - The second input.
  3294. * @returns {OperatorNode}
  3295. */
  3296. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3297. /**
  3298. * Performs bitwise OR on two nodes.
  3299. *
  3300. * @function
  3301. * @param {Node} aNode - The first input.
  3302. * @param {Node} bNode - The second input.
  3303. * @returns {OperatorNode}
  3304. */
  3305. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3306. /**
  3307. * Performs bitwise XOR on two nodes.
  3308. *
  3309. * @function
  3310. * @param {Node} aNode - The first input.
  3311. * @param {Node} bNode - The second input.
  3312. * @returns {OperatorNode}
  3313. */
  3314. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3315. /**
  3316. * Shifts a node to the left.
  3317. *
  3318. * @function
  3319. * @param {Node} aNode - The node to shift.
  3320. * @param {Node} bNode - The value to shift.
  3321. * @returns {OperatorNode}
  3322. */
  3323. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3324. /**
  3325. * Shifts a node to the right.
  3326. *
  3327. * @function
  3328. * @param {Node} aNode - The node to shift.
  3329. * @param {Node} bNode - The value to shift.
  3330. * @returns {OperatorNode}
  3331. */
  3332. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3333. addMethodChaining( 'add', add );
  3334. addMethodChaining( 'sub', sub );
  3335. addMethodChaining( 'mul', mul );
  3336. addMethodChaining( 'div', div );
  3337. addMethodChaining( 'modInt', modInt );
  3338. addMethodChaining( 'equal', equal );
  3339. addMethodChaining( 'notEqual', notEqual );
  3340. addMethodChaining( 'lessThan', lessThan );
  3341. addMethodChaining( 'greaterThan', greaterThan );
  3342. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3343. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3344. addMethodChaining( 'and', and );
  3345. addMethodChaining( 'or', or );
  3346. addMethodChaining( 'not', not );
  3347. addMethodChaining( 'xor', xor );
  3348. addMethodChaining( 'bitAnd', bitAnd );
  3349. addMethodChaining( 'bitNot', bitNot );
  3350. addMethodChaining( 'bitOr', bitOr );
  3351. addMethodChaining( 'bitXor', bitXor );
  3352. addMethodChaining( 'shiftLeft', shiftLeft );
  3353. addMethodChaining( 'shiftRight', shiftRight );
  3354. /**
  3355. * @function
  3356. * @deprecated since r168. Use {@link modInt} instead.
  3357. *
  3358. * @param {...any} params
  3359. * @returns {Function}
  3360. */
  3361. const remainder = ( ...params ) => { // @deprecated, r168
  3362. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3363. return modInt( ...params );
  3364. };
  3365. addMethodChaining( 'remainder', remainder );
  3366. /** @module MathNode **/
  3367. /**
  3368. * This node represents a variety of mathematical methods available in shaders.
  3369. * They are divided into three categories:
  3370. *
  3371. * - Methods with one input like `sin`, `cos` or `normalize`.
  3372. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3373. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3374. *
  3375. * @augments TempNode
  3376. */
  3377. class MathNode extends TempNode {
  3378. static get type() {
  3379. return 'MathNode';
  3380. }
  3381. /**
  3382. * Constructs a new math node.
  3383. *
  3384. * @param {String} method - The method name.
  3385. * @param {Node} aNode - The first input.
  3386. * @param {Node?} [bNode=null] - The second input.
  3387. * @param {Node?} [cNode=null] - The third input.
  3388. */
  3389. constructor( method, aNode, bNode = null, cNode = null ) {
  3390. super();
  3391. /**
  3392. * The method name.
  3393. *
  3394. * @type {String}
  3395. */
  3396. this.method = method;
  3397. /**
  3398. * The first input.
  3399. *
  3400. * @type {Node}
  3401. */
  3402. this.aNode = aNode;
  3403. /**
  3404. * The second input.
  3405. *
  3406. * @type {Node?}
  3407. * @default null
  3408. */
  3409. this.bNode = bNode;
  3410. /**
  3411. * The third input.
  3412. *
  3413. * @type {Node?}
  3414. * @default null
  3415. */
  3416. this.cNode = cNode;
  3417. /**
  3418. * This flag can be used for type testing.
  3419. *
  3420. * @type {Boolean}
  3421. * @readonly
  3422. * @default true
  3423. */
  3424. this.isMathNode = true;
  3425. }
  3426. /**
  3427. * The input type is inferred from the node types of the input nodes.
  3428. *
  3429. * @param {NodeBuilder} builder - The current node builder.
  3430. * @return {String} The input type.
  3431. */
  3432. getInputType( builder ) {
  3433. const aType = this.aNode.getNodeType( builder );
  3434. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3435. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3436. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3437. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3438. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3439. if ( aLen > bLen && aLen > cLen ) {
  3440. return aType;
  3441. } else if ( bLen > cLen ) {
  3442. return bType;
  3443. } else if ( cLen > aLen ) {
  3444. return cType;
  3445. }
  3446. return aType;
  3447. }
  3448. /**
  3449. * The selected method as well as the input type determine the node type of this node.
  3450. *
  3451. * @param {NodeBuilder} builder - The current node builder.
  3452. * @return {String} The node type.
  3453. */
  3454. getNodeType( builder ) {
  3455. const method = this.method;
  3456. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3457. return 'float';
  3458. } else if ( method === MathNode.CROSS ) {
  3459. return 'vec3';
  3460. } else if ( method === MathNode.ALL ) {
  3461. return 'bool';
  3462. } else if ( method === MathNode.EQUALS ) {
  3463. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3464. } else if ( method === MathNode.MOD ) {
  3465. return this.aNode.getNodeType( builder );
  3466. } else {
  3467. return this.getInputType( builder );
  3468. }
  3469. }
  3470. generate( builder, output ) {
  3471. let method = this.method;
  3472. const type = this.getNodeType( builder );
  3473. const inputType = this.getInputType( builder );
  3474. const a = this.aNode;
  3475. const b = this.bNode;
  3476. const c = this.cNode;
  3477. const coordinateSystem = builder.renderer.coordinateSystem;
  3478. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3479. // dir can be either a direction vector or a normal vector
  3480. // upper-left 3x3 of matrix is assumed to be orthogonal
  3481. let tA = a;
  3482. let tB = b;
  3483. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3484. tB = vec4( vec3( tB ), 0.0 );
  3485. } else {
  3486. tA = vec4( vec3( tA ), 0.0 );
  3487. }
  3488. const mulNode = mul( tA, tB ).xyz;
  3489. return normalize( mulNode ).build( builder, output );
  3490. } else if ( method === MathNode.NEGATE ) {
  3491. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3492. } else if ( method === MathNode.ONE_MINUS ) {
  3493. return sub( 1.0, a ).build( builder, output );
  3494. } else if ( method === MathNode.RECIPROCAL ) {
  3495. return div( 1.0, a ).build( builder, output );
  3496. } else if ( method === MathNode.DIFFERENCE ) {
  3497. return abs( sub( a, b ) ).build( builder, output );
  3498. } else {
  3499. const params = [];
  3500. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3501. params.push(
  3502. a.build( builder, type ),
  3503. b.build( builder, type )
  3504. );
  3505. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3506. params.push(
  3507. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3508. b.build( builder, inputType )
  3509. );
  3510. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3511. params.push(
  3512. a.build( builder, inputType ),
  3513. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3514. );
  3515. } else if ( method === MathNode.REFRACT ) {
  3516. params.push(
  3517. a.build( builder, inputType ),
  3518. b.build( builder, inputType ),
  3519. c.build( builder, 'float' )
  3520. );
  3521. } else if ( method === MathNode.MIX ) {
  3522. params.push(
  3523. a.build( builder, inputType ),
  3524. b.build( builder, inputType ),
  3525. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3526. );
  3527. } else {
  3528. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3529. method = 'atan2';
  3530. }
  3531. params.push( a.build( builder, inputType ) );
  3532. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3533. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3534. }
  3535. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3536. }
  3537. }
  3538. serialize( data ) {
  3539. super.serialize( data );
  3540. data.method = this.method;
  3541. }
  3542. deserialize( data ) {
  3543. super.deserialize( data );
  3544. this.method = data.method;
  3545. }
  3546. }
  3547. // 1 input
  3548. MathNode.ALL = 'all';
  3549. MathNode.ANY = 'any';
  3550. MathNode.RADIANS = 'radians';
  3551. MathNode.DEGREES = 'degrees';
  3552. MathNode.EXP = 'exp';
  3553. MathNode.EXP2 = 'exp2';
  3554. MathNode.LOG = 'log';
  3555. MathNode.LOG2 = 'log2';
  3556. MathNode.SQRT = 'sqrt';
  3557. MathNode.INVERSE_SQRT = 'inversesqrt';
  3558. MathNode.FLOOR = 'floor';
  3559. MathNode.CEIL = 'ceil';
  3560. MathNode.NORMALIZE = 'normalize';
  3561. MathNode.FRACT = 'fract';
  3562. MathNode.SIN = 'sin';
  3563. MathNode.COS = 'cos';
  3564. MathNode.TAN = 'tan';
  3565. MathNode.ASIN = 'asin';
  3566. MathNode.ACOS = 'acos';
  3567. MathNode.ATAN = 'atan';
  3568. MathNode.ABS = 'abs';
  3569. MathNode.SIGN = 'sign';
  3570. MathNode.LENGTH = 'length';
  3571. MathNode.NEGATE = 'negate';
  3572. MathNode.ONE_MINUS = 'oneMinus';
  3573. MathNode.DFDX = 'dFdx';
  3574. MathNode.DFDY = 'dFdy';
  3575. MathNode.ROUND = 'round';
  3576. MathNode.RECIPROCAL = 'reciprocal';
  3577. MathNode.TRUNC = 'trunc';
  3578. MathNode.FWIDTH = 'fwidth';
  3579. MathNode.TRANSPOSE = 'transpose';
  3580. // 2 inputs
  3581. MathNode.BITCAST = 'bitcast';
  3582. MathNode.EQUALS = 'equals';
  3583. MathNode.MIN = 'min';
  3584. MathNode.MAX = 'max';
  3585. MathNode.MOD = 'mod';
  3586. MathNode.STEP = 'step';
  3587. MathNode.REFLECT = 'reflect';
  3588. MathNode.DISTANCE = 'distance';
  3589. MathNode.DIFFERENCE = 'difference';
  3590. MathNode.DOT = 'dot';
  3591. MathNode.CROSS = 'cross';
  3592. MathNode.POW = 'pow';
  3593. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3594. // 3 inputs
  3595. MathNode.MIX = 'mix';
  3596. MathNode.CLAMP = 'clamp';
  3597. MathNode.REFRACT = 'refract';
  3598. MathNode.SMOOTHSTEP = 'smoothstep';
  3599. MathNode.FACEFORWARD = 'faceforward';
  3600. // 1 inputs
  3601. /**
  3602. * A small value used to handle floating-point precision errors.
  3603. *
  3604. * @type {Node<float>}
  3605. */
  3606. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3607. /**
  3608. * Represents infinity.
  3609. *
  3610. * @type {Node<float>}
  3611. */
  3612. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3613. /**
  3614. * Represents PI.
  3615. *
  3616. * @type {Node<float>}
  3617. */
  3618. const PI = /*@__PURE__*/ float( Math.PI );
  3619. /**
  3620. * Represents PI * 2.
  3621. *
  3622. * @type {Node<float>}
  3623. */
  3624. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3625. /**
  3626. * Returns `true` if all components of `x` are `true`.
  3627. *
  3628. * @function
  3629. * @param {Node | Number} x - The parameter.
  3630. * @returns {Node<bool>}
  3631. */
  3632. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3633. /**
  3634. * Returns `true` if any components of `x` are `true`.
  3635. *
  3636. * @function
  3637. * @param {Node | Number} x - The parameter.
  3638. * @returns {Node<bool>}
  3639. */
  3640. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3641. /**
  3642. * Converts a quantity in degrees to radians.
  3643. *
  3644. * @function
  3645. * @param {Node | Number} x - The input in degrees.
  3646. * @returns {Node}
  3647. */
  3648. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3649. /**
  3650. * Convert a quantity in radians to degrees.
  3651. *
  3652. * @function
  3653. * @param {Node | Number} x - The input in radians.
  3654. * @returns {Node}
  3655. */
  3656. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3657. /**
  3658. * Returns the natural exponentiation of the parameter.
  3659. *
  3660. * @function
  3661. * @param {Node | Number} x - The parameter.
  3662. * @returns {Node}
  3663. */
  3664. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3665. /**
  3666. * Returns 2 raised to the power of the parameter.
  3667. *
  3668. * @function
  3669. * @param {Node | Number} x - The parameter.
  3670. * @returns {Node}
  3671. */
  3672. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3673. /**
  3674. * Returns the natural logarithm of the parameter.
  3675. *
  3676. * @function
  3677. * @param {Node | Number} x - The parameter.
  3678. * @returns {Node}
  3679. */
  3680. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3681. /**
  3682. * Returns the base 2 logarithm of the parameter.
  3683. *
  3684. * @function
  3685. * @param {Node | Number} x - The parameter.
  3686. * @returns {Node}
  3687. */
  3688. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3689. /**
  3690. * Returns the square root of the parameter.
  3691. *
  3692. * @function
  3693. * @param {Node | Number} x - The parameter.
  3694. * @returns {Node}
  3695. */
  3696. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3697. /**
  3698. * Returns the inverse of the square root of the parameter.
  3699. *
  3700. * @function
  3701. * @param {Node | Number} x - The parameter.
  3702. * @returns {Node}
  3703. */
  3704. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3705. /**
  3706. * Finds the nearest integer less than or equal to the parameter.
  3707. *
  3708. * @function
  3709. * @param {Node | Number} x - The parameter.
  3710. * @returns {Node}
  3711. */
  3712. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3713. /**
  3714. * Finds the nearest integer that is greater than or equal to the parameter.
  3715. *
  3716. * @function
  3717. * @param {Node | Number} x - The parameter.
  3718. * @returns {Node}
  3719. */
  3720. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3721. /**
  3722. * Calculates the unit vector in the same direction as the original vector.
  3723. *
  3724. * @function
  3725. * @param {Node} x - The input vector.
  3726. * @returns {Node}
  3727. */
  3728. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  3729. /**
  3730. * Computes the fractional part of the parameter.
  3731. *
  3732. * @function
  3733. * @param {Node | Number} x - The parameter.
  3734. * @returns {Node}
  3735. */
  3736. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  3737. /**
  3738. * Returns the sine of the parameter.
  3739. *
  3740. * @function
  3741. * @param {Node | Number} x - The parameter.
  3742. * @returns {Node}
  3743. */
  3744. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  3745. /**
  3746. * Returns the cosine of the parameter.
  3747. *
  3748. * @function
  3749. * @param {Node | Number} x - The parameter.
  3750. * @returns {Node}
  3751. */
  3752. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  3753. /**
  3754. * Returns the tangent of the parameter.
  3755. *
  3756. * @function
  3757. * @param {Node | Number} x - The parameter.
  3758. * @returns {Node}
  3759. */
  3760. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  3761. /**
  3762. * Returns the arcsine of the parameter.
  3763. *
  3764. * @function
  3765. * @param {Node | Number} x - The parameter.
  3766. * @returns {Node}
  3767. */
  3768. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  3769. /**
  3770. * Returns the arccosine of the parameter.
  3771. *
  3772. * @function
  3773. * @param {Node | Number} x - The parameter.
  3774. * @returns {Node}
  3775. */
  3776. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  3777. /**
  3778. * Returns the arc-tangent of the parameter.
  3779. * If two parameters are provided, the result is `atan2(y/x)`.
  3780. *
  3781. * @function
  3782. * @param {Node | Number} y - The y parameter.
  3783. * @param {(Node | Number)?} x - The x parameter.
  3784. * @returns {Node}
  3785. */
  3786. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  3787. /**
  3788. * Returns the absolute value of the parameter.
  3789. *
  3790. * @function
  3791. * @param {Node | Number} x - The parameter.
  3792. * @returns {Node}
  3793. */
  3794. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  3795. /**
  3796. * Extracts the sign of the parameter.
  3797. *
  3798. * @function
  3799. * @param {Node | Number} x - The parameter.
  3800. * @returns {Node}
  3801. */
  3802. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  3803. /**
  3804. * Calculates the length of a vector.
  3805. *
  3806. * @function
  3807. * @param {Node} x - The parameter.
  3808. * @returns {Node<float>}
  3809. */
  3810. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  3811. /**
  3812. * Negates the value of the parameter (-x).
  3813. *
  3814. * @function
  3815. * @param {Node | Number} x - The parameter.
  3816. * @returns {Node}
  3817. */
  3818. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  3819. /**
  3820. * Return `1` minus the parameter.
  3821. *
  3822. * @function
  3823. * @param {Node | Number} x - The parameter.
  3824. * @returns {Node}
  3825. */
  3826. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  3827. /**
  3828. * Returns the partial derivative of the parameter with respect to x.
  3829. *
  3830. * @function
  3831. * @param {Node | Number} x - The parameter.
  3832. * @returns {Node}
  3833. */
  3834. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  3835. /**
  3836. * Returns the partial derivative of the parameter with respect to y.
  3837. *
  3838. * @function
  3839. * @param {Node | Number} x - The parameter.
  3840. * @returns {Node}
  3841. */
  3842. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  3843. /**
  3844. * Rounds the parameter to the nearest integer.
  3845. *
  3846. * @function
  3847. * @param {Node | Number} x - The parameter.
  3848. * @returns {Node}
  3849. */
  3850. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  3851. /**
  3852. * Returns the reciprocal of the parameter `(1/x)`.
  3853. *
  3854. * @function
  3855. * @param {Node | Number} x - The parameter.
  3856. * @returns {Node}
  3857. */
  3858. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  3859. /**
  3860. * Truncates the parameter, removing the fractional part.
  3861. *
  3862. * @function
  3863. * @param {Node | Number} x - The parameter.
  3864. * @returns {Node}
  3865. */
  3866. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  3867. /**
  3868. * Returns the sum of the absolute derivatives in x and y.
  3869. *
  3870. * @function
  3871. * @param {Node | Number} x - The parameter.
  3872. * @returns {Node}
  3873. */
  3874. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  3875. /**
  3876. * Returns the transpose of a matrix.
  3877. *
  3878. * @function
  3879. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  3880. * @returns {Node}
  3881. */
  3882. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  3883. // 2 inputs
  3884. /**
  3885. * Reinterpret the bit representation of a value in one type as a value in another type.
  3886. *
  3887. * @function
  3888. * @param {Node | Number} x - The parameter.
  3889. * @param {String} y - The new type.
  3890. * @returns {Node}
  3891. */
  3892. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  3893. /**
  3894. * Returns `true` if `x` equals `y`.
  3895. *
  3896. * @function
  3897. * @param {Node | Number} x - The first parameter.
  3898. * @param {Node | Number} y - The second parameter.
  3899. * @returns {Node<bool>}
  3900. */
  3901. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  3902. /**
  3903. * Returns the lesser of two values.
  3904. *
  3905. * @function
  3906. * @param {Node | Number} x - The y parameter.
  3907. * @param {Node | Number} y - The x parameter.
  3908. * @returns {Node}
  3909. */
  3910. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  3911. /**
  3912. * Returns the greater of two values.
  3913. *
  3914. * @function
  3915. * @param {Node | Number} x - The y parameter.
  3916. * @param {Node | Number} y - The x parameter.
  3917. * @returns {Node}
  3918. */
  3919. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  3920. /**
  3921. * Computes the remainder of dividing the first node by the second one.
  3922. *
  3923. * @function
  3924. * @param {Node | Number} x - The y parameter.
  3925. * @param {Node | Number} y - The x parameter.
  3926. * @returns {Node}
  3927. */
  3928. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  3929. /**
  3930. * Generate a step function by comparing two values.
  3931. *
  3932. * @function
  3933. * @param {Node | Number} x - The y parameter.
  3934. * @param {Node | Number} y - The x parameter.
  3935. * @returns {Node}
  3936. */
  3937. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  3938. /**
  3939. * Calculates the reflection direction for an incident vector.
  3940. *
  3941. * @function
  3942. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  3943. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  3944. * @returns {Node<vec2|vec3|vec4>}
  3945. */
  3946. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  3947. /**
  3948. * Calculates the distance between two points.
  3949. *
  3950. * @function
  3951. * @param {Node<vec2|vec3|vec4>} x - The first point.
  3952. * @param {Node<vec2|vec3|vec4>} y - The second point.
  3953. * @returns {Node<float>}
  3954. */
  3955. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  3956. /**
  3957. * Calculates the absolute difference between two values.
  3958. *
  3959. * @function
  3960. * @param {Node | Number} x - The first parameter.
  3961. * @param {Node | Number} y - The second parameter.
  3962. * @returns {Node}
  3963. */
  3964. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  3965. /**
  3966. * Calculates the dot product of two vectors.
  3967. *
  3968. * @function
  3969. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  3970. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  3971. * @returns {Node<float>}
  3972. */
  3973. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  3974. /**
  3975. * Calculates the cross product of two vectors.
  3976. *
  3977. * @function
  3978. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  3979. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  3980. * @returns {Node<vec2|vec3|vec4>}
  3981. */
  3982. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  3983. /**
  3984. * Return the value of the first parameter raised to the power of the second one.
  3985. *
  3986. * @function
  3987. * @param {Node | Number} x - The first parameter.
  3988. * @param {Node | Number} y - The second parameter.
  3989. * @returns {Node}
  3990. */
  3991. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  3992. /**
  3993. * Returns the square of the parameter.
  3994. *
  3995. * @function
  3996. * @param {Node | Number} x - The first parameter.
  3997. * @returns {Node}
  3998. */
  3999. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  4000. /**
  4001. * Returns the cube of the parameter.
  4002. *
  4003. * @function
  4004. * @param {Node | Number} x - The first parameter.
  4005. * @returns {Node}
  4006. */
  4007. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  4008. /**
  4009. * Returns the fourth power of the parameter.
  4010. *
  4011. * @function
  4012. * @param {Node | Number} x - The first parameter.
  4013. * @returns {Node}
  4014. */
  4015. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  4016. /**
  4017. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4018. *
  4019. * @function
  4020. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4021. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4022. * @returns {Node}
  4023. */
  4024. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  4025. /**
  4026. * Returns the cube root of a number.
  4027. *
  4028. * @function
  4029. * @param {Node | Number} a - The first parameter.
  4030. * @returns {Node}
  4031. */
  4032. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4033. /**
  4034. * Calculate the squared length of a vector.
  4035. *
  4036. * @function
  4037. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4038. * @returns {Node<float>}
  4039. */
  4040. const lengthSq = ( a ) => dot( a, a );
  4041. /**
  4042. * Linearly interpolates between two values.
  4043. *
  4044. * @function
  4045. * @param {Node | Number} a - The first parameter.
  4046. * @param {Node | Number} b - The second parameter.
  4047. * @param {Node | Number} t - The interpolation value.
  4048. * @returns {Node}
  4049. */
  4050. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  4051. /**
  4052. * Constrains a value to lie between two further values.
  4053. *
  4054. * @function
  4055. * @param {Node | Number} value - The value to constrain.
  4056. * @param {Node | Number} [low=0] - The lower bound.
  4057. * @param {Node | Number} [high=1] - The upper bound.
  4058. * @returns {Node}
  4059. */
  4060. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4061. /**
  4062. * Constrains a value between `0` and `1`.
  4063. *
  4064. * @function
  4065. * @param {Node | Number} value - The value to constrain.
  4066. * @returns {Node}
  4067. */
  4068. const saturate = ( value ) => clamp( value );
  4069. /**
  4070. * Calculates the refraction direction for an incident vector.
  4071. *
  4072. * @function
  4073. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4074. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4075. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4076. * @returns {Node<vec2|vec3|vec4>}
  4077. */
  4078. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4079. /**
  4080. * Performs a Hermite interpolation between two values.
  4081. *
  4082. * @function
  4083. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4084. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4085. * @param {Node | Number} x - The source value for interpolation.
  4086. * @returns {Node}
  4087. */
  4088. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4089. /**
  4090. * Returns a vector pointing in the same direction as another.
  4091. *
  4092. * @function
  4093. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4094. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4095. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4096. * @returns {Node<vec2|vec3|vec4>}
  4097. */
  4098. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4099. /**
  4100. * Returns a random value for the given uv.
  4101. *
  4102. * @function
  4103. * @param {Node<vec2>} uv - The uv node.
  4104. * @returns {Node<float>}
  4105. */
  4106. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4107. const a = 12.9898, b = 78.233, c = 43758.5453;
  4108. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4109. return fract( sin( sn ).mul( c ) );
  4110. } );
  4111. /**
  4112. * Alias for `mix()` with a different parameter order.
  4113. *
  4114. * @function
  4115. * @param {Node | Number} t - The interpolation value.
  4116. * @param {Node | Number} e1 - The first parameter.
  4117. * @param {Node | Number} e2 - The second parameter.
  4118. * @returns {Node}
  4119. */
  4120. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4121. /**
  4122. * Alias for `smoothstep()` with a different parameter order.
  4123. *
  4124. * @function
  4125. * @param {Node | Number} x - The source value for interpolation.
  4126. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4127. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4128. * @returns {Node}
  4129. */
  4130. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4131. /**
  4132. * Returns the arc-tangent of the quotient of its parameters.
  4133. *
  4134. * @function
  4135. * @deprecated since r172. Use {@link atan} instead.
  4136. *
  4137. * @param {Node | Number} y - The y parameter.
  4138. * @param {Node | Number} x - The x parameter.
  4139. * @returns {Node}
  4140. */
  4141. const atan2 = ( y, x ) => { // @deprecated, r172
  4142. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4143. return atan( y, x );
  4144. };
  4145. // GLSL alias function
  4146. const faceforward = faceForward;
  4147. const inversesqrt = inverseSqrt;
  4148. // Method chaining
  4149. addMethodChaining( 'all', all );
  4150. addMethodChaining( 'any', any );
  4151. addMethodChaining( 'equals', equals );
  4152. addMethodChaining( 'radians', radians );
  4153. addMethodChaining( 'degrees', degrees );
  4154. addMethodChaining( 'exp', exp );
  4155. addMethodChaining( 'exp2', exp2 );
  4156. addMethodChaining( 'log', log );
  4157. addMethodChaining( 'log2', log2 );
  4158. addMethodChaining( 'sqrt', sqrt );
  4159. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4160. addMethodChaining( 'floor', floor );
  4161. addMethodChaining( 'ceil', ceil );
  4162. addMethodChaining( 'normalize', normalize );
  4163. addMethodChaining( 'fract', fract );
  4164. addMethodChaining( 'sin', sin );
  4165. addMethodChaining( 'cos', cos );
  4166. addMethodChaining( 'tan', tan );
  4167. addMethodChaining( 'asin', asin );
  4168. addMethodChaining( 'acos', acos );
  4169. addMethodChaining( 'atan', atan );
  4170. addMethodChaining( 'abs', abs );
  4171. addMethodChaining( 'sign', sign );
  4172. addMethodChaining( 'length', length );
  4173. addMethodChaining( 'lengthSq', lengthSq );
  4174. addMethodChaining( 'negate', negate );
  4175. addMethodChaining( 'oneMinus', oneMinus );
  4176. addMethodChaining( 'dFdx', dFdx );
  4177. addMethodChaining( 'dFdy', dFdy );
  4178. addMethodChaining( 'round', round );
  4179. addMethodChaining( 'reciprocal', reciprocal );
  4180. addMethodChaining( 'trunc', trunc );
  4181. addMethodChaining( 'fwidth', fwidth );
  4182. addMethodChaining( 'atan2', atan2 );
  4183. addMethodChaining( 'min', min$1 );
  4184. addMethodChaining( 'max', max$1 );
  4185. addMethodChaining( 'mod', mod );
  4186. addMethodChaining( 'step', step );
  4187. addMethodChaining( 'reflect', reflect );
  4188. addMethodChaining( 'distance', distance );
  4189. addMethodChaining( 'dot', dot );
  4190. addMethodChaining( 'cross', cross );
  4191. addMethodChaining( 'pow', pow );
  4192. addMethodChaining( 'pow2', pow2 );
  4193. addMethodChaining( 'pow3', pow3 );
  4194. addMethodChaining( 'pow4', pow4 );
  4195. addMethodChaining( 'transformDirection', transformDirection );
  4196. addMethodChaining( 'mix', mixElement );
  4197. addMethodChaining( 'clamp', clamp );
  4198. addMethodChaining( 'refract', refract );
  4199. addMethodChaining( 'smoothstep', smoothstepElement );
  4200. addMethodChaining( 'faceForward', faceForward );
  4201. addMethodChaining( 'difference', difference );
  4202. addMethodChaining( 'saturate', saturate );
  4203. addMethodChaining( 'cbrt', cbrt );
  4204. addMethodChaining( 'transpose', transpose );
  4205. addMethodChaining( 'rand', rand );
  4206. /** @module ConditionalNode **/
  4207. /**
  4208. * Represents a logical `if/else` statement. Can be used as an alternative
  4209. * to the `If()`/`Else()` syntax.
  4210. *
  4211. * The corresponding TSL `select()` looks like so:
  4212. * ```js
  4213. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4214. * ```
  4215. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4216. * determine the outcome of the entire statement.
  4217. *
  4218. * @augments Node
  4219. */
  4220. class ConditionalNode extends Node {
  4221. static get type() {
  4222. return 'ConditionalNode';
  4223. }
  4224. /**
  4225. * Constructs a new conditional node.
  4226. *
  4227. * @param {Node} condNode - The node that defines the condition.
  4228. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4229. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4230. */
  4231. constructor( condNode, ifNode, elseNode = null ) {
  4232. super();
  4233. /**
  4234. * The node that defines the condition.
  4235. *
  4236. * @type {Node}
  4237. */
  4238. this.condNode = condNode;
  4239. /**
  4240. * The node that is evaluate when the condition ends up `true`.
  4241. *
  4242. * @type {Node}
  4243. */
  4244. this.ifNode = ifNode;
  4245. /**
  4246. * The node that is evaluate when the condition ends up `false`.
  4247. *
  4248. * @type {Node?}
  4249. * @default null
  4250. */
  4251. this.elseNode = elseNode;
  4252. }
  4253. /**
  4254. * This method is overwritten since the node type is inferred from the if/else
  4255. * nodes.
  4256. *
  4257. * @param {NodeBuilder} builder - The current node builder.
  4258. * @return {String} The node type.
  4259. */
  4260. getNodeType( builder ) {
  4261. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4262. if ( ifNode === undefined ) {
  4263. // fallback setup
  4264. this.setup( builder );
  4265. return this.getNodeType( builder );
  4266. }
  4267. const ifType = ifNode.getNodeType( builder );
  4268. if ( elseNode !== null ) {
  4269. const elseType = elseNode.getNodeType( builder );
  4270. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4271. return elseType;
  4272. }
  4273. }
  4274. return ifType;
  4275. }
  4276. setup( builder ) {
  4277. const condNode = this.condNode.cache();
  4278. const ifNode = this.ifNode.cache();
  4279. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4280. //
  4281. const currentNodeBlock = builder.context.nodeBlock;
  4282. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4283. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4284. //
  4285. const properties = builder.getNodeProperties( this );
  4286. properties.condNode = condNode;
  4287. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4288. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4289. }
  4290. generate( builder, output ) {
  4291. const type = this.getNodeType( builder );
  4292. const nodeData = builder.getDataFromNode( this );
  4293. if ( nodeData.nodeProperty !== undefined ) {
  4294. return nodeData.nodeProperty;
  4295. }
  4296. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4297. const needsOutput = output !== 'void';
  4298. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4299. nodeData.nodeProperty = nodeProperty;
  4300. const nodeSnippet = condNode.build( builder, 'bool' );
  4301. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4302. let ifSnippet = ifNode.build( builder, type );
  4303. if ( ifSnippet ) {
  4304. if ( needsOutput ) {
  4305. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4306. } else {
  4307. ifSnippet = 'return ' + ifSnippet + ';';
  4308. }
  4309. }
  4310. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4311. if ( elseNode !== null ) {
  4312. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4313. let elseSnippet = elseNode.build( builder, type );
  4314. if ( elseSnippet ) {
  4315. if ( needsOutput ) {
  4316. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4317. } else {
  4318. elseSnippet = 'return ' + elseSnippet + ';';
  4319. }
  4320. }
  4321. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4322. } else {
  4323. builder.addFlowCode( '\n\n' );
  4324. }
  4325. return builder.format( nodeProperty, type, output );
  4326. }
  4327. }
  4328. /**
  4329. * TSL function for creating a conditional node.
  4330. *
  4331. * @function
  4332. * @param {Node} condNode - The node that defines the condition.
  4333. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4334. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4335. * @returns {ConditionalNode}
  4336. */
  4337. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4338. addMethodChaining( 'select', select );
  4339. // deprecated
  4340. /**
  4341. * @function
  4342. * @deprecated since r168. Use {@link select} instead.
  4343. *
  4344. * @param {...any} params
  4345. * @returns {ConditionalNode}
  4346. */
  4347. const cond = ( ...params ) => { // @deprecated, r168
  4348. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4349. return select( ...params );
  4350. };
  4351. addMethodChaining( 'cond', cond );
  4352. /** @module ContextNode **/
  4353. /**
  4354. * This node can be used as a context management component for another node.
  4355. * {@link NodeBuilder} performs its node building process in a specific context and
  4356. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4357. *
  4358. * ```js
  4359. *node.context( { getUV: () => customCoord } );
  4360. *```
  4361. * @augments Node
  4362. */
  4363. class ContextNode extends Node {
  4364. static get type() {
  4365. return 'ContextNode';
  4366. }
  4367. /**
  4368. * Constructs a new context node.
  4369. *
  4370. * @param {Node} node - The node whose context should be modified.
  4371. * @param {Object} [value={}] - The modified context data.
  4372. */
  4373. constructor( node, value = {} ) {
  4374. super();
  4375. /**
  4376. * This flag can be used for type testing.
  4377. *
  4378. * @type {Boolean}
  4379. * @readonly
  4380. * @default true
  4381. */
  4382. this.isContextNode = true;
  4383. /**
  4384. * The node whose context should be modified.
  4385. *
  4386. * @type {Node}
  4387. */
  4388. this.node = node;
  4389. /**
  4390. * The modified context data.
  4391. *
  4392. * @type {Object}
  4393. * @default {}
  4394. */
  4395. this.value = value;
  4396. }
  4397. /**
  4398. * This method is overwritten to ensure it returns the reference to {@link module:ContextNode~ContextNode#node}.
  4399. *
  4400. * @return {Node} A reference to {@link module:ContextNode~ContextNode#node}.
  4401. */
  4402. getScope() {
  4403. return this.node.getScope();
  4404. }
  4405. /**
  4406. * This method is overwritten to ensure it returns the type of {@link module:ContextNode~ContextNode#node}.
  4407. *
  4408. * @param {NodeBuilder} builder - The current node builder.
  4409. * @return {String} The node type.
  4410. */
  4411. getNodeType( builder ) {
  4412. return this.node.getNodeType( builder );
  4413. }
  4414. analyze( builder ) {
  4415. this.node.build( builder );
  4416. }
  4417. setup( builder ) {
  4418. const previousContext = builder.getContext();
  4419. builder.setContext( { ...builder.context, ...this.value } );
  4420. const node = this.node.build( builder );
  4421. builder.setContext( previousContext );
  4422. return node;
  4423. }
  4424. generate( builder, output ) {
  4425. const previousContext = builder.getContext();
  4426. builder.setContext( { ...builder.context, ...this.value } );
  4427. const snippet = this.node.build( builder, output );
  4428. builder.setContext( previousContext );
  4429. return snippet;
  4430. }
  4431. }
  4432. /**
  4433. * TSL function for creating a context node.
  4434. *
  4435. * @function
  4436. * @param {Node} node - The node whose context should be modified.
  4437. * @param {Object} [value={}] - The modified context data.
  4438. * @returns {ContextNode}
  4439. */
  4440. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4441. /**
  4442. * TSL function for defining a label context value for a given node.
  4443. *
  4444. * @function
  4445. * @param {Node} node - The node whose context should be modified.
  4446. * @param {String} name - The name/label to set.
  4447. * @returns {ContextNode}
  4448. */
  4449. const label = ( node, name ) => context( node, { label: name } );
  4450. addMethodChaining( 'context', context );
  4451. addMethodChaining( 'label', label );
  4452. /** @module VarNode **/
  4453. /**
  4454. * Class for representing shader variables as nodes. Variables are created from
  4455. * existing nodes like the following:
  4456. *
  4457. * ```js
  4458. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4459. * ```
  4460. *
  4461. * @augments Node
  4462. */
  4463. class VarNode extends Node {
  4464. static get type() {
  4465. return 'VarNode';
  4466. }
  4467. /**
  4468. * Constructs a new variable node.
  4469. *
  4470. * @param {Node} node - The node for which a variable should be created.
  4471. * @param {String?} name - The name of the variable in the shader.
  4472. * @param {Boolean?} readOnly - The read-only flag.
  4473. */
  4474. constructor( node, name = null, readOnly = false ) {
  4475. super();
  4476. /**
  4477. * The node for which a variable should be created.
  4478. *
  4479. * @type {Node}
  4480. */
  4481. this.node = node;
  4482. /**
  4483. * The name of the variable in the shader. If no name is defined,
  4484. * the node system auto-generates one.
  4485. *
  4486. * @type {String?}
  4487. * @default null
  4488. */
  4489. this.name = name;
  4490. /**
  4491. * `VarNode` sets this property to `true` by default.
  4492. *
  4493. * @type {Boolean}
  4494. * @default true
  4495. */
  4496. this.global = true;
  4497. /**
  4498. * This flag can be used for type testing.
  4499. *
  4500. * @type {Boolean}
  4501. * @readonly
  4502. * @default true
  4503. */
  4504. this.isVarNode = true;
  4505. /**
  4506. *
  4507. * The read-only flag.
  4508. *
  4509. * @type {Boolean}
  4510. * @default false
  4511. */
  4512. this.readOnly = readOnly;
  4513. }
  4514. getHash( builder ) {
  4515. return this.name || super.getHash( builder );
  4516. }
  4517. getNodeType( builder ) {
  4518. return this.node.getNodeType( builder );
  4519. }
  4520. generate( builder ) {
  4521. const { node, name, readOnly } = this;
  4522. const { renderer } = builder;
  4523. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  4524. let isDeterministic = false;
  4525. let shouldTreatAsReadOnly = false;
  4526. if ( readOnly ) {
  4527. isDeterministic = builder.isDeterministic( node );
  4528. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  4529. }
  4530. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  4531. const snippet = node.build( builder, vectorType );
  4532. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  4533. const propertyName = builder.getPropertyName( nodeVar );
  4534. let declarationPrefix = propertyName;
  4535. if ( shouldTreatAsReadOnly ) {
  4536. const type = builder.getType( nodeVar.type );
  4537. if ( isWebGPUBackend ) {
  4538. declarationPrefix = isDeterministic
  4539. ? `const ${ propertyName }`
  4540. : `let ${ propertyName }`;
  4541. } else {
  4542. declarationPrefix = `const ${ type } ${ propertyName }`;
  4543. }
  4544. }
  4545. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  4546. return propertyName;
  4547. }
  4548. }
  4549. /**
  4550. * TSL function for creating a var node.
  4551. *
  4552. * @function
  4553. * @param {Node} node - The node for which a variable should be created.
  4554. * @param {String?} name - The name of the variable in the shader.
  4555. * @returns {VarNode}
  4556. */
  4557. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4558. /**
  4559. * TSL function for creating a var node.
  4560. *
  4561. * @function
  4562. * @param {Node} node - The node for which a variable should be created.
  4563. * @param {String?} name - The name of the variable in the shader.
  4564. * @returns {VarNode}
  4565. */
  4566. const Var = ( node, name = null ) => createVar( node, name ).append();
  4567. /**
  4568. * TSL function for creating a const node.
  4569. *
  4570. * @function
  4571. * @param {Node} node - The node for which a constant should be created.
  4572. * @param {String?} name - The name of the constant in the shader.
  4573. * @returns {VarNode}
  4574. */
  4575. const Const = ( node, name = null ) => createVar( node, name, true ).append();
  4576. // Method chaining
  4577. addMethodChaining( 'toVar', Var );
  4578. addMethodChaining( 'toConst', Const );
  4579. // Deprecated
  4580. /**
  4581. * @function
  4582. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  4583. *
  4584. * @param {Any} node
  4585. * @returns {VarNode}
  4586. */
  4587. const temp = ( node ) => { // @deprecated, r170
  4588. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  4589. return createVar( node );
  4590. };
  4591. addMethodChaining( 'temp', temp );
  4592. /** @module VaryingNode **/
  4593. /**
  4594. * Class for representing shader varyings as nodes. Varyings are create from
  4595. * existing nodes like the following:
  4596. *
  4597. * ```js
  4598. * const positionLocal = positionGeometry.varying( 'vPositionLocal' );
  4599. * ```
  4600. *
  4601. * @augments Node
  4602. */
  4603. class VaryingNode extends Node {
  4604. static get type() {
  4605. return 'VaryingNode';
  4606. }
  4607. /**
  4608. * Constructs a new varying node.
  4609. *
  4610. * @param {Node} node - The node for which a varying should be created.
  4611. * @param {String?} name - The name of the varying in the shader.
  4612. */
  4613. constructor( node, name = null ) {
  4614. super();
  4615. /**
  4616. * The node for which a varying should be created.
  4617. *
  4618. * @type {Node}
  4619. */
  4620. this.node = node;
  4621. /**
  4622. * The name of the varying in the shader. If no name is defined,
  4623. * the node system auto-generates one.
  4624. *
  4625. * @type {String?}
  4626. * @default null
  4627. */
  4628. this.name = name;
  4629. /**
  4630. * This flag can be used for type testing.
  4631. *
  4632. * @type {Boolean}
  4633. * @readonly
  4634. * @default true
  4635. */
  4636. this.isVaryingNode = true;
  4637. }
  4638. /**
  4639. * The method is overwritten so it always returns `true`.
  4640. *
  4641. * @param {NodeBuilder} builder - The current node builder.
  4642. * @return {Boolean} Whether this node is global or not.
  4643. */
  4644. isGlobal( /*builder*/ ) {
  4645. return true;
  4646. }
  4647. getHash( builder ) {
  4648. return this.name || super.getHash( builder );
  4649. }
  4650. getNodeType( builder ) {
  4651. // VaryingNode is auto type
  4652. return this.node.getNodeType( builder );
  4653. }
  4654. /**
  4655. * This method performs the setup of a varying node with the current node builder.
  4656. *
  4657. * @param {NodeBuilder} builder - The current node builder.
  4658. * @return {NodeVarying} The node varying from the node builder.
  4659. */
  4660. setupVarying( builder ) {
  4661. const properties = builder.getNodeProperties( this );
  4662. let varying = properties.varying;
  4663. if ( varying === undefined ) {
  4664. const name = this.name;
  4665. const type = this.getNodeType( builder );
  4666. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  4667. properties.node = this.node;
  4668. }
  4669. // this property can be used to check if the varying can be optimized for a variable
  4670. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  4671. return varying;
  4672. }
  4673. setup( builder ) {
  4674. this.setupVarying( builder );
  4675. }
  4676. analyze( builder ) {
  4677. this.setupVarying( builder );
  4678. return this.node.analyze( builder );
  4679. }
  4680. generate( builder ) {
  4681. const properties = builder.getNodeProperties( this );
  4682. const varying = this.setupVarying( builder );
  4683. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  4684. if ( properties.propertyName === undefined || needsReassign ) {
  4685. const type = this.getNodeType( builder );
  4686. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  4687. // force node run in vertex stage
  4688. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  4689. properties.propertyName = propertyName;
  4690. if ( needsReassign ) {
  4691. // once reassign varying in fragment stage
  4692. properties.reassignPosition = false;
  4693. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  4694. properties.reassignPosition = true;
  4695. }
  4696. }
  4697. return builder.getPropertyName( varying );
  4698. }
  4699. }
  4700. /**
  4701. * TSL function for creating a varying node.
  4702. *
  4703. * @function
  4704. * @param {Node} node - The node for which a varying should be created.
  4705. * @param {String?} name - The name of the varying in the shader.
  4706. * @returns {VaryingNode}
  4707. */
  4708. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  4709. /**
  4710. * Computes a node in the vertex stage.
  4711. *
  4712. * @function
  4713. * @param {Node} node - The node which should be executed in the vertex stage.
  4714. * @returns {VaryingNode}
  4715. */
  4716. const vertexStage = ( node ) => varying( node );
  4717. addMethodChaining( 'varying', varying );
  4718. addMethodChaining( 'vertexStage', vertexStage );
  4719. /** @module ColorSpaceFunctions **/
  4720. /**
  4721. * Converts the given color value from sRGB to linear-sRGB color space.
  4722. *
  4723. * @method
  4724. * @param {Node<vec3>} color - The sRGB color.
  4725. * @return {Node<vec3>} The linear-sRGB color.
  4726. */
  4727. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4728. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  4729. const b = color.mul( 0.0773993808 );
  4730. const factor = color.lessThanEqual( 0.04045 );
  4731. const rgbResult = mix( a, b, factor );
  4732. return rgbResult;
  4733. } ).setLayout( {
  4734. name: 'sRGBTransferEOTF',
  4735. type: 'vec3',
  4736. inputs: [
  4737. { name: 'color', type: 'vec3' }
  4738. ]
  4739. } );
  4740. /**
  4741. * Converts the given color value from linear-sRGB to sRGB color space.
  4742. *
  4743. * @method
  4744. * @param {Node<vec3>} color - The linear-sRGB color.
  4745. * @return {Node<vec3>} The sRGB color.
  4746. */
  4747. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4748. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  4749. const b = color.mul( 12.92 );
  4750. const factor = color.lessThanEqual( 0.0031308 );
  4751. const rgbResult = mix( a, b, factor );
  4752. return rgbResult;
  4753. } ).setLayout( {
  4754. name: 'sRGBTransferOETF',
  4755. type: 'vec3',
  4756. inputs: [
  4757. { name: 'color', type: 'vec3' }
  4758. ]
  4759. } );
  4760. /** @module ColorSpaceNode **/
  4761. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  4762. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  4763. /**
  4764. * This node represents a color space conversion. Meaning it converts
  4765. * a color value from a source to a target color space.
  4766. *
  4767. * @augments TempNode
  4768. */
  4769. class ColorSpaceNode extends TempNode {
  4770. static get type() {
  4771. return 'ColorSpaceNode';
  4772. }
  4773. /**
  4774. * Constructs a new color space node.
  4775. *
  4776. * @param {Node} colorNode - Represents the color to convert.
  4777. * @param {String} source - The source color space.
  4778. * @param {String} target - The target color space.
  4779. */
  4780. constructor( colorNode, source, target ) {
  4781. super( 'vec4' );
  4782. /**
  4783. * Represents the color to convert.
  4784. *
  4785. * @type {Node}
  4786. */
  4787. this.colorNode = colorNode;
  4788. /**
  4789. * The source color space.
  4790. *
  4791. * @type {String}
  4792. */
  4793. this.source = source;
  4794. /**
  4795. * The target color space.
  4796. *
  4797. * @type {String}
  4798. */
  4799. this.target = target;
  4800. }
  4801. /**
  4802. * This method resolves the constants `WORKING_COLOR_SPACE` and
  4803. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  4804. * color management and renderer.
  4805. *
  4806. * @param {NodeBuilder} builder - The current node builder.
  4807. * @param {String} colorSpace - The color space to resolve.
  4808. * @return {String} The resolved color space.
  4809. */
  4810. resolveColorSpace( builder, colorSpace ) {
  4811. if ( colorSpace === WORKING_COLOR_SPACE ) {
  4812. return ColorManagement.workingColorSpace;
  4813. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  4814. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  4815. }
  4816. return colorSpace;
  4817. }
  4818. setup( builder ) {
  4819. const { colorNode } = this;
  4820. const source = this.resolveColorSpace( builder, this.source );
  4821. const target = this.resolveColorSpace( builder, this.target );
  4822. let outputNode = colorNode;
  4823. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  4824. return outputNode;
  4825. }
  4826. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  4827. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  4828. }
  4829. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  4830. outputNode = vec4(
  4831. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  4832. outputNode.a
  4833. );
  4834. }
  4835. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  4836. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  4837. }
  4838. return outputNode;
  4839. }
  4840. }
  4841. /**
  4842. * TSL function for converting a given color node to the current output color space.
  4843. *
  4844. * @function
  4845. * @param {Node} node - Represents the node to convert.
  4846. * @returns {ColorSpaceNode}
  4847. */
  4848. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  4849. /**
  4850. * TSL function for converting a given color node to the current working color space.
  4851. *
  4852. * @function
  4853. * @param {Node} node - Represents the node to convert.
  4854. * @returns {ColorSpaceNode}
  4855. */
  4856. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  4857. /**
  4858. * TSL function for converting a given color node from the current working color space to the given color space.
  4859. *
  4860. * @function
  4861. * @param {Node} node - Represents the node to convert.
  4862. * @param {String} colorSpace - The target color space.
  4863. * @returns {ColorSpaceNode}
  4864. */
  4865. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  4866. /**
  4867. * TSL function for converting a given color node from the given color space to the current working color space.
  4868. *
  4869. * @function
  4870. * @param {Node} node - Represents the node to convert.
  4871. * @param {String} colorSpace - The source color space.
  4872. * @returns {ColorSpaceNode}
  4873. */
  4874. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  4875. /**
  4876. * TSL function for converting a given color node from one color space to another one.
  4877. *
  4878. * @function
  4879. * @param {Node} node - Represents the node to convert.
  4880. * @param {String} sourceColorSpace - The source color space.
  4881. * @param {String} targetColorSpace - The target color space.
  4882. * @returns {ColorSpaceNode}
  4883. */
  4884. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  4885. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  4886. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  4887. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  4888. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  4889. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  4890. /** @module ReferenceBaseNode **/
  4891. /**
  4892. * This class is only relevant if the referenced property is array-like.
  4893. * In this case, `ReferenceElementNode` allows to refer to a specific
  4894. * element inside the data structure via an index.
  4895. *
  4896. * @augments ArrayElementNode
  4897. */
  4898. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  4899. static get type() {
  4900. return 'ReferenceElementNode';
  4901. }
  4902. /**
  4903. * Constructs a new reference element node.
  4904. *
  4905. * @param {Node?} referenceNode - The reference node.
  4906. * @param {Node} indexNode - The index node that defines the element access.
  4907. */
  4908. constructor( referenceNode, indexNode ) {
  4909. super( referenceNode, indexNode );
  4910. /**
  4911. * Similar to {@link module:ReferenceBaseNode~ReferenceBaseNode#reference}, an additional
  4912. * property references to the current node.
  4913. *
  4914. * @type {Node?}
  4915. * @default null
  4916. */
  4917. this.referenceNode = referenceNode;
  4918. /**
  4919. * This flag can be used for type testing.
  4920. *
  4921. * @type {Boolean}
  4922. * @readonly
  4923. * @default true
  4924. */
  4925. this.isReferenceElementNode = true;
  4926. }
  4927. /**
  4928. * This method is overwritten since the node type is inferred from
  4929. * the uniform type of the reference node.
  4930. *
  4931. * @param {NodeBuilder} builder - The current node builder.
  4932. * @return {String} The node type.
  4933. */
  4934. getNodeType() {
  4935. return this.referenceNode.uniformType;
  4936. }
  4937. generate( builder ) {
  4938. const snippet = super.generate( builder );
  4939. const arrayType = this.referenceNode.getNodeType();
  4940. const elementType = this.getNodeType();
  4941. return builder.format( snippet, arrayType, elementType );
  4942. }
  4943. };
  4944. /**
  4945. * Base class for nodes which establishes a reference to a property of another object.
  4946. * In this way, the value of the node is automatically linked to the value of
  4947. * referenced object. Reference nodes internally represent the linked value
  4948. * as a uniform.
  4949. *
  4950. * @augments Node
  4951. */
  4952. class ReferenceBaseNode extends Node {
  4953. static get type() {
  4954. return 'ReferenceBaseNode';
  4955. }
  4956. /**
  4957. * Constructs a new reference base node.
  4958. *
  4959. * @param {String} property - The name of the property the node refers to.
  4960. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  4961. * @param {Object?} [object=null] - The object the property belongs to.
  4962. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  4963. */
  4964. constructor( property, uniformType, object = null, count = null ) {
  4965. super();
  4966. /**
  4967. * The name of the property the node refers to.
  4968. *
  4969. * @type {String}
  4970. */
  4971. this.property = property;
  4972. /**
  4973. * The uniform type that should be used to represent the property value.
  4974. *
  4975. * @type {String}
  4976. */
  4977. this.uniformType = uniformType;
  4978. /**
  4979. * The object the property belongs to.
  4980. *
  4981. * @type {Object?}
  4982. * @default null
  4983. */
  4984. this.object = object;
  4985. /**
  4986. * When the linked property is an array, this parameter defines its length.
  4987. *
  4988. * @type {Number?}
  4989. * @default null
  4990. */
  4991. this.count = count;
  4992. /**
  4993. * The property name might have dots so nested properties can be referred.
  4994. * The hierarchy of the names is stored inside this array.
  4995. *
  4996. * @type {Array<String>}
  4997. */
  4998. this.properties = property.split( '.' );
  4999. /**
  5000. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  5001. * since the final reference might be updated from calling code.
  5002. *
  5003. * @type {Object?}
  5004. * @default null
  5005. */
  5006. this.reference = object;
  5007. /**
  5008. * The uniform node that holds the value of the reference node.
  5009. *
  5010. * @type {UniformNode}
  5011. * @default null
  5012. */
  5013. this.node = null;
  5014. /**
  5015. * The uniform group of the internal uniform.
  5016. *
  5017. * @type {UniformGroupNode}
  5018. * @default null
  5019. */
  5020. this.group = null;
  5021. /**
  5022. * Overwritten since reference nodes are updated per object.
  5023. *
  5024. * @type {String}
  5025. * @default 'object'
  5026. */
  5027. this.updateType = NodeUpdateType.OBJECT;
  5028. }
  5029. /**
  5030. * Sets the uniform group for this reference node.
  5031. *
  5032. * @param {UniformGroupNode} group - The uniform group to set.
  5033. * @return {ReferenceBaseNode} A reference to this node.
  5034. */
  5035. setGroup( group ) {
  5036. this.group = group;
  5037. return this;
  5038. }
  5039. /**
  5040. * When the referred property is array-like, this method can be used
  5041. * to access elements via an index node.
  5042. *
  5043. * @param {IndexNode} indexNode - indexNode.
  5044. * @return {ReferenceElementNode} A reference to an element.
  5045. */
  5046. element( indexNode ) {
  5047. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5048. }
  5049. /**
  5050. * Sets the node type which automatically defines the internal
  5051. * uniform type.
  5052. *
  5053. * @param {String} uniformType - The type to set.
  5054. */
  5055. setNodeType( uniformType ) {
  5056. const node = uniform( null, uniformType ).getSelf();
  5057. if ( this.group !== null ) {
  5058. node.setGroup( this.group );
  5059. }
  5060. this.node = node;
  5061. }
  5062. /**
  5063. * This method is overwritten since the node type is inferred from
  5064. * the type of the reference node.
  5065. *
  5066. * @param {NodeBuilder} builder - The current node builder.
  5067. * @return {String} The node type.
  5068. */
  5069. getNodeType( builder ) {
  5070. if ( this.node === null ) {
  5071. this.updateReference( builder );
  5072. this.updateValue();
  5073. }
  5074. return this.node.getNodeType( builder );
  5075. }
  5076. /**
  5077. * Returns the property value from the given referred object.
  5078. *
  5079. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5080. * @return {Any} The value.
  5081. */
  5082. getValueFromReference( object = this.reference ) {
  5083. const { properties } = this;
  5084. let value = object[ properties[ 0 ] ];
  5085. for ( let i = 1; i < properties.length; i ++ ) {
  5086. value = value[ properties[ i ] ];
  5087. }
  5088. return value;
  5089. }
  5090. /**
  5091. * Allows to update the reference based on the given state. The state is only
  5092. * evaluated {@link module:ReferenceBaseNode~ReferenceBaseNode#object} is not set.
  5093. *
  5094. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5095. * @return {Object} The updated reference.
  5096. */
  5097. updateReference( state ) {
  5098. this.reference = this.object !== null ? this.object : state.object;
  5099. return this.reference;
  5100. }
  5101. /**
  5102. * The output of the reference node is the internal uniform node.
  5103. *
  5104. * @param {NodeBuilder} builder - The current node builder.
  5105. * @return {UniformNode} The output node.
  5106. */
  5107. setup() {
  5108. this.updateValue();
  5109. return this.node;
  5110. }
  5111. /**
  5112. * Overwritten to to update the internal uniform value.
  5113. *
  5114. * @param {NodeFrame} frame - A reference to the current node frame.
  5115. */
  5116. update( /*frame*/ ) {
  5117. this.updateValue();
  5118. }
  5119. /**
  5120. * Retrieves the value from the referred object property and uses it
  5121. * to updated the internal uniform.
  5122. */
  5123. updateValue() {
  5124. if ( this.node === null ) this.setNodeType( this.uniformType );
  5125. const value = this.getValueFromReference();
  5126. if ( Array.isArray( value ) ) {
  5127. this.node.array = value;
  5128. } else {
  5129. this.node.value = value;
  5130. }
  5131. }
  5132. }
  5133. /**
  5134. * TSL function for creating a reference base node.
  5135. *
  5136. * @function
  5137. * @param {String} name - The name of the property the node refers to.
  5138. * @param {String} type - The uniform type that should be used to represent the property value.
  5139. * @param {Object} object - The object the property belongs to.
  5140. * @returns {ReferenceBaseNode}
  5141. */
  5142. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5143. /** @module RendererReferenceNode **/
  5144. /**
  5145. * This node is a special type of reference node which is intended
  5146. * for linking renderer properties with node values.
  5147. * ```js
  5148. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5149. * ```
  5150. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5151. * automatically be updated.
  5152. *
  5153. * @augments ReferenceBaseNode
  5154. */
  5155. class RendererReferenceNode extends ReferenceBaseNode {
  5156. static get type() {
  5157. return 'RendererReferenceNode';
  5158. }
  5159. /**
  5160. * Constructs a new renderer reference node.
  5161. *
  5162. * @param {String} property - The name of the property the node refers to.
  5163. * @param {String} inputType - The uniform type that should be used to represent the property value.
  5164. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5165. * the node refers to the renderer of the current state.
  5166. */
  5167. constructor( property, inputType, renderer = null ) {
  5168. super( property, inputType, renderer );
  5169. /**
  5170. * The renderer the property belongs to. When no renderer is set,
  5171. * the node refers to the renderer of the current state.
  5172. *
  5173. * @type {Renderer?}
  5174. * @default null
  5175. */
  5176. this.renderer = renderer;
  5177. this.setGroup( renderGroup );
  5178. }
  5179. /**
  5180. * Updates the reference based on the given state. The state is only evaluated
  5181. * {@link module:RendererReferenceNode~RendererReferenceNode#renderer} is not set.
  5182. *
  5183. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5184. * @return {Object} The updated reference.
  5185. */
  5186. updateReference( state ) {
  5187. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5188. return this.reference;
  5189. }
  5190. }
  5191. /**
  5192. * TSL function for creating a renderer reference node.
  5193. *
  5194. * @function
  5195. * @param {String} name - The name of the property the node refers to.
  5196. * @param {String} type - The uniform type that should be used to represent the property value.
  5197. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5198. * the node refers to the renderer of the current state.
  5199. * @returns {RendererReferenceNode}
  5200. */
  5201. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5202. /** @module ToneMappingNode **/
  5203. /**
  5204. * This node represents a tone mapping operation.
  5205. *
  5206. * @augments TempNode
  5207. */
  5208. class ToneMappingNode extends TempNode {
  5209. static get type() {
  5210. return 'ToneMappingNode';
  5211. }
  5212. /**
  5213. * Constructs a new tone mapping node.
  5214. *
  5215. * @param {Number} toneMapping - The tone mapping type.
  5216. * @param {Node} exposureNode - The tone mapping exposure.
  5217. * @param {Node} [colorNode=null] - The color node to process.
  5218. */
  5219. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5220. super( 'vec3' );
  5221. /**
  5222. * The tone mapping type.
  5223. *
  5224. * @type {Number}
  5225. */
  5226. this.toneMapping = toneMapping;
  5227. /**
  5228. * The tone mapping exposure.
  5229. *
  5230. * @type {Node}
  5231. * @default null
  5232. */
  5233. this.exposureNode = exposureNode;
  5234. /**
  5235. * Represents the color to process.
  5236. *
  5237. * @type {Node?}
  5238. * @default null
  5239. */
  5240. this.colorNode = colorNode;
  5241. }
  5242. /**
  5243. * Overwrites the default `customCacheKey()` implementation by including the tone
  5244. * mapping type into the cache key.
  5245. *
  5246. * @return {Number} The hash.
  5247. */
  5248. customCacheKey() {
  5249. return hash$1( this.toneMapping );
  5250. }
  5251. setup( builder ) {
  5252. const colorNode = this.colorNode || builder.context.color;
  5253. const toneMapping = this.toneMapping;
  5254. if ( toneMapping === NoToneMapping ) return colorNode;
  5255. let outputNode = null;
  5256. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5257. if ( toneMappingFn !== null ) {
  5258. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5259. } else {
  5260. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5261. outputNode = colorNode;
  5262. }
  5263. return outputNode;
  5264. }
  5265. }
  5266. /**
  5267. * TSL function for creating a tone mapping node.
  5268. *
  5269. * @function
  5270. * @param {Number} mapping - The tone mapping type.
  5271. * @param {Node<float> | Number} exposure - The tone mapping exposure.
  5272. * @param {Node<vec3> | Color} color - The color node to process.
  5273. * @returns {ToneMappingNode<vec3>}
  5274. */
  5275. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5276. /**
  5277. * TSL object that represents the global tone mapping exposure of the renderer.
  5278. *
  5279. * @type {RendererReferenceNode<vec3>}
  5280. */
  5281. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5282. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5283. /** @module BufferAttributeNode **/
  5284. /**
  5285. * In earlier `three.js` versions it was only possible to define attribute data
  5286. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5287. * on the node level.
  5288. * ```js
  5289. * const geometry = new THREE.PlaneGeometry();
  5290. * const positionAttribute = geometry.getAttribute( 'position' );
  5291. *
  5292. * const colors = [];
  5293. * for ( let i = 0; i < position.count; i ++ ) {
  5294. * colors.push( 1, 0, 0 );
  5295. * }
  5296. *
  5297. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5298. * ```
  5299. * This new approach is especially interesting when geometry data are generated via
  5300. * compute shaders. The below line converts a storage buffer into an attribute node.
  5301. * ```js
  5302. * material.positionNode = positionBuffer.toAttribute();
  5303. * ```
  5304. * @augments InputNode
  5305. */
  5306. class BufferAttributeNode extends InputNode {
  5307. static get type() {
  5308. return 'BufferAttributeNode';
  5309. }
  5310. /**
  5311. * Constructs a new buffer attribute node.
  5312. *
  5313. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5314. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5315. * @param {Number} [bufferStride=0] - The buffer stride.
  5316. * @param {Number} [bufferOffset=0] - The buffer offset.
  5317. */
  5318. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5319. super( value, bufferType );
  5320. /**
  5321. * This flag can be used for type testing.
  5322. *
  5323. * @type {Boolean}
  5324. * @readonly
  5325. * @default true
  5326. */
  5327. this.isBufferNode = true;
  5328. /**
  5329. * The buffer type (e.g. `'vec3'`).
  5330. *
  5331. * @type {String}
  5332. * @default null
  5333. */
  5334. this.bufferType = bufferType;
  5335. /**
  5336. * The buffer stride.
  5337. *
  5338. * @type {Number}
  5339. * @default 0
  5340. */
  5341. this.bufferStride = bufferStride;
  5342. /**
  5343. * The buffer offset.
  5344. *
  5345. * @type {Number}
  5346. * @default 0
  5347. */
  5348. this.bufferOffset = bufferOffset;
  5349. /**
  5350. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5351. * if you are planning to update the attribute data per frame.
  5352. *
  5353. * @type {Number}
  5354. * @default StaticDrawUsage
  5355. */
  5356. this.usage = StaticDrawUsage;
  5357. /**
  5358. * Whether the attribute is instanced or not.
  5359. *
  5360. * @type {Boolean}
  5361. * @default false
  5362. */
  5363. this.instanced = false;
  5364. /**
  5365. * A reference to the buffer attribute.
  5366. *
  5367. * @type {BufferAttribute?}
  5368. * @default null
  5369. */
  5370. this.attribute = null;
  5371. /**
  5372. * `BufferAttributeNode` sets this property to `true` by default.
  5373. *
  5374. * @type {Boolean}
  5375. * @default true
  5376. */
  5377. this.global = true;
  5378. if ( value && value.isBufferAttribute === true ) {
  5379. this.attribute = value;
  5380. this.usage = value.usage;
  5381. this.instanced = value.isInstancedBufferAttribute;
  5382. }
  5383. }
  5384. /**
  5385. * This method is overwritten since the attribute data might be shared
  5386. * and thus the hash should be shared as well.
  5387. *
  5388. * @param {NodeBuilder} builder - The current node builder.
  5389. * @return {String} The hash.
  5390. */
  5391. getHash( builder ) {
  5392. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5393. let bufferData = builder.globalCache.getData( this.value );
  5394. if ( bufferData === undefined ) {
  5395. bufferData = {
  5396. node: this
  5397. };
  5398. builder.globalCache.setData( this.value, bufferData );
  5399. }
  5400. return bufferData.node.uuid;
  5401. }
  5402. return this.uuid;
  5403. }
  5404. /**
  5405. * This method is overwritten since the node type is inferred from
  5406. * the buffer attribute.
  5407. *
  5408. * @param {NodeBuilder} builder - The current node builder.
  5409. * @return {String} The node type.
  5410. */
  5411. getNodeType( builder ) {
  5412. if ( this.bufferType === null ) {
  5413. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5414. }
  5415. return this.bufferType;
  5416. }
  5417. /**
  5418. * Depending on which value was passed to the node, `setup()` behaves
  5419. * differently. If no instance of `BufferAttribute` was passed, the method
  5420. * creates an internal attribute and configures it respectively.
  5421. *
  5422. * @param {NodeBuilder} builder - The current node builder.
  5423. */
  5424. setup( builder ) {
  5425. if ( this.attribute !== null ) return;
  5426. const type = this.getNodeType( builder );
  5427. const array = this.value;
  5428. const itemSize = builder.getTypeLength( type );
  5429. const stride = this.bufferStride || itemSize;
  5430. const offset = this.bufferOffset;
  5431. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5432. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5433. buffer.setUsage( this.usage );
  5434. this.attribute = bufferAttribute;
  5435. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5436. }
  5437. /**
  5438. * Generates the code snippet of the buffer attribute node.
  5439. *
  5440. * @param {NodeBuilder} builder - The current node builder.
  5441. * @return {String} The generated code snippet.
  5442. */
  5443. generate( builder ) {
  5444. const nodeType = this.getNodeType( builder );
  5445. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5446. const propertyName = builder.getPropertyName( nodeAttribute );
  5447. let output = null;
  5448. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5449. this.name = propertyName;
  5450. output = propertyName;
  5451. } else {
  5452. const nodeVarying = varying( this );
  5453. output = nodeVarying.build( builder, nodeType );
  5454. }
  5455. return output;
  5456. }
  5457. /**
  5458. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5459. *
  5460. * @param {NodeBuilder} builder - The current node builder.
  5461. * @return {String} The input type.
  5462. */
  5463. getInputType( /*builder*/ ) {
  5464. return 'bufferAttribute';
  5465. }
  5466. /**
  5467. * Sets the `usage` property to the given value.
  5468. *
  5469. * @param {Number} value - The usage to set.
  5470. * @return {BufferAttributeNode} A reference to this node.
  5471. */
  5472. setUsage( value ) {
  5473. this.usage = value;
  5474. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5475. this.attribute.usage = value;
  5476. }
  5477. return this;
  5478. }
  5479. /**
  5480. * Sets the `instanced` property to the given value.
  5481. *
  5482. * @param {Number} value - The value to set.
  5483. * @return {BufferAttributeNode} A reference to this node.
  5484. */
  5485. setInstanced( value ) {
  5486. this.instanced = value;
  5487. return this;
  5488. }
  5489. }
  5490. /**
  5491. * TSL function for creating a buffer attribute node.
  5492. *
  5493. * @function
  5494. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5495. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5496. * @param {Number} [stride=0] - The buffer stride.
  5497. * @param {Number} [offset=0] - The buffer offset.
  5498. * @returns {BufferAttributeNode}
  5499. */
  5500. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5501. /**
  5502. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5503. * Use this function if attribute data are updated per frame.
  5504. *
  5505. * @function
  5506. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5507. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5508. * @param {Number} [stride=0] - The buffer stride.
  5509. * @param {Number} [offset=0] - The buffer offset.
  5510. * @returns {BufferAttributeNode}
  5511. */
  5512. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5513. /**
  5514. * TSL function for creating a buffer attribute node but with enabled instancing
  5515. *
  5516. * @function
  5517. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5518. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5519. * @param {Number} [stride=0] - The buffer stride.
  5520. * @param {Number} [offset=0] - The buffer offset.
  5521. * @returns {BufferAttributeNode}
  5522. */
  5523. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5524. /**
  5525. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5526. *
  5527. * @function
  5528. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5529. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5530. * @param {Number} [stride=0] - The buffer stride.
  5531. * @param {Number} [offset=0] - The buffer offset.
  5532. * @returns {BufferAttributeNode}
  5533. */
  5534. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5535. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5536. /** @module ComputeNode **/
  5537. /**
  5538. * TODO
  5539. *
  5540. * @augments Node
  5541. */
  5542. class ComputeNode extends Node {
  5543. static get type() {
  5544. return 'ComputeNode';
  5545. }
  5546. /**
  5547. * Constructs a new compute node.
  5548. *
  5549. * @param {Node} computeNode - TODO
  5550. * @param {Number} count - TODO.
  5551. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5552. */
  5553. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5554. super( 'void' );
  5555. /**
  5556. * This flag can be used for type testing.
  5557. *
  5558. * @type {Boolean}
  5559. * @readonly
  5560. * @default true
  5561. */
  5562. this.isComputeNode = true;
  5563. /**
  5564. * TODO
  5565. *
  5566. * @type {Node}
  5567. */
  5568. this.computeNode = computeNode;
  5569. /**
  5570. * TODO
  5571. *
  5572. * @type {Number}
  5573. */
  5574. this.count = count;
  5575. /**
  5576. * TODO
  5577. *
  5578. * @type {Array<Number>}
  5579. * @default [64]
  5580. */
  5581. this.workgroupSize = workgroupSize;
  5582. /**
  5583. * TODO
  5584. *
  5585. * @type {Number}
  5586. */
  5587. this.dispatchCount = 0;
  5588. /**
  5589. * TODO
  5590. *
  5591. * @type {Number}
  5592. */
  5593. this.version = 1;
  5594. /**
  5595. * The name or label of the uniform.
  5596. *
  5597. * @type {String}
  5598. * @default ''
  5599. */
  5600. this.name = '';
  5601. /**
  5602. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5603. * is executed once per object by default.
  5604. *
  5605. * @type {String}
  5606. * @default 'object'
  5607. */
  5608. this.updateBeforeType = NodeUpdateType.OBJECT;
  5609. /**
  5610. * TODO
  5611. *
  5612. * @type {Function}
  5613. */
  5614. this.onInitFunction = null;
  5615. this.updateDispatchCount();
  5616. }
  5617. /**
  5618. * Executes the `dispose` event for this node.
  5619. */
  5620. dispose() {
  5621. this.dispatchEvent( { type: 'dispose' } );
  5622. }
  5623. /**
  5624. * Sets the {@link ComputeNode#name} property.
  5625. *
  5626. * @param {String} name - The name of the uniform.
  5627. * @return {ComputeNode} A reference to this node.
  5628. */
  5629. label( name ) {
  5630. this.name = name;
  5631. return this;
  5632. }
  5633. /**
  5634. * TODO
  5635. */
  5636. updateDispatchCount() {
  5637. const { count, workgroupSize } = this;
  5638. let size = workgroupSize[ 0 ];
  5639. for ( let i = 1; i < workgroupSize.length; i ++ )
  5640. size *= workgroupSize[ i ];
  5641. this.dispatchCount = Math.ceil( count / size );
  5642. }
  5643. /**
  5644. * TODO
  5645. *
  5646. * @param {Function} callback - TODO.
  5647. * @return {ComputeNode} A reference to this node.
  5648. */
  5649. onInit( callback ) {
  5650. this.onInitFunction = callback;
  5651. return this;
  5652. }
  5653. /**
  5654. * The method execute the compute for this node.
  5655. *
  5656. * @param {NodeFrame} frame - A reference to the current node frame.
  5657. */
  5658. updateBefore( { renderer } ) {
  5659. renderer.compute( this );
  5660. }
  5661. generate( builder ) {
  5662. const { shaderStage } = builder;
  5663. if ( shaderStage === 'compute' ) {
  5664. const snippet = this.computeNode.build( builder, 'void' );
  5665. if ( snippet !== '' ) {
  5666. builder.addLineFlowCode( snippet, this );
  5667. }
  5668. }
  5669. }
  5670. }
  5671. /**
  5672. * TSL function for creating a compute node.
  5673. *
  5674. * @function
  5675. * @param {Node} node - TODO
  5676. * @param {Number} count - TODO.
  5677. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5678. * @returns {AtomicFunctionNode}
  5679. */
  5680. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  5681. addMethodChaining( 'compute', compute );
  5682. /** @module CacheNode **/
  5683. /**
  5684. * This node can be used as a cache management component for another node.
  5685. * Caching is in general used by default in {@link NodeBuilder} but this node
  5686. * allows the usage of a shared parent cache during the build process.
  5687. *
  5688. * @augments Node
  5689. */
  5690. class CacheNode extends Node {
  5691. static get type() {
  5692. return 'CacheNode';
  5693. }
  5694. /**
  5695. * Constructs a new cache node.
  5696. *
  5697. * @param {Node} node - The node that should be cached.
  5698. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  5699. */
  5700. constructor( node, parent = true ) {
  5701. super();
  5702. /**
  5703. * The node that should be cached.
  5704. *
  5705. * @type {Node}
  5706. */
  5707. this.node = node;
  5708. /**
  5709. * Whether this node refers to a shared parent cache or not.
  5710. *
  5711. * @type {Boolean}
  5712. * @default true
  5713. */
  5714. this.parent = parent;
  5715. /**
  5716. * This flag can be used for type testing.
  5717. *
  5718. * @type {Boolean}
  5719. * @readonly
  5720. * @default true
  5721. */
  5722. this.isCacheNode = true;
  5723. }
  5724. getNodeType( builder ) {
  5725. const previousCache = builder.getCache();
  5726. const cache = builder.getCacheFromNode( this, this.parent );
  5727. builder.setCache( cache );
  5728. const nodeType = this.node.getNodeType( builder );
  5729. builder.setCache( previousCache );
  5730. return nodeType;
  5731. }
  5732. build( builder, ...params ) {
  5733. const previousCache = builder.getCache();
  5734. const cache = builder.getCacheFromNode( this, this.parent );
  5735. builder.setCache( cache );
  5736. const data = this.node.build( builder, ...params );
  5737. builder.setCache( previousCache );
  5738. return data;
  5739. }
  5740. }
  5741. /**
  5742. * TSL function for creating a cache node.
  5743. *
  5744. * @function
  5745. * @param {Node} node - The node that should be cached.
  5746. * @param {Boolean} parent - Whether this node refers to a shared parent cache or not.
  5747. * @returns {CacheNode}
  5748. */
  5749. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  5750. addMethodChaining( 'cache', cache );
  5751. /** @module BypassNode **/
  5752. /**
  5753. * The class generates the code of a given node but returns another node in the output.
  5754. * This can be used to call a method or node that does not return a value, i.e.
  5755. * type `void` on an input where returning a value is required. Example:
  5756. *
  5757. * ```js
  5758. * material.colorNode = myColor.bypass( runVoidFn() )
  5759. *```
  5760. *
  5761. * @augments Node
  5762. */
  5763. class BypassNode extends Node {
  5764. static get type() {
  5765. return 'BypassNode';
  5766. }
  5767. /**
  5768. * Constructs a new bypass node.
  5769. *
  5770. * @param {Node} outputNode - The output node.
  5771. * @param {Node} callNode - The call node.
  5772. */
  5773. constructor( outputNode, callNode ) {
  5774. super();
  5775. /**
  5776. * This flag can be used for type testing.
  5777. *
  5778. * @type {Boolean}
  5779. * @readonly
  5780. * @default true
  5781. */
  5782. this.isBypassNode = true;
  5783. /**
  5784. * The output node.
  5785. *
  5786. * @type {Node}
  5787. */
  5788. this.outputNode = outputNode;
  5789. /**
  5790. * The call node.
  5791. *
  5792. * @type {Node}
  5793. */
  5794. this.callNode = callNode;
  5795. }
  5796. getNodeType( builder ) {
  5797. return this.outputNode.getNodeType( builder );
  5798. }
  5799. generate( builder ) {
  5800. const snippet = this.callNode.build( builder, 'void' );
  5801. if ( snippet !== '' ) {
  5802. builder.addLineFlowCode( snippet, this );
  5803. }
  5804. return this.outputNode.build( builder );
  5805. }
  5806. }
  5807. /**
  5808. * TSL function for creating a bypass node.
  5809. *
  5810. * @function
  5811. * @param {Node} outputNode - The output node.
  5812. * @param {Node} callNode - The call node.
  5813. * @returns {BypassNode}
  5814. */
  5815. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  5816. addMethodChaining( 'bypass', bypass );
  5817. /** @module RemapNode **/
  5818. /**
  5819. * This node allows to remap a node value from one range into another. E.g a value of
  5820. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  5821. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  5822. *
  5823. * @augments Node
  5824. */
  5825. class RemapNode extends Node {
  5826. static get type() {
  5827. return 'RemapNode';
  5828. }
  5829. /**
  5830. * Constructs a new remap node.
  5831. *
  5832. * @param {Node} node - The node that should be remapped.
  5833. * @param {Node} inLowNode - The source or current lower bound of the range.
  5834. * @param {Node} inHighNode - The source or current upper bound of the range.
  5835. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5836. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5837. */
  5838. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  5839. super();
  5840. /**
  5841. * The node that should be remapped.
  5842. *
  5843. * @type {Node}
  5844. */
  5845. this.node = node;
  5846. /**
  5847. * The source or current lower bound of the range.
  5848. *
  5849. * @type {Node}
  5850. */
  5851. this.inLowNode = inLowNode;
  5852. /**
  5853. * The source or current upper bound of the range.
  5854. *
  5855. * @type {Node}
  5856. */
  5857. this.inHighNode = inHighNode;
  5858. /**
  5859. * The target lower bound of the range.
  5860. *
  5861. * @type {Node}
  5862. * @default float(0)
  5863. */
  5864. this.outLowNode = outLowNode;
  5865. /**
  5866. * The target upper bound of the range.
  5867. *
  5868. * @type {Node}
  5869. * @default float(1)
  5870. */
  5871. this.outHighNode = outHighNode;
  5872. /**
  5873. * Whether the node value should be clamped before
  5874. * remapping it to the target range.
  5875. *
  5876. * @type {Boolean}
  5877. * @default true
  5878. */
  5879. this.doClamp = true;
  5880. }
  5881. setup() {
  5882. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  5883. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  5884. if ( doClamp === true ) t = t.clamp();
  5885. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  5886. }
  5887. }
  5888. /**
  5889. * TSL function for creating a remap node.
  5890. *
  5891. * @function
  5892. * @param {Node} node - The node that should be remapped.
  5893. * @param {Node} inLowNode - The source or current lower bound of the range.
  5894. * @param {Node} inHighNode - The source or current upper bound of the range.
  5895. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5896. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5897. * @returns {RemapNode}
  5898. */
  5899. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  5900. /**
  5901. * TSL function for creating a remap node, but with enabled clamping.
  5902. *
  5903. * @function
  5904. * @param {Node} node - The node that should be remapped.
  5905. * @param {Node} inLowNode - The source or current lower bound of the range.
  5906. * @param {Node} inHighNode - The source or current upper bound of the range.
  5907. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5908. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5909. * @returns {RemapNode}
  5910. */
  5911. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  5912. addMethodChaining( 'remap', remap );
  5913. addMethodChaining( 'remapClamp', remapClamp );
  5914. /** @module ExpressionNode **/
  5915. /**
  5916. * This class can be used to implement basic expressions in shader code.
  5917. * Basic examples for that are `return`, `continue` or `discard` statements.
  5918. *
  5919. * @augments Node
  5920. */
  5921. class ExpressionNode extends Node {
  5922. static get type() {
  5923. return 'ExpressionNode';
  5924. }
  5925. /**
  5926. * Constructs a new expression node.
  5927. *
  5928. * @param {String} [snippet=''] - The native code snippet.
  5929. * @param {String} [nodeType='void'] - The node type.
  5930. */
  5931. constructor( snippet = '', nodeType = 'void' ) {
  5932. super( nodeType );
  5933. /**
  5934. * The native code snippet.
  5935. *
  5936. * @type {String}
  5937. * @default ''
  5938. */
  5939. this.snippet = snippet;
  5940. }
  5941. generate( builder, output ) {
  5942. const type = this.getNodeType( builder );
  5943. const snippet = this.snippet;
  5944. if ( type === 'void' ) {
  5945. builder.addLineFlowCode( snippet, this );
  5946. } else {
  5947. return builder.format( `( ${ snippet } )`, type, output );
  5948. }
  5949. }
  5950. }
  5951. /**
  5952. * TSL function for creating an expression node.
  5953. *
  5954. * @function
  5955. * @param {String} [snippet=''] - The native code snippet.
  5956. * @param {String} [nodeType='void'] - The node type.
  5957. * @returns {ExpressionNode}
  5958. */
  5959. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  5960. /** @module Discard **/
  5961. /**
  5962. * Represents a `discard` shader operation in TSL.
  5963. *
  5964. * @method
  5965. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  5966. * @return {Node} The `discard` expression.
  5967. */
  5968. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  5969. /**
  5970. * Represents a `return` shader operation in TSL.
  5971. *
  5972. * @method
  5973. * @return {ExpressionNode} The `return` expression.
  5974. */
  5975. const Return = () => expression( 'return' ).append();
  5976. addMethodChaining( 'discard', Discard );
  5977. /** @module RenderOutputNode **/
  5978. /**
  5979. * Normally, tone mapping and color conversion happens automatically
  5980. * before outputting pixel too the default (screen) framebuffer. In certain
  5981. * post processing setups this happens to late because certain effects
  5982. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  5983. * to apply tone mapping and color space conversion at an arbitrary point
  5984. * in the effect chain.
  5985. *
  5986. * When applying tone mapping and color space conversion manually with this node,
  5987. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  5988. *
  5989. * ```js
  5990. * const postProcessing = new PostProcessing( renderer );
  5991. * postProcessing.outputColorTransform = false;
  5992. *
  5993. * const scenePass = pass( scene, camera );
  5994. * const outputPass = renderOutput( scenePass );
  5995. *
  5996. * postProcessing.outputNode = outputPass;
  5997. * ```
  5998. *
  5999. * @augments TempNode
  6000. */
  6001. class RenderOutputNode extends TempNode {
  6002. static get type() {
  6003. return 'RenderOutputNode';
  6004. }
  6005. /**
  6006. * Constructs a new render output node.
  6007. *
  6008. * @param {Node} colorNode - The color node to process.
  6009. * @param {Number} toneMapping - The tone mapping type.
  6010. * @param {String} outputColorSpace - The output color space.
  6011. */
  6012. constructor( colorNode, toneMapping, outputColorSpace ) {
  6013. super( 'vec4' );
  6014. /**
  6015. * The color node to process.
  6016. *
  6017. * @type {Node}
  6018. */
  6019. this.colorNode = colorNode;
  6020. /**
  6021. * The tone mapping type.
  6022. *
  6023. * @type {Number?}
  6024. */
  6025. this.toneMapping = toneMapping;
  6026. /**
  6027. * The output color space.
  6028. *
  6029. * @type {String?}
  6030. */
  6031. this.outputColorSpace = outputColorSpace;
  6032. /**
  6033. * This flag can be used for type testing.
  6034. *
  6035. * @type {Boolean}
  6036. * @readonly
  6037. * @default true
  6038. */
  6039. this.isRenderOutputNode = true;
  6040. }
  6041. setup( { context } ) {
  6042. let outputNode = this.colorNode || context.color;
  6043. // tone mapping
  6044. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6045. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6046. if ( toneMapping !== NoToneMapping ) {
  6047. outputNode = outputNode.toneMapping( toneMapping );
  6048. }
  6049. // working to output color space
  6050. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6051. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6052. }
  6053. return outputNode;
  6054. }
  6055. }
  6056. /**
  6057. * TSL function for creating a posterize node.
  6058. *
  6059. * @function
  6060. * @param {Node} color - The color node to process.
  6061. * @param {Number?} [toneMapping=null] - The tone mapping type.
  6062. * @param {String?} [outputColorSpace=null] - The output color space.
  6063. * @returns {RenderOutputNode}
  6064. */
  6065. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6066. addMethodChaining( 'renderOutput', renderOutput );
  6067. // Non-PURE exports list, side-effects are required here.
  6068. // TSL Base Syntax
  6069. function addNodeElement( name/*, nodeElement*/ ) {
  6070. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6071. }
  6072. /** @module AttributeNode **/
  6073. /**
  6074. * Base class for representing shader attributes as nodes.
  6075. *
  6076. * @augments Node
  6077. */
  6078. class AttributeNode extends Node {
  6079. static get type() {
  6080. return 'AttributeNode';
  6081. }
  6082. /**
  6083. * Constructs a new attribute node.
  6084. *
  6085. * @param {String} attributeName - The name of the attribute.
  6086. * @param {String?} nodeType - The node type.
  6087. */
  6088. constructor( attributeName, nodeType = null ) {
  6089. super( nodeType );
  6090. /**
  6091. * `AttributeNode` sets this property to `true` by default.
  6092. *
  6093. * @type {Boolean}
  6094. * @default true
  6095. */
  6096. this.global = true;
  6097. this._attributeName = attributeName;
  6098. }
  6099. getHash( builder ) {
  6100. return this.getAttributeName( builder );
  6101. }
  6102. getNodeType( builder ) {
  6103. let nodeType = this.nodeType;
  6104. if ( nodeType === null ) {
  6105. const attributeName = this.getAttributeName( builder );
  6106. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6107. const attribute = builder.geometry.getAttribute( attributeName );
  6108. nodeType = builder.getTypeFromAttribute( attribute );
  6109. } else {
  6110. nodeType = 'float';
  6111. }
  6112. }
  6113. return nodeType;
  6114. }
  6115. /**
  6116. * Sets the attribute name to the given value. The method can be
  6117. * overwritten in derived classes if the final name must be computed
  6118. * analytically.
  6119. *
  6120. * @param {String} attributeName - The name of the attribute.
  6121. * @return {AttributeNode} A reference to this node.
  6122. */
  6123. setAttributeName( attributeName ) {
  6124. this._attributeName = attributeName;
  6125. return this;
  6126. }
  6127. /**
  6128. * Returns the attribute name of this node. The method can be
  6129. * overwritten in derived classes if the final name must be computed
  6130. * analytically.
  6131. *
  6132. * @param {NodeBuilder} builder - The current node builder.
  6133. * @return {String} The attribute name.
  6134. */
  6135. getAttributeName( /*builder*/ ) {
  6136. return this._attributeName;
  6137. }
  6138. generate( builder ) {
  6139. const attributeName = this.getAttributeName( builder );
  6140. const nodeType = this.getNodeType( builder );
  6141. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6142. if ( geometryAttribute === true ) {
  6143. const attribute = builder.geometry.getAttribute( attributeName );
  6144. const attributeType = builder.getTypeFromAttribute( attribute );
  6145. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6146. if ( builder.shaderStage === 'vertex' ) {
  6147. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6148. } else {
  6149. const nodeVarying = varying( this );
  6150. return nodeVarying.build( builder, nodeType );
  6151. }
  6152. } else {
  6153. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6154. return builder.generateConst( nodeType );
  6155. }
  6156. }
  6157. serialize( data ) {
  6158. super.serialize( data );
  6159. data.global = this.global;
  6160. data._attributeName = this._attributeName;
  6161. }
  6162. deserialize( data ) {
  6163. super.deserialize( data );
  6164. this.global = data.global;
  6165. this._attributeName = data._attributeName;
  6166. }
  6167. }
  6168. /**
  6169. * TSL function for creating an attribute node.
  6170. *
  6171. * @function
  6172. * @param {String} name - The name of the attribute.
  6173. * @param {String?} nodeType - The node type.
  6174. * @returns {AttributeNode}
  6175. */
  6176. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6177. /** @module UV **/
  6178. /**
  6179. * TSL function for creating an uv attribute node with the given index.
  6180. *
  6181. * @function
  6182. * @param {Number} [index=0] - The uv index.
  6183. * @return {AttributeNode<vec2>} The uv attribute node.
  6184. */
  6185. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6186. /** @module TextureSizeNode **/
  6187. /**
  6188. * A node that represents the dimensions of a texture. The texture size is
  6189. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6190. * or `textureSize()`.
  6191. *
  6192. * @augments Node
  6193. */
  6194. class TextureSizeNode extends Node {
  6195. static get type() {
  6196. return 'TextureSizeNode';
  6197. }
  6198. /**
  6199. * Constructs a new texture size node.
  6200. *
  6201. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6202. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6203. */
  6204. constructor( textureNode, levelNode = null ) {
  6205. super( 'uvec2' );
  6206. /**
  6207. * This flag can be used for type testing.
  6208. *
  6209. * @type {Boolean}
  6210. * @readonly
  6211. * @default true
  6212. */
  6213. this.isTextureSizeNode = true;
  6214. /**
  6215. * A texture node which size should be retrieved.
  6216. *
  6217. * @type {TextureNode}
  6218. */
  6219. this.textureNode = textureNode;
  6220. /**
  6221. * A level node which defines the requested mip.
  6222. *
  6223. * @type {Node<int>}
  6224. * @default null
  6225. */
  6226. this.levelNode = levelNode;
  6227. }
  6228. generate( builder, output ) {
  6229. const textureProperty = this.textureNode.build( builder, 'property' );
  6230. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6231. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6232. }
  6233. }
  6234. /**
  6235. * TSL function for creating a texture size node.
  6236. *
  6237. * @function
  6238. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6239. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6240. * @returns {TextureSizeNode}
  6241. */
  6242. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6243. /** @module MatcapUVNode **/
  6244. /**
  6245. * A special type of uniform node that computes the
  6246. * maximum mipmap level for a given texture node.
  6247. *
  6248. * ```js
  6249. * const level = maxMipLevel( textureNode );
  6250. * ```
  6251. *
  6252. * @augments module:UniformNode~UniformNode
  6253. */
  6254. class MaxMipLevelNode extends UniformNode {
  6255. static get type() {
  6256. return 'MaxMipLevelNode';
  6257. }
  6258. /**
  6259. * Constructs a new max mip level node.
  6260. *
  6261. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6262. */
  6263. constructor( textureNode ) {
  6264. super( 0 );
  6265. /**
  6266. * The texture node to compute the max mip level for.
  6267. *
  6268. * @private
  6269. * @type {TextureNode}
  6270. */
  6271. this._textureNode = textureNode;
  6272. /**
  6273. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6274. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6275. *
  6276. * @type {String}
  6277. * @default 'frame'
  6278. */
  6279. this.updateType = NodeUpdateType.FRAME;
  6280. }
  6281. /**
  6282. * The texture node to compute the max mip level for.
  6283. *
  6284. * @readonly
  6285. * @type {TextureNode}
  6286. */
  6287. get textureNode() {
  6288. return this._textureNode;
  6289. }
  6290. /**
  6291. * The texture.
  6292. *
  6293. * @readonly
  6294. * @type {Texture}
  6295. */
  6296. get texture() {
  6297. return this._textureNode.value;
  6298. }
  6299. update() {
  6300. const texture = this.texture;
  6301. const images = texture.images;
  6302. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6303. if ( image && image.width !== undefined ) {
  6304. const { width, height } = image;
  6305. this.value = Math.log2( Math.max( width, height ) );
  6306. }
  6307. }
  6308. }
  6309. /**
  6310. * TSL function for creating a max mip level node.
  6311. *
  6312. * @function
  6313. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6314. * @returns {MaxMipLevelNode}
  6315. */
  6316. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6317. /** @module TextureNode **/
  6318. /**
  6319. * This type of uniform node represents a 2D texture.
  6320. *
  6321. * @augments module:UniformNode~UniformNode
  6322. */
  6323. class TextureNode extends UniformNode {
  6324. static get type() {
  6325. return 'TextureNode';
  6326. }
  6327. /**
  6328. * Constructs a new texture node.
  6329. *
  6330. * @param {Texture} value - The texture.
  6331. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6332. * @param {Node<int>?} [levelNode=null] - The level node.
  6333. * @param {Node<float>?} [biasNode=null] - The bias node.
  6334. */
  6335. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6336. super( value );
  6337. /**
  6338. * This flag can be used for type testing.
  6339. *
  6340. * @type {Boolean}
  6341. * @readonly
  6342. * @default true
  6343. */
  6344. this.isTextureNode = true;
  6345. /**
  6346. * Represents the texture coordinates.
  6347. *
  6348. * @type {Node<vec2|vec3>?}
  6349. * @default null
  6350. */
  6351. this.uvNode = uvNode;
  6352. /**
  6353. * Represents the mip level that should be selected.
  6354. *
  6355. * @type {Node<int>?}
  6356. * @default null
  6357. */
  6358. this.levelNode = levelNode;
  6359. /**
  6360. * Represents the bias to be applied during level-of-detail computation.
  6361. *
  6362. * @type {Node<float>?}
  6363. * @default null
  6364. */
  6365. this.biasNode = biasNode;
  6366. /**
  6367. * Represents a reference value a texture sample is compared to.
  6368. *
  6369. * @type {Node<float>?}
  6370. * @default null
  6371. */
  6372. this.compareNode = null;
  6373. /**
  6374. * When using texture arrays, the depth node defines the layer to select.
  6375. *
  6376. * @type {Node<int>?}
  6377. * @default null
  6378. */
  6379. this.depthNode = null;
  6380. /**
  6381. * When defined, a texture is sampled using explicit gradients.
  6382. *
  6383. * @type {Array<Node<vec2>>?}
  6384. * @default null
  6385. */
  6386. this.gradNode = null;
  6387. /**
  6388. * Whether texture values should be sampled or fetched.
  6389. *
  6390. * @type {Boolean}
  6391. * @default true
  6392. */
  6393. this.sampler = true;
  6394. /**
  6395. * Whether the uv transformation matrix should be
  6396. * automatically updated or not. Use `setUpdateMatrix()`
  6397. * if you want to change the value of the property.
  6398. *
  6399. * @type {Boolean}
  6400. * @default false
  6401. */
  6402. this.updateMatrix = false;
  6403. /**
  6404. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6405. * sets the value to `frame` when the uv transformation matrix should
  6406. * automatically be updated.
  6407. *
  6408. * @type {String}
  6409. * @default 'none'
  6410. */
  6411. this.updateType = NodeUpdateType.NONE;
  6412. /**
  6413. * The reference node.
  6414. *
  6415. * @type {Node?}
  6416. * @default null
  6417. */
  6418. this.referenceNode = null;
  6419. /**
  6420. * The texture value is stored in a private property.
  6421. *
  6422. * @private
  6423. * @type {Texture}
  6424. */
  6425. this._value = value;
  6426. /**
  6427. * The uniform node that represents the uv transformation matrix.
  6428. *
  6429. * @private
  6430. * @type {UniformNode<mat3>?}
  6431. */
  6432. this._matrixUniform = null;
  6433. this.setUpdateMatrix( uvNode === null );
  6434. }
  6435. set value( value ) {
  6436. if ( this.referenceNode ) {
  6437. this.referenceNode.value = value;
  6438. } else {
  6439. this._value = value;
  6440. }
  6441. }
  6442. /**
  6443. * The texture value.
  6444. *
  6445. * @type {Texture}
  6446. */
  6447. get value() {
  6448. return this.referenceNode ? this.referenceNode.value : this._value;
  6449. }
  6450. /**
  6451. * Overwritten since the uniform hash is defined by the texture's UUID.
  6452. *
  6453. * @param {NodeBuilder} builder - The current node builder.
  6454. * @return {String} The uniform hash.
  6455. */
  6456. getUniformHash( /*builder*/ ) {
  6457. return this.value.uuid;
  6458. }
  6459. /**
  6460. * Overwritten since the node type is inferred from the texture type.
  6461. *
  6462. * @param {NodeBuilder} builder - The current node builder.
  6463. * @return {String} The node type.
  6464. */
  6465. getNodeType( /*builder*/ ) {
  6466. if ( this.value.isDepthTexture === true ) return 'float';
  6467. if ( this.value.type === UnsignedIntType ) {
  6468. return 'uvec4';
  6469. } else if ( this.value.type === IntType ) {
  6470. return 'ivec4';
  6471. }
  6472. return 'vec4';
  6473. }
  6474. /**
  6475. * Overwrites the default implementation to return a fixed value `'texture'`.
  6476. *
  6477. * @param {NodeBuilder} builder - The current node builder.
  6478. * @return {String} The input type.
  6479. */
  6480. getInputType( /*builder*/ ) {
  6481. return 'texture';
  6482. }
  6483. /**
  6484. * Returns a default uvs based on the current texture's channel.
  6485. *
  6486. * @return {AttributeNode<vec2>} The default uvs.
  6487. */
  6488. getDefaultUV() {
  6489. return uv( this.value.channel );
  6490. }
  6491. /**
  6492. * Overwritten to always return the texture reference of the node.
  6493. *
  6494. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6495. * @return {Texture} The texture reference.
  6496. */
  6497. updateReference( /*state*/ ) {
  6498. return this.value;
  6499. }
  6500. /**
  6501. * Transforms the given uv node with the texture transformation matrix.
  6502. *
  6503. * @param {Node} uvNode - The uv node to transform.
  6504. * @return {Node} The transformed uv node.
  6505. */
  6506. getTransformedUV( uvNode ) {
  6507. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6508. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6509. }
  6510. /**
  6511. * Defines whether the uv transformation matrix should automatically be updated or not.
  6512. *
  6513. * @param {Boolean} value - The update toggle.
  6514. * @return {TextureNode} A reference to this node.
  6515. */
  6516. setUpdateMatrix( value ) {
  6517. this.updateMatrix = value;
  6518. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6519. return this;
  6520. }
  6521. /**
  6522. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6523. * to modify the uv node for correct sampling.
  6524. *
  6525. * @param {NodeBuilder} builder - The current node builder.
  6526. * @param {Node} uvNode - The uv node to setup.
  6527. * @return {Node} The updated uv node.
  6528. */
  6529. setupUV( builder, uvNode ) {
  6530. const texture = this.value;
  6531. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6532. if ( this.sampler ) {
  6533. uvNode = uvNode.flipY();
  6534. } else {
  6535. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6536. }
  6537. }
  6538. return uvNode;
  6539. }
  6540. /**
  6541. * Setups texture node by preparing the internal nodes for code generation.
  6542. *
  6543. * @param {NodeBuilder} builder - The current node builder.
  6544. */
  6545. setup( builder ) {
  6546. const properties = builder.getNodeProperties( this );
  6547. properties.referenceNode = this.referenceNode;
  6548. //
  6549. const texture = this.value;
  6550. if ( ! texture || texture.isTexture !== true ) {
  6551. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6552. }
  6553. //
  6554. let uvNode = this.uvNode;
  6555. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6556. uvNode = builder.context.getUV( this );
  6557. }
  6558. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6559. if ( this.updateMatrix === true ) {
  6560. uvNode = this.getTransformedUV( uvNode );
  6561. }
  6562. uvNode = this.setupUV( builder, uvNode );
  6563. //
  6564. let levelNode = this.levelNode;
  6565. if ( levelNode === null && builder.context.getTextureLevel ) {
  6566. levelNode = builder.context.getTextureLevel( this );
  6567. }
  6568. //
  6569. properties.uvNode = uvNode;
  6570. properties.levelNode = levelNode;
  6571. properties.biasNode = this.biasNode;
  6572. properties.compareNode = this.compareNode;
  6573. properties.gradNode = this.gradNode;
  6574. properties.depthNode = this.depthNode;
  6575. }
  6576. /**
  6577. * Generates the uv code snippet.
  6578. *
  6579. * @param {NodeBuilder} builder - The current node builder.
  6580. * @param {Node} uvNode - The uv node to generate code for.
  6581. * @return {String} The generated code snippet.
  6582. */
  6583. generateUV( builder, uvNode ) {
  6584. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6585. }
  6586. /**
  6587. * Generates the snippet for the texture sampling.
  6588. *
  6589. * @param {NodeBuilder} builder - The current node builder.
  6590. * @param {String} textureProperty - The texture property.
  6591. * @param {String} uvSnippet - The uv snippet.
  6592. * @param {String} levelSnippet - The level snippet.
  6593. * @param {String} biasSnippet - The bias snippet.
  6594. * @param {String} depthSnippet - The depth snippet.
  6595. * @param {String} compareSnippet - The compare snippet.
  6596. * @param {String} gradSnippet - The grad snippet.
  6597. * @return {String} The generated code snippet.
  6598. */
  6599. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6600. const texture = this.value;
  6601. let snippet;
  6602. if ( levelSnippet ) {
  6603. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6604. } else if ( biasSnippet ) {
  6605. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6606. } else if ( gradSnippet ) {
  6607. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6608. } else if ( compareSnippet ) {
  6609. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6610. } else if ( this.sampler === false ) {
  6611. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6612. } else {
  6613. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6614. }
  6615. return snippet;
  6616. }
  6617. /**
  6618. * Generates the code snippet of the texture node.
  6619. *
  6620. * @param {NodeBuilder} builder - The current node builder.
  6621. * @param {String} output - The current output.
  6622. * @return {String} The generated code snippet.
  6623. */
  6624. generate( builder, output ) {
  6625. const texture = this.value;
  6626. const properties = builder.getNodeProperties( this );
  6627. const textureProperty = super.generate( builder, 'property' );
  6628. if ( output === 'sampler' ) {
  6629. return textureProperty + '_sampler';
  6630. } else if ( builder.isReference( output ) ) {
  6631. return textureProperty;
  6632. } else {
  6633. const nodeData = builder.getDataFromNode( this );
  6634. let propertyName = nodeData.propertyName;
  6635. if ( propertyName === undefined ) {
  6636. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6637. const uvSnippet = this.generateUV( builder, uvNode );
  6638. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6639. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6640. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6641. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6642. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6643. const nodeVar = builder.getVarFromNode( this );
  6644. propertyName = builder.getPropertyName( nodeVar );
  6645. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  6646. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  6647. nodeData.snippet = snippet;
  6648. nodeData.propertyName = propertyName;
  6649. }
  6650. let snippet = propertyName;
  6651. const nodeType = this.getNodeType( builder );
  6652. if ( builder.needsToWorkingColorSpace( texture ) ) {
  6653. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  6654. }
  6655. return builder.format( snippet, nodeType, output );
  6656. }
  6657. }
  6658. /**
  6659. * Sets the sampler value.
  6660. *
  6661. * @param {Boolean} value - The sampler value to set.
  6662. * @return {TextureNode} A reference to this texture node.
  6663. */
  6664. setSampler( value ) {
  6665. this.sampler = value;
  6666. return this;
  6667. }
  6668. /**
  6669. * Returns the sampler value.
  6670. *
  6671. * @return {Boolean} The sampler value.
  6672. */
  6673. getSampler() {
  6674. return this.sampler;
  6675. }
  6676. // @TODO: Move to TSL
  6677. /**
  6678. * @function
  6679. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  6680. *
  6681. * @param {Node} uvNode - The uv node.
  6682. * @return {TextureNode} A texture node representing the texture sample.
  6683. */
  6684. uv( uvNode ) { // @deprecated, r172
  6685. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  6686. return this.sample( uvNode );
  6687. }
  6688. /**
  6689. * Samples the texture with the given uv node.
  6690. *
  6691. * @param {Node} uvNode - The uv node.
  6692. * @return {TextureNode} A texture node representing the texture sample.
  6693. */
  6694. sample( uvNode ) {
  6695. const textureNode = this.clone();
  6696. textureNode.uvNode = nodeObject( uvNode );
  6697. textureNode.referenceNode = this.getSelf();
  6698. return nodeObject( textureNode );
  6699. }
  6700. /**
  6701. * Samples a blurred version of the texture by defining an internal bias.
  6702. *
  6703. * @param {Node<float>} amountNode - How blurred the texture should be.
  6704. * @return {TextureNode} A texture node representing the texture sample.
  6705. */
  6706. blur( amountNode ) {
  6707. const textureNode = this.clone();
  6708. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  6709. textureNode.referenceNode = this.getSelf();
  6710. return nodeObject( textureNode );
  6711. }
  6712. /**
  6713. * Samples a specific mip of the texture.
  6714. *
  6715. * @param {Node<int>} levelNode - The mip level to sample.
  6716. * @return {TextureNode} A texture node representing the texture sample.
  6717. */
  6718. level( levelNode ) {
  6719. const textureNode = this.clone();
  6720. textureNode.levelNode = nodeObject( levelNode );
  6721. textureNode.referenceNode = this.getSelf();
  6722. return nodeObject( textureNode );
  6723. }
  6724. /**
  6725. * Returns the texture size of the requested level.
  6726. *
  6727. * @param {Node<int>} levelNode - The level to compute the size for.
  6728. * @return {TextureSizeNode} The texture size.
  6729. */
  6730. size( levelNode ) {
  6731. return textureSize( this, levelNode );
  6732. }
  6733. /**
  6734. * Samples the texture with the given bias.
  6735. *
  6736. * @param {Node<float>} biasNode - The bias node.
  6737. * @return {TextureNode} A texture node representing the texture sample.
  6738. */
  6739. bias( biasNode ) {
  6740. const textureNode = this.clone();
  6741. textureNode.biasNode = nodeObject( biasNode );
  6742. textureNode.referenceNode = this.getSelf();
  6743. return nodeObject( textureNode );
  6744. }
  6745. /**
  6746. * Samples the texture by executing a compare operation.
  6747. *
  6748. * @param {Node<float>} compareNode - The node that defines the compare value.
  6749. * @return {TextureNode} A texture node representing the texture sample.
  6750. */
  6751. compare( compareNode ) {
  6752. const textureNode = this.clone();
  6753. textureNode.compareNode = nodeObject( compareNode );
  6754. textureNode.referenceNode = this.getSelf();
  6755. return nodeObject( textureNode );
  6756. }
  6757. /**
  6758. * Samples the texture using an explicit gradient.
  6759. *
  6760. * @param {Node<vec2>} gradNodeX - The gradX node.
  6761. * @param {Node<vec2>} gradNodeY - The gradY node.
  6762. * @return {TextureNode} A texture node representing the texture sample.
  6763. */
  6764. grad( gradNodeX, gradNodeY ) {
  6765. const textureNode = this.clone();
  6766. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  6767. textureNode.referenceNode = this.getSelf();
  6768. return nodeObject( textureNode );
  6769. }
  6770. /**
  6771. * Samples the texture by defining a depth node.
  6772. *
  6773. * @param {Node<int>} depthNode - The depth node.
  6774. * @return {TextureNode} A texture node representing the texture sample.
  6775. */
  6776. depth( depthNode ) {
  6777. const textureNode = this.clone();
  6778. textureNode.depthNode = nodeObject( depthNode );
  6779. textureNode.referenceNode = this.getSelf();
  6780. return nodeObject( textureNode );
  6781. }
  6782. // --
  6783. serialize( data ) {
  6784. super.serialize( data );
  6785. data.value = this.value.toJSON( data.meta ).uuid;
  6786. data.sampler = this.sampler;
  6787. data.updateMatrix = this.updateMatrix;
  6788. data.updateType = this.updateType;
  6789. }
  6790. deserialize( data ) {
  6791. super.deserialize( data );
  6792. this.value = data.meta.textures[ data.value ];
  6793. this.sampler = data.sampler;
  6794. this.updateMatrix = data.updateMatrix;
  6795. this.updateType = data.updateType;
  6796. }
  6797. /**
  6798. * The update is used to implement the update of the uv transformation matrix.
  6799. */
  6800. update() {
  6801. const texture = this.value;
  6802. const matrixUniform = this._matrixUniform;
  6803. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  6804. if ( texture.matrixAutoUpdate === true ) {
  6805. texture.updateMatrix();
  6806. }
  6807. }
  6808. /**
  6809. * Clones the texture node.
  6810. *
  6811. * @return {TextureNode} The cloned texture node.
  6812. */
  6813. clone() {
  6814. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  6815. newNode.sampler = this.sampler;
  6816. return newNode;
  6817. }
  6818. }
  6819. /**
  6820. * TSL function for creating a texture node.
  6821. *
  6822. * @function
  6823. * @param {Texture} value - The texture.
  6824. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6825. * @param {Node<int>?} [levelNode=null] - The level node.
  6826. * @param {Node<float>?} [biasNode=null] - The bias node.
  6827. * @returns {TextureNode}
  6828. */
  6829. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  6830. /**
  6831. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  6832. *
  6833. * @function
  6834. * @param {Texture} value - The texture.
  6835. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6836. * @param {Node<int>?} [levelNode=null] - The level node.
  6837. * @param {Node<float>?} [biasNode=null] - The bias node.
  6838. * @returns {TextureNode}
  6839. */
  6840. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  6841. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  6842. /**
  6843. * Converts a texture or texture node to a sampler.
  6844. *
  6845. * @function
  6846. * @param {TextureNode|Texture} aTexture - The texture or texture node to convert.
  6847. * @returns {Node}
  6848. */
  6849. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  6850. /** @module Camera **/
  6851. /**
  6852. * TSL object that represents the `near` value of the camera used for the current render.
  6853. *
  6854. * @type {UniformNode<float>}
  6855. */
  6856. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  6857. /**
  6858. * TSL object that represents the `far` value of the camera used for the current render.
  6859. *
  6860. * @type {UniformNode<float>}
  6861. */
  6862. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  6863. /**
  6864. * TSL object that represents the projection matrix of the camera used for the current render.
  6865. *
  6866. * @type {UniformNode<mat4>}
  6867. */
  6868. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  6869. /**
  6870. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  6871. *
  6872. * @type {UniformNode<mat4>}
  6873. */
  6874. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  6875. /**
  6876. * TSL object that represents the view matrix of the camera used for the current render.
  6877. *
  6878. * @type {UniformNode<mat4>}
  6879. */
  6880. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  6881. /**
  6882. * TSL object that represents the world matrix of the camera used for the current render.
  6883. *
  6884. * @type {UniformNode<mat4>}
  6885. */
  6886. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  6887. /**
  6888. * TSL object that represents the normal matrix of the camera used for the current render.
  6889. *
  6890. * @type {UniformNode<mat3>}
  6891. */
  6892. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  6893. /**
  6894. * TSL object that represents the position in world space of the camera used for the current render.
  6895. *
  6896. * @type {UniformNode<vec3>}
  6897. */
  6898. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  6899. /** @module Object3DNode **/
  6900. /**
  6901. * This node can be used to access transformation related metrics of 3D objects.
  6902. * Depending on the selected scope, a different metric is represented as a uniform
  6903. * in the shader. The following scopes are supported:
  6904. *
  6905. * - `POSITION`: The object's position in world space.
  6906. * - `VIEW_POSITION`: The object's position in view/camera space.
  6907. * - `DIRECTION`: The object's direction in world space.
  6908. * - `SCALE`: The object's scale in world space.
  6909. * - `WORLD_MATRIX`: The object's matrix in world space.
  6910. *
  6911. * @augments Node
  6912. */
  6913. class Object3DNode extends Node {
  6914. static get type() {
  6915. return 'Object3DNode';
  6916. }
  6917. /**
  6918. * Constructs a new object 3D node.
  6919. *
  6920. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  6921. * @param {Object3D?} [object3d=null] - The 3D object.
  6922. */
  6923. constructor( scope, object3d = null ) {
  6924. super();
  6925. /**
  6926. * The node reports a different type of transformation depending on the scope.
  6927. *
  6928. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  6929. */
  6930. this.scope = scope;
  6931. /**
  6932. * The 3D object.
  6933. *
  6934. * @type {Object3D?}
  6935. * @default null
  6936. */
  6937. this.object3d = object3d;
  6938. /**
  6939. * Overwritten since this type of node is updated per object.
  6940. *
  6941. * @type {String}
  6942. * @default 'object'
  6943. */
  6944. this.updateType = NodeUpdateType.OBJECT;
  6945. /**
  6946. * Holds the value of the node as a uniform.
  6947. *
  6948. * @private
  6949. * @type {UniformNode}
  6950. */
  6951. this._uniformNode = new UniformNode( null );
  6952. }
  6953. /**
  6954. * Overwritten since the node type is inferred from the scope.
  6955. *
  6956. * @param {NodeBuilder} builder - The current node builder.
  6957. * @return {String} The node type.
  6958. */
  6959. getNodeType() {
  6960. const scope = this.scope;
  6961. if ( scope === Object3DNode.WORLD_MATRIX ) {
  6962. return 'mat4';
  6963. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  6964. return 'vec3';
  6965. }
  6966. }
  6967. /**
  6968. * Updates the uniform value depending on the scope.
  6969. *
  6970. * @param {NodeFrame} frame - The current node frame.
  6971. */
  6972. update( frame ) {
  6973. const object = this.object3d;
  6974. const uniformNode = this._uniformNode;
  6975. const scope = this.scope;
  6976. if ( scope === Object3DNode.WORLD_MATRIX ) {
  6977. uniformNode.value = object.matrixWorld;
  6978. } else if ( scope === Object3DNode.POSITION ) {
  6979. uniformNode.value = uniformNode.value || new Vector3();
  6980. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  6981. } else if ( scope === Object3DNode.SCALE ) {
  6982. uniformNode.value = uniformNode.value || new Vector3();
  6983. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  6984. } else if ( scope === Object3DNode.DIRECTION ) {
  6985. uniformNode.value = uniformNode.value || new Vector3();
  6986. object.getWorldDirection( uniformNode.value );
  6987. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  6988. const camera = frame.camera;
  6989. uniformNode.value = uniformNode.value || new Vector3();
  6990. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  6991. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  6992. }
  6993. }
  6994. /**
  6995. * Generates the code snippet of the uniform node. The node type of the uniform
  6996. * node also depends on the selected scope.
  6997. *
  6998. * @param {NodeBuilder} builder - The current node builder.
  6999. * @return {String} The generated code snippet.
  7000. */
  7001. generate( builder ) {
  7002. const scope = this.scope;
  7003. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7004. this._uniformNode.nodeType = 'mat4';
  7005. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7006. this._uniformNode.nodeType = 'vec3';
  7007. }
  7008. return this._uniformNode.build( builder );
  7009. }
  7010. serialize( data ) {
  7011. super.serialize( data );
  7012. data.scope = this.scope;
  7013. }
  7014. deserialize( data ) {
  7015. super.deserialize( data );
  7016. this.scope = data.scope;
  7017. }
  7018. }
  7019. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  7020. Object3DNode.POSITION = 'position';
  7021. Object3DNode.SCALE = 'scale';
  7022. Object3DNode.VIEW_POSITION = 'viewPosition';
  7023. Object3DNode.DIRECTION = 'direction';
  7024. /**
  7025. * TSL function for creating an object 3D node that represents the object's direction in world space.
  7026. *
  7027. * @function
  7028. * @param {Object3D?} [object3d=null] - The 3D object.
  7029. * @returns {Object3DNode<vec3>}
  7030. */
  7031. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  7032. /**
  7033. * TSL function for creating an object 3D node that represents the object's world matrix.
  7034. *
  7035. * @function
  7036. * @param {Object3D?} [object3d=null] - The 3D object.
  7037. * @returns {Object3DNode<mat4>}
  7038. */
  7039. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  7040. /**
  7041. * TSL function for creating an object 3D node that represents the object's position in world space.
  7042. *
  7043. * @function
  7044. * @param {Object3D?} [object3d=null] - The 3D object.
  7045. * @returns {Object3DNode<vec3>}
  7046. */
  7047. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  7048. /**
  7049. * TSL function for creating an object 3D node that represents the object's scale in world space.
  7050. *
  7051. * @function
  7052. * @param {Object3D?} [object3d=null] - The 3D object.
  7053. * @returns {Object3DNode<vec3>}
  7054. */
  7055. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  7056. /**
  7057. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  7058. *
  7059. * @function
  7060. * @param {Object3D?} [object3d=null] - The 3D object.
  7061. * @returns {Object3DNode<vec3>}
  7062. */
  7063. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  7064. /** @module ModelNode **/
  7065. /**
  7066. * This type of node is a specialized version of `Object3DNode`
  7067. * with larger set of model related metrics. Unlike `Object3DNode`,
  7068. * `ModelNode` extracts the reference to the 3D object from the
  7069. * current node frame state.
  7070. *
  7071. * @augments module:Object3DNode~Object3DNode
  7072. */
  7073. class ModelNode extends Object3DNode {
  7074. static get type() {
  7075. return 'ModelNode';
  7076. }
  7077. /**
  7078. * Constructs a new object model node.
  7079. *
  7080. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7081. */
  7082. constructor( scope ) {
  7083. super( scope );
  7084. }
  7085. /**
  7086. * Extracts the model reference from the frame state and then
  7087. * updates the uniform value depending on the scope.
  7088. *
  7089. * @param {NodeFrame} frame - The current node frame.
  7090. */
  7091. update( frame ) {
  7092. this.object3d = frame.object;
  7093. super.update( frame );
  7094. }
  7095. }
  7096. /**
  7097. * TSL object that represents the object's direction in world space.
  7098. *
  7099. * @type {ModelNode<vec3>}
  7100. */
  7101. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  7102. /**
  7103. * TSL object that represents the object's world matrix.
  7104. *
  7105. * @type {ModelNode<mat4>}
  7106. */
  7107. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7108. /**
  7109. * TSL object that represents the object's position in world space.
  7110. *
  7111. * @type {ModelNode<vec3>}
  7112. */
  7113. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7114. /**
  7115. * TSL object that represents the object's scale in world space.
  7116. *
  7117. * @type {ModelNode<vec3>}
  7118. */
  7119. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7120. /**
  7121. * TSL object that represents the object's position in view/camera space.
  7122. *
  7123. * @type {ModelNode<vec3>}
  7124. */
  7125. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7126. /**
  7127. * TSL object that represents the object's normal matrix.
  7128. *
  7129. * @type {UniformNode<mat3>}
  7130. */
  7131. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7132. /**
  7133. * TSL object that represents the object's inverse world matrix.
  7134. *
  7135. * @type {UniformNode<mat4>}
  7136. */
  7137. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7138. /**
  7139. * TSL object that represents the object's model view matrix.
  7140. *
  7141. * @type {Node<mat4>}
  7142. */
  7143. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7144. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7145. } ).once() )().toVar( 'modelViewMatrix' );
  7146. // GPU Precision
  7147. /**
  7148. * TSL object that represents the object's model view in `mediump` precision.
  7149. *
  7150. * @type {Node<mat4>}
  7151. */
  7152. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7153. // CPU Precision
  7154. /**
  7155. * TSL object that represents the object's model view in `highp` precision
  7156. * which is achieved by computing the matrix in JS and not in the shader.
  7157. *
  7158. * @type {Node<mat4>}
  7159. */
  7160. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7161. builder.context.isHighPrecisionModelViewMatrix = true;
  7162. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7163. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7164. } );
  7165. } ).once() )().toVar( 'highpModelViewMatrix' );
  7166. /**
  7167. * TSL object that represents the object's model normal view in `highp` precision
  7168. * which is achieved by computing the matrix in JS and not in the shader.
  7169. *
  7170. * @type {Node<mat3>}
  7171. */
  7172. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7173. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7174. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7175. if ( isHighPrecisionModelViewMatrix !== true ) {
  7176. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7177. }
  7178. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7179. } );
  7180. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7181. /** @module Position **/
  7182. /**
  7183. * TSL object that represents the position attribute of the current rendered object.
  7184. *
  7185. * @type {AttributeNode<vec3>}
  7186. */
  7187. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7188. /**
  7189. * TSL object that represents the vertex position in local space of the current rendered object.
  7190. *
  7191. * @type {AttributeNode<vec3>}
  7192. */
  7193. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  7194. /**
  7195. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7196. * Used in context of {@link module:VelocityNode~VelocityNode} for rendering motion vectors.
  7197. *
  7198. * @type {AttributeNode<vec3>}
  7199. */
  7200. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  7201. /**
  7202. * TSL object that represents the vertex position in world space of the current rendered object.
  7203. *
  7204. * @type {VaryingNode<vec3>}
  7205. */
  7206. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7207. /**
  7208. * TSL object that represents the position world direction of the current rendered object.
  7209. *
  7210. * @type {Node<vec3>}
  7211. */
  7212. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  7213. /**
  7214. * TSL object that represents the vertex position in view space of the current rendered object.
  7215. *
  7216. * @type {VaryingNode<vec3>}
  7217. */
  7218. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7219. return builder.context.setupPositionView();
  7220. }, 'vec3' ).once() )().varying( 'v_positionView' ).context( { needsPositionReassign: true } );
  7221. /**
  7222. * TSL object that represents the position view direction of the current rendered object.
  7223. *
  7224. * @type {VaryingNode<vec3>}
  7225. */
  7226. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  7227. /** @module FrontFacingNode **/
  7228. /**
  7229. * This node can be used to evaluate whether a primitive is front or back facing.
  7230. *
  7231. * @augments Node
  7232. */
  7233. class FrontFacingNode extends Node {
  7234. static get type() {
  7235. return 'FrontFacingNode';
  7236. }
  7237. /**
  7238. * Constructs a new front facing node.
  7239. */
  7240. constructor() {
  7241. super( 'bool' );
  7242. /**
  7243. * This flag can be used for type testing.
  7244. *
  7245. * @type {Boolean}
  7246. * @readonly
  7247. * @default true
  7248. */
  7249. this.isFrontFacingNode = true;
  7250. }
  7251. generate( builder ) {
  7252. const { renderer, material } = builder;
  7253. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  7254. if ( material.side === BackSide ) {
  7255. return 'false';
  7256. }
  7257. }
  7258. return builder.getFrontFacing();
  7259. }
  7260. }
  7261. /**
  7262. * TSL object that represents whether a primitive is front or back facing
  7263. *
  7264. * @type {FrontFacingNode<bool>}
  7265. */
  7266. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  7267. /**
  7268. * TSL object that represents the front facing status as a number instead of a bool.
  7269. * `1` means front facing, `-1` means back facing.
  7270. *
  7271. * @type {Node<float>}
  7272. */
  7273. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  7274. /** @module Normal **/
  7275. /**
  7276. * TSL object that represents the normal attribute of the current rendered object.
  7277. *
  7278. * @type {Node<vec3>}
  7279. */
  7280. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  7281. /**
  7282. * TSL object that represents the vertex normal in local space of the current rendered object.
  7283. *
  7284. * @type {Node<vec3>}
  7285. */
  7286. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  7287. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  7288. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  7289. return vec3( 0, 1, 0 );
  7290. }
  7291. return normalGeometry;
  7292. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  7293. /**
  7294. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  7295. *
  7296. * @type {Node<vec3>}
  7297. */
  7298. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  7299. /**
  7300. * TSL object that represents the vertex normal in view space of the current rendered object.
  7301. *
  7302. * @type {Node<vec3>}
  7303. */
  7304. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7305. let node;
  7306. if ( builder.material.flatShading === true ) {
  7307. node = normalFlat;
  7308. } else {
  7309. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  7310. }
  7311. return node;
  7312. }, 'vec3' ).once() )().toVar( 'normalView' );
  7313. /**
  7314. * TSL object that represents the vertex normal in world space of the current rendered object.
  7315. *
  7316. * @type {Node<vec3>}
  7317. */
  7318. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  7319. /**
  7320. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  7321. *
  7322. * @type {Node<vec3>}
  7323. */
  7324. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7325. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7326. return builder.context.setupNormal().context( { getUV: null } );
  7327. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  7328. /**
  7329. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  7330. *
  7331. * @type {Node<vec3>}
  7332. */
  7333. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  7334. /**
  7335. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  7336. *
  7337. * @type {Node<vec3>}
  7338. */
  7339. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7340. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7341. return builder.context.setupClearcoatNormal().context( { getUV: null } );
  7342. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  7343. /**
  7344. * Transforms the normal with the given matrix.
  7345. *
  7346. * @function
  7347. * @param {Node<vec3>} normal - The normal.
  7348. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  7349. * @return {Node<vec3>} The transformed normal.
  7350. */
  7351. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  7352. const m = mat3( matrix );
  7353. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  7354. return m.mul( transformedNormal ).xyz;
  7355. } );
  7356. /**
  7357. * Transforms the given normal from local to view space.
  7358. *
  7359. * @function
  7360. * @param {Node<vec3>} normal - The normal.
  7361. * @param {NodeBuilder} builder - The current node builder.
  7362. * @return {Node<vec3>} The transformed normal.
  7363. */
  7364. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  7365. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  7366. if ( modelNormalViewMatrix !== null ) {
  7367. return modelNormalViewMatrix.transformDirection( normal );
  7368. }
  7369. //
  7370. const transformedNormal = modelNormalMatrix.mul( normal );
  7371. return cameraViewMatrix.transformDirection( transformedNormal );
  7372. } );
  7373. /** @module MaterialProperties **/
  7374. /**
  7375. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  7376. *
  7377. * @type {UniformNode<float>}
  7378. */
  7379. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  7380. /** @module ReflectVector **/
  7381. /**
  7382. * The reflect vector in view space.
  7383. *
  7384. * @type {Node<vec3>}
  7385. */
  7386. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  7387. /**
  7388. * The refract vector in view space.
  7389. *
  7390. * @type {Node<vec3>}
  7391. */
  7392. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  7393. /**
  7394. * Used for sampling cube maps when using cube reflection mapping.
  7395. *
  7396. * @type {Node<vec3>}
  7397. */
  7398. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7399. /**
  7400. * Used for sampling cube maps when using cube refraction mapping.
  7401. *
  7402. * @type {Node<vec3>}
  7403. */
  7404. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7405. /** @module CubeTextureNode **/
  7406. /**
  7407. * This type of uniform node represents a cube texture.
  7408. *
  7409. * @augments module:TextureNode~TextureNode
  7410. */
  7411. class CubeTextureNode extends TextureNode {
  7412. static get type() {
  7413. return 'CubeTextureNode';
  7414. }
  7415. /**
  7416. * Constructs a new cube texture node.
  7417. *
  7418. * @param {CubeTexture} value - The cube texture.
  7419. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7420. * @param {Node<int>?} [levelNode=null] - The level node.
  7421. * @param {Node<float>?} [biasNode=null] - The bias node.
  7422. */
  7423. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7424. super( value, uvNode, levelNode, biasNode );
  7425. /**
  7426. * This flag can be used for type testing.
  7427. *
  7428. * @type {Boolean}
  7429. * @readonly
  7430. * @default true
  7431. */
  7432. this.isCubeTextureNode = true;
  7433. }
  7434. /**
  7435. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  7436. *
  7437. * @param {NodeBuilder} builder - The current node builder.
  7438. * @return {String} The input type.
  7439. */
  7440. getInputType( /*builder*/ ) {
  7441. return 'cubeTexture';
  7442. }
  7443. /**
  7444. * Returns a default uvs based on the mapping type of the cube texture.
  7445. *
  7446. * @return {Node<vec3>} The default uv attribute.
  7447. */
  7448. getDefaultUV() {
  7449. const texture = this.value;
  7450. if ( texture.mapping === CubeReflectionMapping ) {
  7451. return reflectVector;
  7452. } else if ( texture.mapping === CubeRefractionMapping ) {
  7453. return refractVector;
  7454. } else {
  7455. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  7456. return vec3( 0, 0, 0 );
  7457. }
  7458. }
  7459. /**
  7460. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  7461. * for cube textures. The uv transformation matrix is not applied to cube textures.
  7462. *
  7463. * @param {Boolean} value - The update toggle.
  7464. */
  7465. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  7466. /**
  7467. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  7468. * to modify the uv node for correct sampling.
  7469. *
  7470. * @param {NodeBuilder} builder - The current node builder.
  7471. * @param {Node} uvNode - The uv node to setup.
  7472. * @return {Node} The updated uv node.
  7473. */
  7474. setupUV( builder, uvNode ) {
  7475. const texture = this.value;
  7476. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  7477. return vec3( uvNode.x.negate(), uvNode.yz );
  7478. } else {
  7479. return uvNode;
  7480. }
  7481. }
  7482. /**
  7483. * Generates the uv code snippet.
  7484. *
  7485. * @param {NodeBuilder} builder - The current node builder.
  7486. * @param {Node} cubeUV - The uv node to generate code for.
  7487. * @return {String} The generated code snippet.
  7488. */
  7489. generateUV( builder, cubeUV ) {
  7490. return cubeUV.build( builder, 'vec3' );
  7491. }
  7492. }
  7493. /**
  7494. * TSL function for creating a cube texture node.
  7495. *
  7496. * @function
  7497. * @param {CubeTexture} value - The cube texture.
  7498. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7499. * @param {Node<int>?} [levelNode=null] - The level node.
  7500. * @param {Node<float>?} [biasNode=null] - The bias node.
  7501. * @returns {CubeTextureNode}
  7502. */
  7503. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  7504. /** @module BufferNode **/
  7505. /**
  7506. * A special type of uniform node which represents array-like data
  7507. * as uniform buffers. The access usually happens via `element()`
  7508. * which returns an instance of {@link ArrayElementNode}. For example:
  7509. *
  7510. * ```js
  7511. * const bufferNode = buffer( array, 'mat4', count );
  7512. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7513. * ```
  7514. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7515. * since it handles more input types and automatically cares about buffer paddings.
  7516. *
  7517. * @augments module:UniformNode~UniformNode
  7518. */
  7519. class BufferNode extends UniformNode {
  7520. static get type() {
  7521. return 'BufferNode';
  7522. }
  7523. /**
  7524. * Constructs a new buffer node.
  7525. *
  7526. * @param {Array<Number>} value - Array-like buffer data.
  7527. * @param {String} bufferType - The data type of the buffer.
  7528. * @param {Number} [bufferCount=0] - The count of buffer elements.
  7529. */
  7530. constructor( value, bufferType, bufferCount = 0 ) {
  7531. super( value, bufferType );
  7532. /**
  7533. * This flag can be used for type testing.
  7534. *
  7535. * @type {Boolean}
  7536. * @readonly
  7537. * @default true
  7538. */
  7539. this.isBufferNode = true;
  7540. /**
  7541. * The data type of the buffer.
  7542. *
  7543. * @type {String}
  7544. */
  7545. this.bufferType = bufferType;
  7546. /**
  7547. * The uniform node that holds the value of the reference node.
  7548. *
  7549. * @type {Number}
  7550. * @default 0
  7551. */
  7552. this.bufferCount = bufferCount;
  7553. }
  7554. /**
  7555. * The data type of the buffer elements.
  7556. *
  7557. * @param {NodeBuilder} builder - The current node builder.
  7558. * @return {String} The element type.
  7559. */
  7560. getElementType( builder ) {
  7561. return this.getNodeType( builder );
  7562. }
  7563. /**
  7564. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7565. *
  7566. * @param {NodeBuilder} builder - The current node builder.
  7567. * @return {String} The input type.
  7568. */
  7569. getInputType( /*builder*/ ) {
  7570. return 'buffer';
  7571. }
  7572. }
  7573. /**
  7574. * TSL function for creating a buffer node.
  7575. *
  7576. * @function
  7577. * @param {Array} value - Array-like buffer data.
  7578. * @param {String} type - The data type of a buffer element.
  7579. * @param {Number} count - The count of buffer elements.
  7580. * @returns {BufferNode}
  7581. */
  7582. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7583. /** @module UniformArrayNode **/
  7584. /**
  7585. * Represents the element access on uniform array nodes.
  7586. *
  7587. * @augments ArrayElementNode
  7588. */
  7589. class UniformArrayElementNode extends ArrayElementNode {
  7590. static get type() {
  7591. return 'UniformArrayElementNode';
  7592. }
  7593. /**
  7594. * Constructs a new buffer node.
  7595. *
  7596. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7597. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7598. */
  7599. constructor( uniformArrayNode, indexNode ) {
  7600. super( uniformArrayNode, indexNode );
  7601. /**
  7602. * This flag can be used for type testing.
  7603. *
  7604. * @type {Boolean}
  7605. * @readonly
  7606. * @default true
  7607. */
  7608. this.isArrayBufferElementNode = true;
  7609. }
  7610. generate( builder ) {
  7611. const snippet = super.generate( builder );
  7612. const type = this.getNodeType();
  7613. const paddedType = this.node.getPaddedType();
  7614. return builder.format( snippet, paddedType, type );
  7615. }
  7616. }
  7617. /**
  7618. * Similar to {@link module:BufferNode~BufferNode} this module represents array-like data as
  7619. * uniform buffers. Unlike {@link module:BufferNode~BufferNode}, it can handle more common
  7620. * data types in the array (e.g `three.js` primitives) and automatically
  7621. * manage buffer padding. It should be the first choice when working with
  7622. * uniforms buffers.
  7623. * ```js
  7624. * const tintColors = uniformArray( [
  7625. * new Color( 1, 0, 0 ),
  7626. * new Color( 0, 1, 0 ),
  7627. * new Color( 0, 0, 1 )
  7628. * ], 'color' );
  7629. *
  7630. * const redColor = tintColors.element( 0 );
  7631. *
  7632. * @augments module:BufferNode~BufferNode
  7633. */
  7634. class UniformArrayNode extends BufferNode {
  7635. static get type() {
  7636. return 'UniformArrayNode';
  7637. }
  7638. /**
  7639. * Constructs a new uniform array node.
  7640. *
  7641. * @param {Array<Any>} value - Array holding the buffer data.
  7642. * @param {String?} [elementType=null] - The data type of a buffer element.
  7643. */
  7644. constructor( value, elementType = null ) {
  7645. super( null );
  7646. /**
  7647. * Array holding the buffer data. Unlike {@link module:BufferNode~BufferNode}, the array can
  7648. * hold number primitives as well as three.js objects like vectors, matrices
  7649. * or colors.
  7650. *
  7651. * @type {Array<Any>}
  7652. */
  7653. this.array = value;
  7654. /**
  7655. * The data type of an array element.
  7656. *
  7657. * @type {String}
  7658. */
  7659. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7660. /**
  7661. * The padded type. Uniform buffers must conform to a certain buffer layout
  7662. * so a separate type is computed to ensure correct buffer size.
  7663. *
  7664. * @type {String}
  7665. */
  7666. this.paddedType = this.getPaddedType();
  7667. /**
  7668. * Overwritten since uniform array nodes are updated per render.
  7669. *
  7670. * @type {String}
  7671. * @default 'render'
  7672. */
  7673. this.updateType = NodeUpdateType.RENDER;
  7674. /**
  7675. * This flag can be used for type testing.
  7676. *
  7677. * @type {Boolean}
  7678. * @readonly
  7679. * @default true
  7680. */
  7681. this.isArrayBufferNode = true;
  7682. }
  7683. /**
  7684. * This method is overwritten since the node type is inferred from the
  7685. * {@link module:UniformArrayNode~UniformArrayNode#paddedType}.
  7686. *
  7687. * @param {NodeBuilder} builder - The current node builder.
  7688. * @return {String} The node type.
  7689. */
  7690. getNodeType( /*builder*/ ) {
  7691. return this.paddedType;
  7692. }
  7693. /**
  7694. * The data type of the array elements.
  7695. *
  7696. * @param {NodeBuilder} builder - The current node builder.
  7697. * @return {String} The element type.
  7698. */
  7699. getElementType() {
  7700. return this.elementType;
  7701. }
  7702. /**
  7703. * Returns the padded type based on the element type.
  7704. *
  7705. * @return {String} The padded type.
  7706. */
  7707. getPaddedType() {
  7708. const elementType = this.elementType;
  7709. let paddedType = 'vec4';
  7710. if ( elementType === 'mat2' ) {
  7711. paddedType = 'mat2';
  7712. } else if ( /mat/.test( elementType ) === true ) {
  7713. paddedType = 'mat4';
  7714. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7715. paddedType = 'ivec4';
  7716. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7717. paddedType = 'uvec4';
  7718. }
  7719. return paddedType;
  7720. }
  7721. /**
  7722. * The update makes sure to correctly transfer the data from the (complex) objects
  7723. * in the array to the internal, correctly padded value buffer.
  7724. *
  7725. * @param {NodeFrame} frame - A reference to the current node frame.
  7726. */
  7727. update( /*frame*/ ) {
  7728. const { array, value } = this;
  7729. const elementType = this.elementType;
  7730. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7731. for ( let i = 0; i < array.length; i ++ ) {
  7732. const index = i * 4;
  7733. value[ index ] = array[ i ];
  7734. }
  7735. } else if ( elementType === 'color' ) {
  7736. for ( let i = 0; i < array.length; i ++ ) {
  7737. const index = i * 4;
  7738. const vector = array[ i ];
  7739. value[ index ] = vector.r;
  7740. value[ index + 1 ] = vector.g;
  7741. value[ index + 2 ] = vector.b || 0;
  7742. //value[ index + 3 ] = vector.a || 0;
  7743. }
  7744. } else if ( elementType === 'mat2' ) {
  7745. for ( let i = 0; i < array.length; i ++ ) {
  7746. const index = i * 4;
  7747. const matrix = array[ i ];
  7748. value[ index ] = matrix.elements[ 0 ];
  7749. value[ index + 1 ] = matrix.elements[ 1 ];
  7750. value[ index + 2 ] = matrix.elements[ 2 ];
  7751. value[ index + 3 ] = matrix.elements[ 3 ];
  7752. }
  7753. } else if ( elementType === 'mat3' ) {
  7754. for ( let i = 0; i < array.length; i ++ ) {
  7755. const index = i * 16;
  7756. const matrix = array[ i ];
  7757. value[ index ] = matrix.elements[ 0 ];
  7758. value[ index + 1 ] = matrix.elements[ 1 ];
  7759. value[ index + 2 ] = matrix.elements[ 2 ];
  7760. value[ index + 4 ] = matrix.elements[ 3 ];
  7761. value[ index + 5 ] = matrix.elements[ 4 ];
  7762. value[ index + 6 ] = matrix.elements[ 5 ];
  7763. value[ index + 8 ] = matrix.elements[ 6 ];
  7764. value[ index + 9 ] = matrix.elements[ 7 ];
  7765. value[ index + 10 ] = matrix.elements[ 8 ];
  7766. value[ index + 15 ] = 1;
  7767. }
  7768. } else if ( elementType === 'mat4' ) {
  7769. for ( let i = 0; i < array.length; i ++ ) {
  7770. const index = i * 16;
  7771. const matrix = array[ i ];
  7772. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7773. value[ index + i ] = matrix.elements[ i ];
  7774. }
  7775. }
  7776. } else {
  7777. for ( let i = 0; i < array.length; i ++ ) {
  7778. const index = i * 4;
  7779. const vector = array[ i ];
  7780. value[ index ] = vector.x;
  7781. value[ index + 1 ] = vector.y;
  7782. value[ index + 2 ] = vector.z || 0;
  7783. value[ index + 3 ] = vector.w || 0;
  7784. }
  7785. }
  7786. }
  7787. /**
  7788. * Implement the value buffer creation based on the array data.
  7789. *
  7790. * @param {NodeBuilder} builder - A reference to the current node builder.
  7791. * @return {null}
  7792. */
  7793. setup( builder ) {
  7794. const length = this.array.length;
  7795. const elementType = this.elementType;
  7796. let arrayType = Float32Array;
  7797. const paddedType = this.paddedType;
  7798. const paddedElementLength = builder.getTypeLength( paddedType );
  7799. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7800. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7801. this.value = new arrayType( length * paddedElementLength );
  7802. this.bufferCount = length;
  7803. this.bufferType = paddedType;
  7804. return super.setup( builder );
  7805. }
  7806. /**
  7807. * Overwrites the default `element()` method to provide element access
  7808. * based on {@link module:UniformArrayNode~UniformArrayNode}.
  7809. *
  7810. * @param {IndexNode} indexNode - The index node.
  7811. * @return {UniformArrayElementNode}
  7812. */
  7813. element( indexNode ) {
  7814. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7815. }
  7816. }
  7817. /**
  7818. * TSL function for creating an uniform array node.
  7819. *
  7820. * @function
  7821. * @param {Array<Any>} values - Array-like data.
  7822. * @param {String} nodeType - The data type of the array elements.
  7823. * @returns {UniformArrayNode}
  7824. */
  7825. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7826. /**
  7827. * @function
  7828. * @deprecated since r168. Use {@link uniformArray} instead.
  7829. *
  7830. * @param {Array<Any>} values - Array-like data.
  7831. * @param {String} nodeType - The data type of the array elements.
  7832. * @returns {UniformArrayNode}
  7833. */
  7834. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7835. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7836. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7837. };
  7838. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  7839. /** @module ReferenceNode **/
  7840. /**
  7841. * This class is only relevant if the referenced property is array-like.
  7842. * In this case, `ReferenceElementNode` allows to refer to a specific
  7843. * element inside the data structure via an index.
  7844. *
  7845. * @augments ArrayElementNode
  7846. */
  7847. class ReferenceElementNode extends ArrayElementNode {
  7848. static get type() {
  7849. return 'ReferenceElementNode';
  7850. }
  7851. /**
  7852. * Constructs a new reference element node.
  7853. *
  7854. * @param {Node?} referenceNode - The reference node.
  7855. * @param {Node} indexNode - The index node that defines the element access.
  7856. */
  7857. constructor( referenceNode, indexNode ) {
  7858. super( referenceNode, indexNode );
  7859. /**
  7860. * Similar to {@link module:ReferenceNode~ReferenceNode#reference}, an additional
  7861. * property references to the current node.
  7862. *
  7863. * @type {Node?}
  7864. * @default null
  7865. */
  7866. this.referenceNode = referenceNode;
  7867. /**
  7868. * This flag can be used for type testing.
  7869. *
  7870. * @type {Boolean}
  7871. * @readonly
  7872. * @default true
  7873. */
  7874. this.isReferenceElementNode = true;
  7875. }
  7876. /**
  7877. * This method is overwritten since the node type is inferred from
  7878. * the uniform type of the reference node.
  7879. *
  7880. * @param {NodeBuilder} builder - The current node builder.
  7881. * @return {String} The node type.
  7882. */
  7883. getNodeType() {
  7884. return this.referenceNode.uniformType;
  7885. }
  7886. generate( builder ) {
  7887. const snippet = super.generate( builder );
  7888. const arrayType = this.referenceNode.getNodeType();
  7889. const elementType = this.getNodeType();
  7890. return builder.format( snippet, arrayType, elementType );
  7891. }
  7892. }
  7893. /**
  7894. * This type of node establishes a reference to a property of another object.
  7895. * In this way, the value of the node is automatically linked to the value of
  7896. * referenced object. Reference nodes internally represent the linked value
  7897. * as a uniform.
  7898. *
  7899. * @augments Node
  7900. */
  7901. class ReferenceNode extends Node {
  7902. static get type() {
  7903. return 'ReferenceNode';
  7904. }
  7905. /**
  7906. * Constructs a new reference node.
  7907. *
  7908. * @param {String} property - The name of the property the node refers to.
  7909. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  7910. * @param {Object?} [object=null] - The object the property belongs to.
  7911. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  7912. */
  7913. constructor( property, uniformType, object = null, count = null ) {
  7914. super();
  7915. /**
  7916. * The name of the property the node refers to.
  7917. *
  7918. * @type {String}
  7919. */
  7920. this.property = property;
  7921. /**
  7922. * The uniform type that should be used to represent the property value.
  7923. *
  7924. * @type {String}
  7925. */
  7926. this.uniformType = uniformType;
  7927. /**
  7928. * The object the property belongs to.
  7929. *
  7930. * @type {Object?}
  7931. * @default null
  7932. */
  7933. this.object = object;
  7934. /**
  7935. * When the linked property is an array, this parameter defines its length.
  7936. *
  7937. * @type {Number?}
  7938. * @default null
  7939. */
  7940. this.count = count;
  7941. /**
  7942. * The property name might have dots so nested properties can be referred.
  7943. * The hierarchy of the names is stored inside this array.
  7944. *
  7945. * @type {Array<String>}
  7946. */
  7947. this.properties = property.split( '.' );
  7948. /**
  7949. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  7950. * since the final reference might be updated from calling code.
  7951. *
  7952. * @type {Object?}
  7953. * @default null
  7954. */
  7955. this.reference = object;
  7956. /**
  7957. * The uniform node that holds the value of the reference node.
  7958. *
  7959. * @type {UniformNode}
  7960. * @default null
  7961. */
  7962. this.node = null;
  7963. /**
  7964. * The uniform group of the internal uniform.
  7965. *
  7966. * @type {UniformGroupNode}
  7967. * @default null
  7968. */
  7969. this.group = null;
  7970. /**
  7971. * An optional label of the internal uniform node.
  7972. *
  7973. * @type {String?}
  7974. * @default null
  7975. */
  7976. this.name = null;
  7977. /**
  7978. * Overwritten since reference nodes are updated per object.
  7979. *
  7980. * @type {String}
  7981. * @default 'object'
  7982. */
  7983. this.updateType = NodeUpdateType.OBJECT;
  7984. }
  7985. /**
  7986. * When the referred property is array-like, this method can be used
  7987. * to access elements via an index node.
  7988. *
  7989. * @param {IndexNode} indexNode - indexNode.
  7990. * @return {ReferenceElementNode} A reference to an element.
  7991. */
  7992. element( indexNode ) {
  7993. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  7994. }
  7995. /**
  7996. * Sets the uniform group for this reference node.
  7997. *
  7998. * @param {UniformGroupNode} group - The uniform group to set.
  7999. * @return {ReferenceNode} A reference to this node.
  8000. */
  8001. setGroup( group ) {
  8002. this.group = group;
  8003. return this;
  8004. }
  8005. /**
  8006. * Sets the label for the internal uniform.
  8007. *
  8008. * @param {String} name - The label to set.
  8009. * @return {ReferenceNode} A reference to this node.
  8010. */
  8011. label( name ) {
  8012. this.name = name;
  8013. return this;
  8014. }
  8015. /**
  8016. * Sets the node type which automatically defines the internal
  8017. * uniform type.
  8018. *
  8019. * @param {String} uniformType - The type to set.
  8020. */
  8021. setNodeType( uniformType ) {
  8022. let node = null;
  8023. if ( this.count !== null ) {
  8024. node = buffer( null, uniformType, this.count );
  8025. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8026. node = uniformArray( null, uniformType );
  8027. } else if ( uniformType === 'texture' ) {
  8028. node = texture( null );
  8029. } else if ( uniformType === 'cubeTexture' ) {
  8030. node = cubeTexture( null );
  8031. } else {
  8032. node = uniform( null, uniformType );
  8033. }
  8034. if ( this.group !== null ) {
  8035. node.setGroup( this.group );
  8036. }
  8037. if ( this.name !== null ) node.label( this.name );
  8038. this.node = node.getSelf();
  8039. }
  8040. /**
  8041. * This method is overwritten since the node type is inferred from
  8042. * the type of the reference node.
  8043. *
  8044. * @param {NodeBuilder} builder - The current node builder.
  8045. * @return {String} The node type.
  8046. */
  8047. getNodeType( builder ) {
  8048. if ( this.node === null ) {
  8049. this.updateReference( builder );
  8050. this.updateValue();
  8051. }
  8052. return this.node.getNodeType( builder );
  8053. }
  8054. /**
  8055. * Returns the property value from the given referred object.
  8056. *
  8057. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8058. * @return {Any} The value.
  8059. */
  8060. getValueFromReference( object = this.reference ) {
  8061. const { properties } = this;
  8062. let value = object[ properties[ 0 ] ];
  8063. for ( let i = 1; i < properties.length; i ++ ) {
  8064. value = value[ properties[ i ] ];
  8065. }
  8066. return value;
  8067. }
  8068. /**
  8069. * Allows to update the reference based on the given state. The state is only
  8070. * evaluated {@link module:ReferenceNode~ReferenceNode#object} is not set.
  8071. *
  8072. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8073. * @return {Object} The updated reference.
  8074. */
  8075. updateReference( state ) {
  8076. this.reference = this.object !== null ? this.object : state.object;
  8077. return this.reference;
  8078. }
  8079. /**
  8080. * The output of the reference node is the internal uniform node.
  8081. *
  8082. * @param {NodeBuilder} builder - The current node builder.
  8083. * @return {UniformNode} The output node.
  8084. */
  8085. setup( /* builder */ ) {
  8086. this.updateValue();
  8087. return this.node;
  8088. }
  8089. /**
  8090. * Overwritten to to update the internal uniform value.
  8091. *
  8092. * @param {NodeFrame} frame - A reference to the current node frame.
  8093. */
  8094. update( /*frame*/ ) {
  8095. this.updateValue();
  8096. }
  8097. /**
  8098. * Retrieves the value from the referred object property and uses it
  8099. * to updated the internal uniform.
  8100. */
  8101. updateValue() {
  8102. if ( this.node === null ) this.setNodeType( this.uniformType );
  8103. const value = this.getValueFromReference();
  8104. if ( Array.isArray( value ) ) {
  8105. this.node.array = value;
  8106. } else {
  8107. this.node.value = value;
  8108. }
  8109. }
  8110. }
  8111. /**
  8112. * TSL function for creating a reference node.
  8113. *
  8114. * @function
  8115. * @param {String} name - The name of the property the node refers to.
  8116. * @param {String} type - The uniform type that should be used to represent the property value.
  8117. * @param {Object} object - The object the property belongs to.
  8118. * @returns {ReferenceNode}
  8119. */
  8120. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8121. /**
  8122. * TSL function for creating a reference node. Use this function if you want need a reference
  8123. * to an array-like property that should be represented as a uniform buffer.
  8124. *
  8125. * @function
  8126. * @param {String} name - The name of the property the node refers to.
  8127. * @param {String} type - The uniform type that should be used to represent the property value.
  8128. * @param {Number} count - The number of value inside the array-like object.
  8129. * @param {Object} object - An array-like object the property belongs to.
  8130. * @returns {ReferenceNode}
  8131. */
  8132. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8133. /** @module MaterialReferenceNode **/
  8134. /**
  8135. * This node is a special type of reference node which is intended
  8136. * for linking material properties with node values.
  8137. * ```js
  8138. * const opacityNode = materialReference( 'opacity', 'float', material );
  8139. * ```
  8140. * When changing `material.opacity`, the node value of `opacityNode` will
  8141. * automatically be updated.
  8142. *
  8143. * @augments module:ReferenceNode~ReferenceNode
  8144. */
  8145. class MaterialReferenceNode extends ReferenceNode {
  8146. static get type() {
  8147. return 'MaterialReferenceNode';
  8148. }
  8149. /**
  8150. * Constructs a new material reference node.
  8151. *
  8152. * @param {String} property - The name of the property the node refers to.
  8153. * @param {String} inputType - The uniform type that should be used to represent the property value.
  8154. * @param {Material?} [material=null] - The material the property belongs to. When no material is set,
  8155. * the node refers to the material of the current rendered object.
  8156. */
  8157. constructor( property, inputType, material = null ) {
  8158. super( property, inputType, material );
  8159. /**
  8160. * The material the property belongs to. When no material is set,
  8161. * the node refers to the material of the current rendered object.
  8162. *
  8163. * @type {Material?}
  8164. * @default null
  8165. */
  8166. this.material = material;
  8167. /**
  8168. * This flag can be used for type testing.
  8169. *
  8170. * @type {Boolean}
  8171. * @readonly
  8172. * @default true
  8173. */
  8174. this.isMaterialReferenceNode = true;
  8175. }
  8176. /**
  8177. * Updates the reference based on the given state. The state is only evaluated
  8178. * {@link module:MaterialReferenceNode~MaterialReferenceNode#material} is not set.
  8179. *
  8180. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8181. * @return {Object} The updated reference.
  8182. */
  8183. updateReference( state ) {
  8184. this.reference = this.material !== null ? this.material : state.material;
  8185. return this.reference;
  8186. }
  8187. }
  8188. /**
  8189. * TSL function for creating a material reference node.
  8190. *
  8191. * @function
  8192. * @param {String} name - The name of the property the node refers to.
  8193. * @param {String} type - The uniform type that should be used to represent the property value.
  8194. * @param {Material?} [material=null] - The material the property belongs to.
  8195. * When no material is set, the node refers to the material of the current rendered object.
  8196. * @returns {MaterialReferenceNode}
  8197. */
  8198. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8199. /** @module Tangent **/
  8200. /**
  8201. * TSL object that represents the tangent attribute of the current rendered object.
  8202. *
  8203. * @type {Node<vec4>}
  8204. */
  8205. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8206. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8207. builder.geometry.computeTangents();
  8208. }
  8209. return attribute( 'tangent', 'vec4' );
  8210. } )();
  8211. /**
  8212. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8213. *
  8214. * @type {Node<vec3>}
  8215. */
  8216. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8217. /**
  8218. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8219. *
  8220. * @type {Node<vec3>}
  8221. */
  8222. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8223. /**
  8224. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8225. *
  8226. * @type {Node<vec3>}
  8227. */
  8228. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8229. /**
  8230. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8231. *
  8232. * @type {Node<vec3>}
  8233. */
  8234. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8235. /**
  8236. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8237. *
  8238. * @type {Node<vec3>}
  8239. */
  8240. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8241. /** @module Bitangent **/
  8242. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8243. /**
  8244. * TSL object that represents the bitangent attribute of the current rendered object.
  8245. *
  8246. * @type {Node<vec3>}
  8247. */
  8248. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8249. /**
  8250. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8251. *
  8252. * @type {Node<vec3>}
  8253. */
  8254. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8255. /**
  8256. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8257. *
  8258. * @type {Node<vec4>}
  8259. */
  8260. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8261. /**
  8262. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8263. *
  8264. * @type {Node<vec4>}
  8265. */
  8266. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8267. /**
  8268. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8269. *
  8270. * @type {Node<vec4>}
  8271. */
  8272. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8273. /**
  8274. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8275. *
  8276. * @type {Node<vec4>}
  8277. */
  8278. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8279. /** @module AccessorsUtils **/
  8280. /**
  8281. * TSL object that represents the TBN matrix in view space.
  8282. *
  8283. * @type {Node<mat3>}
  8284. */
  8285. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8286. /**
  8287. * TSL object that represents the parallax direction.
  8288. *
  8289. * @type {Node<mat3>}
  8290. */
  8291. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8292. /**
  8293. * TSL function for computing parallax uv coordinates.
  8294. *
  8295. * @function
  8296. * @param {Node<vec2>} uv - A uv node.
  8297. * @param {Node<vec2>} scale - A scale node.
  8298. * @returns {Node<vec2>} Parallax uv coordinates.
  8299. */
  8300. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8301. /**
  8302. * TSL function for computing bent normals.
  8303. *
  8304. * @function
  8305. * @returns {Node<vec3>} Bent normals.
  8306. */
  8307. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8308. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8309. let bentNormal = anisotropyB.cross( positionViewDirection );
  8310. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8311. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8312. return bentNormal;
  8313. } )();
  8314. /** @module NormalMapNode **/
  8315. // Normal Mapping Without Precomputed Tangents
  8316. // http://www.thetenthplanet.de/archives/1180
  8317. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8318. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8319. const q0 = eye_pos.dFdx();
  8320. const q1 = eye_pos.dFdy();
  8321. const st0 = uv.dFdx();
  8322. const st1 = uv.dFdy();
  8323. const N = surf_norm; // normalized
  8324. const q1perp = q1.cross( N );
  8325. const q0perp = N.cross( q0 );
  8326. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8327. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8328. const det = T.dot( T ).max( B.dot( B ) );
  8329. const scale = faceDirection.mul( det.inverseSqrt() );
  8330. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8331. } );
  8332. /**
  8333. * This class can be used for applying normals maps to materials.
  8334. *
  8335. * ```js
  8336. * material.normalNode = normalMap( texture( normalTex ) );
  8337. * ```
  8338. *
  8339. * @augments TempNode
  8340. */
  8341. class NormalMapNode extends TempNode {
  8342. static get type() {
  8343. return 'NormalMapNode';
  8344. }
  8345. /**
  8346. * Constructs a new normal map node.
  8347. *
  8348. * @param {Node<vec3>} node - Represents the normal map data.
  8349. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8350. */
  8351. constructor( node, scaleNode = null ) {
  8352. super( 'vec3' );
  8353. /**
  8354. * Represents the normal map data.
  8355. *
  8356. * @type {Node<vec3>}
  8357. */
  8358. this.node = node;
  8359. /**
  8360. * Controls the intensity of the effect.
  8361. *
  8362. * @type {Node<vec2>?}
  8363. * @default null
  8364. */
  8365. this.scaleNode = scaleNode;
  8366. /**
  8367. * The normal map type.
  8368. *
  8369. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8370. * @default TangentSpaceNormalMap
  8371. */
  8372. this.normalMapType = TangentSpaceNormalMap;
  8373. }
  8374. setup( builder ) {
  8375. const { normalMapType, scaleNode } = this;
  8376. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8377. if ( scaleNode !== null ) {
  8378. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8379. }
  8380. let outputNode = null;
  8381. if ( normalMapType === ObjectSpaceNormalMap ) {
  8382. outputNode = transformNormalToView( normalMap );
  8383. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8384. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8385. if ( tangent === true ) {
  8386. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8387. } else {
  8388. outputNode = perturbNormal2Arb( {
  8389. eye_pos: positionView,
  8390. surf_norm: normalView,
  8391. mapN: normalMap,
  8392. uv: uv()
  8393. } );
  8394. }
  8395. }
  8396. return outputNode;
  8397. }
  8398. }
  8399. /**
  8400. * TSL function for creating a normal map node.
  8401. *
  8402. * @function
  8403. * @param {Node<vec3>} node - Represents the normal map data.
  8404. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8405. * @returns {NormalMapNode}
  8406. */
  8407. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8408. /** @module BumpMapNode **/
  8409. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8410. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8411. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8412. // It's used to preserve the same TextureNode instance
  8413. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8414. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8415. return vec2(
  8416. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8417. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8418. ).mul( bumpScale );
  8419. } );
  8420. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8421. const perturbNormalArb = Fn( ( inputs ) => {
  8422. const { surf_pos, surf_norm, dHdxy } = inputs;
  8423. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8424. const vSigmaX = surf_pos.dFdx().normalize();
  8425. const vSigmaY = surf_pos.dFdy().normalize();
  8426. const vN = surf_norm; // normalized
  8427. const R1 = vSigmaY.cross( vN );
  8428. const R2 = vN.cross( vSigmaX );
  8429. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8430. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8431. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8432. } );
  8433. /**
  8434. * This class can be used for applying bump maps to materials.
  8435. *
  8436. * ```js
  8437. * material.normalNode = bumpMap( texture( bumpTex ) );
  8438. * ```
  8439. *
  8440. * @augments TempNode
  8441. */
  8442. class BumpMapNode extends TempNode {
  8443. static get type() {
  8444. return 'BumpMapNode';
  8445. }
  8446. /**
  8447. * Constructs a new bump map node.
  8448. *
  8449. * @param {Node<float>} textureNode - Represents the bump map data.
  8450. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8451. */
  8452. constructor( textureNode, scaleNode = null ) {
  8453. super( 'vec3' );
  8454. /**
  8455. * Represents the bump map data.
  8456. *
  8457. * @type {Node<float>}
  8458. */
  8459. this.textureNode = textureNode;
  8460. /**
  8461. * Controls the intensity of the bump effect.
  8462. *
  8463. * @type {Node<float>?}
  8464. * @default null
  8465. */
  8466. this.scaleNode = scaleNode;
  8467. }
  8468. setup() {
  8469. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8470. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8471. return perturbNormalArb( {
  8472. surf_pos: positionView,
  8473. surf_norm: normalView,
  8474. dHdxy
  8475. } );
  8476. }
  8477. }
  8478. /**
  8479. * TSL function for creating a bump map node.
  8480. *
  8481. * @function
  8482. * @param {Node<float>} textureNode - Represents the bump map data.
  8483. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8484. * @returns {BumpMapNode}
  8485. */
  8486. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8487. /** @module MaterialNode **/
  8488. const _propertyCache = new Map();
  8489. /**
  8490. * This class should simplify the node access to material properties.
  8491. * It internal uses reference nodes to make sure changes to material
  8492. * properties are automatically reflected to predefined TSL objects
  8493. * like e.g. `materialColor`.
  8494. *
  8495. * @augments Node
  8496. */
  8497. class MaterialNode extends Node {
  8498. static get type() {
  8499. return 'MaterialNode';
  8500. }
  8501. /**
  8502. * Constructs a new material node.
  8503. *
  8504. * @param {String} scope - The scope defines what kind of material property is referred by the node.
  8505. */
  8506. constructor( scope ) {
  8507. super();
  8508. /**
  8509. * The scope defines what material property is referred by the node.
  8510. *
  8511. * @type {String}
  8512. */
  8513. this.scope = scope;
  8514. }
  8515. /**
  8516. * Returns a cached reference node for the given property and type.
  8517. *
  8518. * @param {String} property - The name of the material property.
  8519. * @param {String} type - The uniform type of the property.
  8520. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8521. */
  8522. getCache( property, type ) {
  8523. let node = _propertyCache.get( property );
  8524. if ( node === undefined ) {
  8525. node = materialReference( property, type );
  8526. _propertyCache.set( property, node );
  8527. }
  8528. return node;
  8529. }
  8530. /**
  8531. * Returns a float-typed material reference node for the given property name.
  8532. *
  8533. * @param {String} property - The name of the material property.
  8534. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8535. */
  8536. getFloat( property ) {
  8537. return this.getCache( property, 'float' );
  8538. }
  8539. /**
  8540. * Returns a color-typed material reference node for the given property name.
  8541. *
  8542. * @param {String} property - The name of the material property.
  8543. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8544. */
  8545. getColor( property ) {
  8546. return this.getCache( property, 'color' );
  8547. }
  8548. /**
  8549. * Returns a texture-typed material reference node for the given property name.
  8550. *
  8551. * @param {String} property - The name of the material property.
  8552. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8553. */
  8554. getTexture( property ) {
  8555. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8556. }
  8557. /**
  8558. * The node setup is done depending on the selected scope. Multiple material properties
  8559. * might be grouped into a single node composition if they logically belong together.
  8560. *
  8561. * @param {NodeBuilder} builder - The current node builder.
  8562. * @return {Node} The node representing the selected scope.
  8563. */
  8564. setup( builder ) {
  8565. const material = builder.context.material;
  8566. const scope = this.scope;
  8567. let node = null;
  8568. if ( scope === MaterialNode.COLOR ) {
  8569. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8570. if ( material.map && material.map.isTexture === true ) {
  8571. node = colorNode.mul( this.getTexture( 'map' ) );
  8572. } else {
  8573. node = colorNode;
  8574. }
  8575. } else if ( scope === MaterialNode.OPACITY ) {
  8576. const opacityNode = this.getFloat( scope );
  8577. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  8578. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  8579. } else {
  8580. node = opacityNode;
  8581. }
  8582. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  8583. if ( material.specularMap && material.specularMap.isTexture === true ) {
  8584. node = this.getTexture( 'specular' ).r;
  8585. } else {
  8586. node = float( 1 );
  8587. }
  8588. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  8589. const specularIntensityNode = this.getFloat( scope );
  8590. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  8591. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  8592. } else {
  8593. node = specularIntensityNode;
  8594. }
  8595. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  8596. const specularColorNode = this.getColor( scope );
  8597. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  8598. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  8599. } else {
  8600. node = specularColorNode;
  8601. }
  8602. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  8603. const roughnessNode = this.getFloat( scope );
  8604. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  8605. node = roughnessNode.mul( this.getTexture( scope ).g );
  8606. } else {
  8607. node = roughnessNode;
  8608. }
  8609. } else if ( scope === MaterialNode.METALNESS ) {
  8610. const metalnessNode = this.getFloat( scope );
  8611. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  8612. node = metalnessNode.mul( this.getTexture( scope ).b );
  8613. } else {
  8614. node = metalnessNode;
  8615. }
  8616. } else if ( scope === MaterialNode.EMISSIVE ) {
  8617. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  8618. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  8619. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  8620. node = emissiveNode.mul( this.getTexture( scope ) );
  8621. } else {
  8622. node = emissiveNode;
  8623. }
  8624. } else if ( scope === MaterialNode.NORMAL ) {
  8625. if ( material.normalMap ) {
  8626. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  8627. node.normalMapType = material.normalMapType;
  8628. } else if ( material.bumpMap ) {
  8629. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  8630. } else {
  8631. node = normalView;
  8632. }
  8633. } else if ( scope === MaterialNode.CLEARCOAT ) {
  8634. const clearcoatNode = this.getFloat( scope );
  8635. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  8636. node = clearcoatNode.mul( this.getTexture( scope ).r );
  8637. } else {
  8638. node = clearcoatNode;
  8639. }
  8640. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  8641. const clearcoatRoughnessNode = this.getFloat( scope );
  8642. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  8643. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  8644. } else {
  8645. node = clearcoatRoughnessNode;
  8646. }
  8647. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  8648. if ( material.clearcoatNormalMap ) {
  8649. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  8650. } else {
  8651. node = normalView;
  8652. }
  8653. } else if ( scope === MaterialNode.SHEEN ) {
  8654. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  8655. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  8656. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  8657. } else {
  8658. node = sheenNode;
  8659. }
  8660. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  8661. const sheenRoughnessNode = this.getFloat( scope );
  8662. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  8663. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  8664. } else {
  8665. node = sheenRoughnessNode;
  8666. }
  8667. node = node.clamp( 0.07, 1.0 );
  8668. } else if ( scope === MaterialNode.ANISOTROPY ) {
  8669. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  8670. const anisotropyPolar = this.getTexture( scope );
  8671. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  8672. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  8673. } else {
  8674. node = materialAnisotropyVector;
  8675. }
  8676. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  8677. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  8678. if ( material.iridescenceThicknessMap ) {
  8679. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  8680. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  8681. } else {
  8682. node = iridescenceThicknessMaximum;
  8683. }
  8684. } else if ( scope === MaterialNode.TRANSMISSION ) {
  8685. const transmissionNode = this.getFloat( scope );
  8686. if ( material.transmissionMap ) {
  8687. node = transmissionNode.mul( this.getTexture( scope ).r );
  8688. } else {
  8689. node = transmissionNode;
  8690. }
  8691. } else if ( scope === MaterialNode.THICKNESS ) {
  8692. const thicknessNode = this.getFloat( scope );
  8693. if ( material.thicknessMap ) {
  8694. node = thicknessNode.mul( this.getTexture( scope ).g );
  8695. } else {
  8696. node = thicknessNode;
  8697. }
  8698. } else if ( scope === MaterialNode.IOR ) {
  8699. node = this.getFloat( scope );
  8700. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  8701. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  8702. } else if ( scope === MaterialNode.AO ) {
  8703. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  8704. } else {
  8705. const outputType = this.getNodeType( builder );
  8706. node = this.getCache( scope, outputType );
  8707. }
  8708. return node;
  8709. }
  8710. }
  8711. MaterialNode.ALPHA_TEST = 'alphaTest';
  8712. MaterialNode.COLOR = 'color';
  8713. MaterialNode.OPACITY = 'opacity';
  8714. MaterialNode.SHININESS = 'shininess';
  8715. MaterialNode.SPECULAR = 'specular';
  8716. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  8717. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  8718. MaterialNode.SPECULAR_COLOR = 'specularColor';
  8719. MaterialNode.REFLECTIVITY = 'reflectivity';
  8720. MaterialNode.ROUGHNESS = 'roughness';
  8721. MaterialNode.METALNESS = 'metalness';
  8722. MaterialNode.NORMAL = 'normal';
  8723. MaterialNode.CLEARCOAT = 'clearcoat';
  8724. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  8725. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  8726. MaterialNode.EMISSIVE = 'emissive';
  8727. MaterialNode.ROTATION = 'rotation';
  8728. MaterialNode.SHEEN = 'sheen';
  8729. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  8730. MaterialNode.ANISOTROPY = 'anisotropy';
  8731. MaterialNode.IRIDESCENCE = 'iridescence';
  8732. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  8733. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  8734. MaterialNode.IOR = 'ior';
  8735. MaterialNode.TRANSMISSION = 'transmission';
  8736. MaterialNode.THICKNESS = 'thickness';
  8737. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  8738. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  8739. MaterialNode.LINE_SCALE = 'scale';
  8740. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  8741. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  8742. MaterialNode.LINE_WIDTH = 'linewidth';
  8743. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  8744. MaterialNode.POINT_SIZE = 'size';
  8745. MaterialNode.DISPERSION = 'dispersion';
  8746. MaterialNode.LIGHT_MAP = 'light';
  8747. MaterialNode.AO = 'ao';
  8748. /**
  8749. * TSL object that represents alpha test of the current material.
  8750. *
  8751. * @type {Node<float>}
  8752. */
  8753. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  8754. /**
  8755. * TSL object that represents the diffuse color of the current material.
  8756. * The value is composed via `color` * `map`.
  8757. *
  8758. * @type {Node<vec3>}
  8759. */
  8760. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  8761. /**
  8762. * TSL object that represents the shininess of the current material.
  8763. *
  8764. * @type {Node<float>}
  8765. */
  8766. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  8767. /**
  8768. * TSL object that represents the emissive color of the current material.
  8769. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  8770. *
  8771. * @type {Node<vec3>}
  8772. */
  8773. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  8774. /**
  8775. * TSL object that represents the opacity of the current material.
  8776. * The value is composed via `opacity` * `alphaMap`.
  8777. *
  8778. * @type {Node<float>}
  8779. */
  8780. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  8781. /**
  8782. * TSL object that represents the specular of the current material.
  8783. *
  8784. * @type {Node<vec3>}
  8785. */
  8786. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  8787. /**
  8788. * TSL object that represents the specular intensity of the current material.
  8789. * The value is composed via `specularIntensity` * `specularMap.a`.
  8790. *
  8791. * @type {Node<float>}
  8792. */
  8793. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  8794. /**
  8795. * TSL object that represents the specular color of the current material.
  8796. * The value is composed via `specularColor` * `specularMap.rgb`.
  8797. *
  8798. * @type {Node<vec3>}
  8799. */
  8800. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  8801. /**
  8802. * TSL object that represents the specular strength of the current material.
  8803. * The value is composed via `specularMap.r`.
  8804. *
  8805. * @type {Node<float>}
  8806. */
  8807. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  8808. /**
  8809. * TSL object that represents the reflectivity of the current material.
  8810. *
  8811. * @type {Node<float>}
  8812. */
  8813. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  8814. /**
  8815. * TSL object that represents the roughness of the current material.
  8816. * The value is composed via `roughness` * `roughnessMap.g`.
  8817. *
  8818. * @type {Node<float>}
  8819. */
  8820. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  8821. /**
  8822. * TSL object that represents the metalness of the current material.
  8823. * The value is composed via `metalness` * `metalnessMap.b`.
  8824. *
  8825. * @type {Node<float>}
  8826. */
  8827. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  8828. /**
  8829. * TSL object that represents the normal of the current material.
  8830. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  8831. *
  8832. * @type {Node<vec3>}
  8833. */
  8834. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  8835. /**
  8836. * TSL object that represents the clearcoat of the current material.
  8837. * The value is composed via `clearcoat` * `clearcoatMap.r`
  8838. *
  8839. * @type {Node<float>}
  8840. */
  8841. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  8842. /**
  8843. * TSL object that represents the clearcoat roughness of the current material.
  8844. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  8845. *
  8846. * @type {Node<float>}
  8847. */
  8848. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  8849. /**
  8850. * TSL object that represents the clearcoat normal of the current material.
  8851. * The value will be either `clearcoatNormalMap` or `normalView`.
  8852. *
  8853. * @type {Node<vec3>}
  8854. */
  8855. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  8856. /**
  8857. * TSL object that represents the rotation of the current sprite material.
  8858. *
  8859. * @type {Node<float>}
  8860. */
  8861. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  8862. /**
  8863. * TSL object that represents the sheen color of the current material.
  8864. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  8865. *
  8866. * @type {Node<vec3>}
  8867. */
  8868. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  8869. /**
  8870. * TSL object that represents the sheen roughness of the current material.
  8871. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  8872. *
  8873. * @type {Node<float>}
  8874. */
  8875. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  8876. /**
  8877. * TSL object that represents the anisotropy of the current material.
  8878. *
  8879. * @type {Node<vec2>}
  8880. */
  8881. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  8882. /**
  8883. * TSL object that represents the iridescence of the current material.
  8884. *
  8885. * @type {Node<float>}
  8886. */
  8887. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  8888. /**
  8889. * TSL object that represents the iridescence IOR of the current material.
  8890. *
  8891. * @type {Node<float>}
  8892. */
  8893. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  8894. /**
  8895. * TSL object that represents the iridescence thickness of the current material.
  8896. *
  8897. * @type {Node<float>}
  8898. */
  8899. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  8900. /**
  8901. * TSL object that represents the transmission of the current material.
  8902. * The value is composed via `transmission` * `transmissionMap.r`.
  8903. *
  8904. * @type {Node<float>}
  8905. */
  8906. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  8907. /**
  8908. * TSL object that represents the thickness of the current material.
  8909. * The value is composed via `thickness` * `thicknessMap.g`.
  8910. *
  8911. * @type {Node<float>}
  8912. */
  8913. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  8914. /**
  8915. * TSL object that represents the IOR of the current material.
  8916. *
  8917. * @type {Node<float>}
  8918. */
  8919. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  8920. /**
  8921. * TSL object that represents the attenuation distance of the current material.
  8922. *
  8923. * @type {Node<float>}
  8924. */
  8925. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  8926. /**
  8927. * TSL object that represents the attenuation color of the current material.
  8928. *
  8929. * @type {Node<vec3>}
  8930. */
  8931. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  8932. /**
  8933. * TSL object that represents the scale of the current dashed line material.
  8934. *
  8935. * @type {Node<float>}
  8936. */
  8937. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  8938. /**
  8939. * TSL object that represents the dash size of the current dashed line material.
  8940. *
  8941. * @type {Node<float>}
  8942. */
  8943. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  8944. /**
  8945. * TSL object that represents the gap size of the current dashed line material.
  8946. *
  8947. * @type {Node<float>}
  8948. */
  8949. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  8950. /**
  8951. * TSL object that represents the line width of the current line material.
  8952. *
  8953. * @type {Node<float>}
  8954. */
  8955. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  8956. /**
  8957. * TSL object that represents the dash offset of the current line material.
  8958. *
  8959. * @type {Node<float>}
  8960. */
  8961. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  8962. /**
  8963. * TSL object that represents the point size of the current points material.
  8964. *
  8965. * @type {Node<float>}
  8966. */
  8967. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  8968. /**
  8969. * TSL object that represents the dispersion of the current material.
  8970. *
  8971. * @type {Node<float>}
  8972. */
  8973. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  8974. /**
  8975. * TSL object that represents the light map of the current material.
  8976. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  8977. *
  8978. * @type {Node<vec3>}
  8979. */
  8980. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  8981. /**
  8982. * TSL object that represents the ambient occlusion map of the current material.
  8983. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  8984. *
  8985. * @type {Node<float>}
  8986. */
  8987. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  8988. /**
  8989. * TSL object that represents the anisotropy vector of the current material.
  8990. *
  8991. * @type {Node<vec2>}
  8992. */
  8993. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  8994. return frame.material;
  8995. } ).onRenderUpdate( function ( { material } ) {
  8996. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  8997. } );
  8998. /** @module ModelViewProjectionNode **/
  8999. /**
  9000. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9001. *
  9002. * @type {VaryingNode<vec4>}
  9003. */
  9004. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9005. return builder.context.setupModelViewProjection();
  9006. }, 'vec4' ).once() )().varying( 'v_modelViewProjection' );
  9007. /** @module IndexNode **/
  9008. /**
  9009. * This class represents shader indices of different types. The following predefined node
  9010. * objects cover frequent use cases:
  9011. *
  9012. * - `vertexIndex`: The index of a vertex within a mesh.
  9013. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  9014. * - `drawIndex`: The index of a draw call.
  9015. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  9016. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  9017. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  9018. *
  9019. * @augments Node
  9020. */
  9021. class IndexNode extends Node {
  9022. static get type() {
  9023. return 'IndexNode';
  9024. }
  9025. /**
  9026. * Constructs a new index node.
  9027. *
  9028. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  9029. */
  9030. constructor( scope ) {
  9031. super( 'uint' );
  9032. /**
  9033. * The scope of the index node.
  9034. *
  9035. * @type {String}
  9036. */
  9037. this.scope = scope;
  9038. /**
  9039. * This flag can be used for type testing.
  9040. *
  9041. * @type {Boolean}
  9042. * @readonly
  9043. * @default true
  9044. */
  9045. this.isIndexNode = true;
  9046. }
  9047. generate( builder ) {
  9048. const nodeType = this.getNodeType( builder );
  9049. const scope = this.scope;
  9050. let propertyName;
  9051. if ( scope === IndexNode.VERTEX ) {
  9052. propertyName = builder.getVertexIndex();
  9053. } else if ( scope === IndexNode.INSTANCE ) {
  9054. propertyName = builder.getInstanceIndex();
  9055. } else if ( scope === IndexNode.DRAW ) {
  9056. propertyName = builder.getDrawIndex();
  9057. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  9058. propertyName = builder.getInvocationLocalIndex();
  9059. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  9060. propertyName = builder.getInvocationSubgroupIndex();
  9061. } else if ( scope === IndexNode.SUBGROUP ) {
  9062. propertyName = builder.getSubgroupIndex();
  9063. } else {
  9064. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  9065. }
  9066. let output;
  9067. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  9068. output = propertyName;
  9069. } else {
  9070. const nodeVarying = varying( this );
  9071. output = nodeVarying.build( builder, nodeType );
  9072. }
  9073. return output;
  9074. }
  9075. }
  9076. IndexNode.VERTEX = 'vertex';
  9077. IndexNode.INSTANCE = 'instance';
  9078. IndexNode.SUBGROUP = 'subgroup';
  9079. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  9080. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  9081. IndexNode.DRAW = 'draw';
  9082. /**
  9083. * TSL object that represents the index of a vertex within a mesh.
  9084. *
  9085. * @type {IndexNode}
  9086. */
  9087. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  9088. /**
  9089. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  9090. *
  9091. * @type {IndexNode}
  9092. */
  9093. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  9094. /**
  9095. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  9096. *
  9097. * @type {IndexNode}
  9098. */
  9099. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  9100. /**
  9101. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  9102. *
  9103. * @type {IndexNode}
  9104. */
  9105. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  9106. /**
  9107. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  9108. *
  9109. * @type {IndexNode}
  9110. */
  9111. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  9112. /**
  9113. * TSL object that represents the index of a draw call.
  9114. *
  9115. * @type {IndexNode}
  9116. */
  9117. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9118. /** @module InstanceNode **/
  9119. /**
  9120. * This node implements the vertex shader logic which is required
  9121. * when rendering 3D objects via instancing. The code makes sure
  9122. * vertex positions, normals and colors can be modified via instanced
  9123. * data.
  9124. *
  9125. * @augments Node
  9126. */
  9127. class InstanceNode extends Node {
  9128. static get type() {
  9129. return 'InstanceNode';
  9130. }
  9131. /**
  9132. * Constructs a new instance node.
  9133. *
  9134. * @param {Number} count - The number of instances.
  9135. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9136. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9137. */
  9138. constructor( count, instanceMatrix, instanceColor ) {
  9139. super( 'void' );
  9140. /**
  9141. * The number of instances.
  9142. *
  9143. * @type {Number}
  9144. */
  9145. this.count = count;
  9146. /**
  9147. * Instanced buffer attribute representing the transformation of instances.
  9148. *
  9149. * @type {InstancedBufferAttribute}
  9150. */
  9151. this.instanceMatrix = instanceMatrix;
  9152. /**
  9153. * Instanced buffer attribute representing the color of instances.
  9154. *
  9155. * @type {InstancedBufferAttribute}
  9156. */
  9157. this.instanceColor = instanceColor;
  9158. /**
  9159. * The node that represents the instance matrix data.
  9160. *
  9161. * @type {Node}
  9162. */
  9163. this.instanceMatrixNode = null;
  9164. /**
  9165. * The node that represents the instance color data.
  9166. *
  9167. * @type {Node}
  9168. */
  9169. this.instanceColorNode = null;
  9170. /**
  9171. * The update type is set to `frame` since an update
  9172. * of instanced buffer data must be checked per frame.
  9173. *
  9174. * @type {String}
  9175. * @default 'frame'
  9176. */
  9177. this.updateType = NodeUpdateType.FRAME;
  9178. /**
  9179. * A reference to a buffer that is used by `instanceMatrixNode`.
  9180. *
  9181. * @type {InstancedInterleavedBuffer}
  9182. */
  9183. this.buffer = null;
  9184. /**
  9185. * A reference to a buffer that is used by `instanceColorNode`.
  9186. *
  9187. * @type {InstancedInterleavedBuffer}
  9188. */
  9189. this.bufferColor = null;
  9190. }
  9191. /**
  9192. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9193. * to predefined node variables for accumulation. That follows the same patterns
  9194. * like with morph and skinning nodes.
  9195. *
  9196. * @param {NodeBuilder} builder - The current node builder.
  9197. */
  9198. setup( builder ) {
  9199. const { count, instanceMatrix, instanceColor } = this;
  9200. let { instanceMatrixNode, instanceColorNode } = this;
  9201. if ( instanceMatrixNode === null ) {
  9202. // 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.
  9203. if ( count <= 1000 ) {
  9204. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9205. } else {
  9206. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9207. this.buffer = buffer;
  9208. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9209. const instanceBuffers = [
  9210. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9211. bufferFn( buffer, 'vec4', 16, 0 ),
  9212. bufferFn( buffer, 'vec4', 16, 4 ),
  9213. bufferFn( buffer, 'vec4', 16, 8 ),
  9214. bufferFn( buffer, 'vec4', 16, 12 )
  9215. ];
  9216. instanceMatrixNode = mat4( ...instanceBuffers );
  9217. }
  9218. this.instanceMatrixNode = instanceMatrixNode;
  9219. }
  9220. if ( instanceColor && instanceColorNode === null ) {
  9221. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9222. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9223. this.bufferColor = buffer;
  9224. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9225. this.instanceColorNode = instanceColorNode;
  9226. }
  9227. // POSITION
  9228. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9229. positionLocal.assign( instancePosition );
  9230. // NORMAL
  9231. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9232. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9233. // ASSIGNS
  9234. normalLocal.assign( instanceNormal );
  9235. }
  9236. // COLOR
  9237. if ( this.instanceColorNode !== null ) {
  9238. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9239. }
  9240. }
  9241. /**
  9242. * Checks if the internal buffers required an update.
  9243. *
  9244. * @param {NodeFrame} frame - The current node frame.
  9245. */
  9246. update( /*frame*/ ) {
  9247. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9248. this.buffer.version = this.instanceMatrix.version;
  9249. }
  9250. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9251. this.bufferColor.version = this.instanceColor.version;
  9252. }
  9253. }
  9254. }
  9255. /**
  9256. * TSL function for creating an instance node.
  9257. *
  9258. * @function
  9259. * @param {Number} count - The number of instances.
  9260. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9261. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9262. * @returns {InstanceNode}
  9263. */
  9264. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9265. /** @module InstancedMeshNode **/
  9266. /**
  9267. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9268. * It allows an easier setup of the instance node.
  9269. *
  9270. * @augments module:InstanceNode~InstanceNode
  9271. */
  9272. class InstancedMeshNode extends InstanceNode {
  9273. static get type() {
  9274. return 'InstancedMeshNode';
  9275. }
  9276. /**
  9277. * Constructs a new instanced mesh node.
  9278. *
  9279. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9280. */
  9281. constructor( instancedMesh ) {
  9282. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9283. super( count, instanceMatrix, instanceColor );
  9284. /**
  9285. * A reference to the instanced mesh.
  9286. *
  9287. * @type {InstancedMesh}
  9288. */
  9289. this.instancedMesh = instancedMesh;
  9290. }
  9291. }
  9292. /**
  9293. * TSL function for creating an instanced mesh node.
  9294. *
  9295. * @function
  9296. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9297. * @returns {InstancedMeshNode}
  9298. */
  9299. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9300. /** @module BatchNode **/
  9301. /**
  9302. * This node implements the vertex shader logic which is required
  9303. * when rendering 3D objects via batching. `BatchNode` must be used
  9304. * with instances of {@link BatchedMesh}.
  9305. *
  9306. * @augments Node
  9307. */
  9308. class BatchNode extends Node {
  9309. static get type() {
  9310. return 'BatchNode';
  9311. }
  9312. /**
  9313. * Constructs a new batch node.
  9314. *
  9315. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9316. */
  9317. constructor( batchMesh ) {
  9318. super( 'void' );
  9319. /**
  9320. * A reference to batched mesh.
  9321. *
  9322. * @type {BatchedMesh}
  9323. */
  9324. this.batchMesh = batchMesh;
  9325. /**
  9326. * The batching index node.
  9327. *
  9328. * @type {IndexNode?}
  9329. * @default null
  9330. */
  9331. this.batchingIdNode = null;
  9332. }
  9333. /**
  9334. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9335. * to predefined node variables for accumulation. That follows the same patterns
  9336. * like with morph and skinning nodes.
  9337. *
  9338. * @param {NodeBuilder} builder - The current node builder.
  9339. */
  9340. setup( builder ) {
  9341. if ( this.batchingIdNode === null ) {
  9342. if ( builder.getDrawIndex() === null ) {
  9343. this.batchingIdNode = instanceIndex;
  9344. } else {
  9345. this.batchingIdNode = drawIndex;
  9346. }
  9347. }
  9348. const getIndirectIndex = Fn( ( [ id ] ) => {
  9349. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  9350. const x = int( id ).modInt( int( size ) );
  9351. const y = int( id ).div( int( size ) );
  9352. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9353. } ).setLayout( {
  9354. name: 'getIndirectIndex',
  9355. type: 'uint',
  9356. inputs: [
  9357. { name: 'id', type: 'int' }
  9358. ]
  9359. } );
  9360. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9361. const matricesTexture = this.batchMesh._matricesTexture;
  9362. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9363. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9364. const x = j.modInt( size );
  9365. const y = j.div( int( size ) );
  9366. const batchingMatrix = mat4(
  9367. textureLoad( matricesTexture, ivec2( x, y ) ),
  9368. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9369. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9370. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9371. );
  9372. const colorsTexture = this.batchMesh._colorsTexture;
  9373. if ( colorsTexture !== null ) {
  9374. const getBatchingColor = Fn( ( [ id ] ) => {
  9375. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9376. const j = id;
  9377. const x = j.modInt( size );
  9378. const y = j.div( size );
  9379. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9380. } ).setLayout( {
  9381. name: 'getBatchingColor',
  9382. type: 'vec3',
  9383. inputs: [
  9384. { name: 'id', type: 'int' }
  9385. ]
  9386. } );
  9387. const color = getBatchingColor( indirectId );
  9388. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9389. }
  9390. const bm = mat3( batchingMatrix );
  9391. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9392. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9393. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9394. normalLocal.assign( batchingNormal );
  9395. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9396. tangentLocal.mulAssign( bm );
  9397. }
  9398. }
  9399. }
  9400. /**
  9401. * TSL function for creating a batch node.
  9402. *
  9403. * @function
  9404. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9405. * @returns {BatchNode}
  9406. */
  9407. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9408. /** @module SkinningNode **/
  9409. const _frameId = new WeakMap();
  9410. /**
  9411. * This node implements the vertex transformation shader logic which is required
  9412. * for skinning/skeletal animation.
  9413. *
  9414. * @augments Node
  9415. */
  9416. class SkinningNode extends Node {
  9417. static get type() {
  9418. return 'SkinningNode';
  9419. }
  9420. /**
  9421. * Constructs a new skinning node.
  9422. *
  9423. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9424. * @param {Boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9425. */
  9426. constructor( skinnedMesh, useReference = false ) {
  9427. super( 'void' );
  9428. /**
  9429. * The skinned mesh.
  9430. *
  9431. * @type {SkinnedMesh}
  9432. */
  9433. this.skinnedMesh = skinnedMesh;
  9434. /**
  9435. * Whether to use reference nodes for internal skinned mesh related data or not.
  9436. * TODO: Explain the purpose of the property.
  9437. *
  9438. * @type {Boolean}
  9439. */
  9440. this.useReference = useReference;
  9441. /**
  9442. * The update type overwritten since skinning nodes are updated per object.
  9443. *
  9444. * @type {String}
  9445. */
  9446. this.updateType = NodeUpdateType.OBJECT;
  9447. //
  9448. /**
  9449. * The skin index attribute.
  9450. *
  9451. * @type {AttributeNode}
  9452. */
  9453. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9454. /**
  9455. * The skin weight attribute.
  9456. *
  9457. * @type {AttributeNode}
  9458. */
  9459. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9460. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9461. if ( useReference ) {
  9462. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9463. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9464. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9465. } else {
  9466. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9467. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9468. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9469. }
  9470. /**
  9471. * The bind matrix node.
  9472. *
  9473. * @type {Node<mat4>}
  9474. */
  9475. this.bindMatrixNode = bindMatrixNode;
  9476. /**
  9477. * The bind matrix inverse node.
  9478. *
  9479. * @type {Node<mat4>}
  9480. */
  9481. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9482. /**
  9483. * The bind matrices as a uniform buffer node.
  9484. *
  9485. * @type {Node}
  9486. */
  9487. this.boneMatricesNode = boneMatricesNode;
  9488. /**
  9489. * The previous bind matrices as a uniform buffer node.
  9490. * Required for computing motion vectors.
  9491. *
  9492. * @type {Node?}
  9493. * @default null
  9494. */
  9495. this.previousBoneMatricesNode = null;
  9496. }
  9497. /**
  9498. * Transforms the given vertex position via skinning.
  9499. *
  9500. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9501. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9502. * @return {Node<vec3>} The transformed vertex position.
  9503. */
  9504. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9505. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9506. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9507. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9508. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9509. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9510. // POSITION
  9511. const skinVertex = bindMatrixNode.mul( position );
  9512. const skinned = add(
  9513. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9514. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9515. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9516. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9517. );
  9518. return bindMatrixInverseNode.mul( skinned ).xyz;
  9519. }
  9520. /**
  9521. * Transforms the given vertex normal via skinning.
  9522. *
  9523. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9524. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9525. * @return {Node<vec3>} The transformed vertex normal.
  9526. */
  9527. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9528. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9529. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9530. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9531. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9532. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9533. // NORMAL
  9534. let skinMatrix = add(
  9535. skinWeightNode.x.mul( boneMatX ),
  9536. skinWeightNode.y.mul( boneMatY ),
  9537. skinWeightNode.z.mul( boneMatZ ),
  9538. skinWeightNode.w.mul( boneMatW )
  9539. );
  9540. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  9541. return skinMatrix.transformDirection( normal ).xyz;
  9542. }
  9543. /**
  9544. * Transforms the given vertex normal via skinning.
  9545. *
  9546. * @param {NodeBuilder} builder - The current node builder.
  9547. * @return {Node<vec3>} The skinned position from the previous frame.
  9548. */
  9549. getPreviousSkinnedPosition( builder ) {
  9550. const skinnedMesh = builder.object;
  9551. if ( this.previousBoneMatricesNode === null ) {
  9552. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  9553. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9554. }
  9555. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  9556. }
  9557. /**
  9558. * Returns `true` if bone matrices from the previous frame are required.
  9559. *
  9560. * @param {NodeBuilder} builder - The current node builder.
  9561. * @return {Boolean} Whether bone matrices from the previous frame are required or not.
  9562. */
  9563. needsPreviousBoneMatrices( builder ) {
  9564. const mrt = builder.renderer.getMRT();
  9565. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  9566. }
  9567. /**
  9568. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  9569. *
  9570. * @param {NodeBuilder} builder - The current node builder.
  9571. */
  9572. setup( builder ) {
  9573. if ( this.needsPreviousBoneMatrices( builder ) ) {
  9574. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  9575. }
  9576. const skinPosition = this.getSkinnedPosition();
  9577. positionLocal.assign( skinPosition );
  9578. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9579. const skinNormal = this.getSkinnedNormal();
  9580. normalLocal.assign( skinNormal );
  9581. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9582. tangentLocal.assign( skinNormal );
  9583. }
  9584. }
  9585. }
  9586. /**
  9587. * Generates the code snippet of the skinning node.
  9588. *
  9589. * @param {NodeBuilder} builder - The current node builder.
  9590. * @param {String} output - The current output.
  9591. * @return {String} The generated code snippet.
  9592. */
  9593. generate( builder, output ) {
  9594. if ( output !== 'void' ) {
  9595. return positionLocal.build( builder, output );
  9596. }
  9597. }
  9598. /**
  9599. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  9600. *
  9601. * @param {NodeFrame} frame - The current node frame.
  9602. */
  9603. update( frame ) {
  9604. const object = this.useReference ? frame.object : this.skinnedMesh;
  9605. const skeleton = object.skeleton;
  9606. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  9607. _frameId.set( skeleton, frame.frameId );
  9608. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  9609. skeleton.update();
  9610. }
  9611. }
  9612. /**
  9613. * TSL function for creating a skinning node.
  9614. *
  9615. * @function
  9616. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9617. * @returns {SkinningNode}
  9618. */
  9619. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  9620. /**
  9621. * TSL function for creating a skinning node with reference usage.
  9622. *
  9623. * @function
  9624. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9625. * @returns {SkinningNode}
  9626. */
  9627. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  9628. /** @module LoopNode **/
  9629. /**
  9630. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  9631. * ```js
  9632. * Loop( count, ( { i } ) => {
  9633. *
  9634. * } );
  9635. * ```
  9636. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  9637. * ```js
  9638. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  9639. *
  9640. * } );
  9641. *```
  9642. * Nested loops can be defined in a compacted form:
  9643. * ```js
  9644. * Loop( 10, 5, ( { i, j } ) => {
  9645. *
  9646. * } );
  9647. * ```
  9648. * Loops that should run backwards can be defined like so:
  9649. * ```js
  9650. * Loop( { start: 10 }, () => {} );
  9651. * ```
  9652. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  9653. * @augments Node
  9654. */
  9655. class LoopNode extends Node {
  9656. static get type() {
  9657. return 'LoopNode';
  9658. }
  9659. /**
  9660. * Constructs a new loop node.
  9661. *
  9662. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  9663. */
  9664. constructor( params = [] ) {
  9665. super();
  9666. this.params = params;
  9667. }
  9668. /**
  9669. * Returns a loop variable name based on an index. The pattern is
  9670. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  9671. *
  9672. * @param {Number} index - The index.
  9673. * @return {String} The loop variable name.
  9674. */
  9675. getVarName( index ) {
  9676. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  9677. }
  9678. /**
  9679. * Returns properties about this node.
  9680. *
  9681. * @param {NodeBuilder} builder - The current node builder.
  9682. * @return {Object} The node properties.
  9683. */
  9684. getProperties( builder ) {
  9685. const properties = builder.getNodeProperties( this );
  9686. if ( properties.stackNode !== undefined ) return properties;
  9687. //
  9688. const inputs = {};
  9689. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9690. const param = this.params[ i ];
  9691. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  9692. const type = ( param.isNode !== true && param.type ) || 'int';
  9693. inputs[ name ] = expression( name, type );
  9694. }
  9695. const stack = builder.addStack(); // TODO: cache() it
  9696. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  9697. properties.stackNode = stack;
  9698. builder.removeStack();
  9699. return properties;
  9700. }
  9701. /**
  9702. * This method is overwritten since the node type is inferred based on the loop configuration.
  9703. *
  9704. * @param {NodeBuilder} builder - The current node builder.
  9705. * @return {String} The node type.
  9706. */
  9707. getNodeType( builder ) {
  9708. const { returnsNode } = this.getProperties( builder );
  9709. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  9710. }
  9711. setup( builder ) {
  9712. // setup properties
  9713. this.getProperties( builder );
  9714. }
  9715. generate( builder ) {
  9716. const properties = this.getProperties( builder );
  9717. const params = this.params;
  9718. const stackNode = properties.stackNode;
  9719. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  9720. const param = params[ i ];
  9721. let start = null, end = null, name = null, type = null, condition = null, update = null;
  9722. if ( param.isNode ) {
  9723. type = 'int';
  9724. name = this.getVarName( i );
  9725. start = '0';
  9726. end = param.build( builder, type );
  9727. condition = '<';
  9728. } else {
  9729. type = param.type || 'int';
  9730. name = param.name || this.getVarName( i );
  9731. start = param.start;
  9732. end = param.end;
  9733. condition = param.condition;
  9734. update = param.update;
  9735. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  9736. else if ( start && start.isNode ) start = start.build( builder, type );
  9737. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  9738. else if ( end && end.isNode ) end = end.build( builder, type );
  9739. if ( start !== undefined && end === undefined ) {
  9740. start = start + ' - 1';
  9741. end = '0';
  9742. condition = '>=';
  9743. } else if ( end !== undefined && start === undefined ) {
  9744. start = '0';
  9745. condition = '<';
  9746. }
  9747. if ( condition === undefined ) {
  9748. if ( Number( start ) > Number( end ) ) {
  9749. condition = '>=';
  9750. } else {
  9751. condition = '<';
  9752. }
  9753. }
  9754. }
  9755. const internalParam = { start, end, condition };
  9756. //
  9757. const startSnippet = internalParam.start;
  9758. const endSnippet = internalParam.end;
  9759. let declarationSnippet = '';
  9760. let conditionalSnippet = '';
  9761. let updateSnippet = '';
  9762. if ( ! update ) {
  9763. if ( type === 'int' || type === 'uint' ) {
  9764. if ( condition.includes( '<' ) ) update = '++';
  9765. else update = '--';
  9766. } else {
  9767. if ( condition.includes( '<' ) ) update = '+= 1.';
  9768. else update = '-= 1.';
  9769. }
  9770. }
  9771. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  9772. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  9773. updateSnippet += name + ' ' + update;
  9774. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  9775. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  9776. }
  9777. const stackSnippet = stackNode.build( builder, 'void' );
  9778. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  9779. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  9780. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9781. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  9782. }
  9783. builder.addFlowTab();
  9784. return returnsSnippet;
  9785. }
  9786. }
  9787. /**
  9788. * TSL function for creating a loop node.
  9789. *
  9790. * @function
  9791. * @param {...Any} params - A list of parameters.
  9792. * @returns {LoopNode}
  9793. */
  9794. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  9795. /**
  9796. * TSL function for creating a `Continue()` expression.
  9797. *
  9798. * @function
  9799. * @returns {ExpressionNode}
  9800. */
  9801. const Continue = () => expression( 'continue' ).append();
  9802. /**
  9803. * TSL function for creating a `Break()` expression.
  9804. *
  9805. * @function
  9806. * @returns {ExpressionNode}
  9807. */
  9808. const Break = () => expression( 'break' ).append();
  9809. // deprecated
  9810. /**
  9811. * @function
  9812. * @deprecated since r168. Use {@link Loop} instead.
  9813. *
  9814. * @param {...any} params
  9815. * @returns {LoopNode}
  9816. */
  9817. const loop = ( ...params ) => { // @deprecated, r168
  9818. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  9819. return Loop( ...params );
  9820. };
  9821. /** @module MorphNode **/
  9822. const _morphTextures = /*@__PURE__*/ new WeakMap();
  9823. const _morphVec4 = /*@__PURE__*/ new Vector4();
  9824. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  9825. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  9826. const y = texelIndex.div( width );
  9827. const x = texelIndex.sub( y.mul( width ) );
  9828. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  9829. return bufferAttrib.mul( influence );
  9830. } );
  9831. function getEntry( geometry ) {
  9832. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9833. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  9834. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  9835. // instead of using attributes, the WebGL 2 code path encodes morph targets
  9836. // into an array of data textures. Each layer represents a single morph target.
  9837. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9838. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9839. let entry = _morphTextures.get( geometry );
  9840. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  9841. if ( entry !== undefined ) entry.texture.dispose();
  9842. const morphTargets = geometry.morphAttributes.position || [];
  9843. const morphNormals = geometry.morphAttributes.normal || [];
  9844. const morphColors = geometry.morphAttributes.color || [];
  9845. let vertexDataCount = 0;
  9846. if ( hasMorphPosition === true ) vertexDataCount = 1;
  9847. if ( hasMorphNormals === true ) vertexDataCount = 2;
  9848. if ( hasMorphColors === true ) vertexDataCount = 3;
  9849. let width = geometry.attributes.position.count * vertexDataCount;
  9850. let height = 1;
  9851. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  9852. if ( width > maxTextureSize ) {
  9853. height = Math.ceil( width / maxTextureSize );
  9854. width = maxTextureSize;
  9855. }
  9856. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  9857. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  9858. bufferTexture.type = FloatType;
  9859. bufferTexture.needsUpdate = true;
  9860. // fill buffer
  9861. const vertexDataStride = vertexDataCount * 4;
  9862. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  9863. const morphTarget = morphTargets[ i ];
  9864. const morphNormal = morphNormals[ i ];
  9865. const morphColor = morphColors[ i ];
  9866. const offset = width * height * 4 * i;
  9867. for ( let j = 0; j < morphTarget.count; j ++ ) {
  9868. const stride = j * vertexDataStride;
  9869. if ( hasMorphPosition === true ) {
  9870. _morphVec4.fromBufferAttribute( morphTarget, j );
  9871. buffer[ offset + stride + 0 ] = _morphVec4.x;
  9872. buffer[ offset + stride + 1 ] = _morphVec4.y;
  9873. buffer[ offset + stride + 2 ] = _morphVec4.z;
  9874. buffer[ offset + stride + 3 ] = 0;
  9875. }
  9876. if ( hasMorphNormals === true ) {
  9877. _morphVec4.fromBufferAttribute( morphNormal, j );
  9878. buffer[ offset + stride + 4 ] = _morphVec4.x;
  9879. buffer[ offset + stride + 5 ] = _morphVec4.y;
  9880. buffer[ offset + stride + 6 ] = _morphVec4.z;
  9881. buffer[ offset + stride + 7 ] = 0;
  9882. }
  9883. if ( hasMorphColors === true ) {
  9884. _morphVec4.fromBufferAttribute( morphColor, j );
  9885. buffer[ offset + stride + 8 ] = _morphVec4.x;
  9886. buffer[ offset + stride + 9 ] = _morphVec4.y;
  9887. buffer[ offset + stride + 10 ] = _morphVec4.z;
  9888. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  9889. }
  9890. }
  9891. }
  9892. entry = {
  9893. count: morphTargetsCount,
  9894. texture: bufferTexture,
  9895. stride: vertexDataCount,
  9896. size: new Vector2( width, height )
  9897. };
  9898. _morphTextures.set( geometry, entry );
  9899. function disposeTexture() {
  9900. bufferTexture.dispose();
  9901. _morphTextures.delete( geometry );
  9902. geometry.removeEventListener( 'dispose', disposeTexture );
  9903. }
  9904. geometry.addEventListener( 'dispose', disposeTexture );
  9905. }
  9906. return entry;
  9907. }
  9908. /**
  9909. * This node implements the vertex transformation shader logic which is required
  9910. * for morph target animation.
  9911. *
  9912. * @augments Node
  9913. */
  9914. class MorphNode extends Node {
  9915. static get type() {
  9916. return 'MorphNode';
  9917. }
  9918. /**
  9919. * Constructs a new morph node.
  9920. *
  9921. * @param {Mesh} mesh - The mesh holding the morph targets.
  9922. */
  9923. constructor( mesh ) {
  9924. super( 'void' );
  9925. /**
  9926. * The mesh holding the morph targets.
  9927. *
  9928. * @type {Mesh}
  9929. */
  9930. this.mesh = mesh;
  9931. /**
  9932. * A uniform node which represents the morph base influence value.
  9933. *
  9934. * @type {UniformNode<float>}
  9935. */
  9936. this.morphBaseInfluence = uniform( 1 );
  9937. /**
  9938. * The update type overwritten since morph nodes are updated per object.
  9939. *
  9940. * @type {String}
  9941. */
  9942. this.updateType = NodeUpdateType.OBJECT;
  9943. }
  9944. /**
  9945. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  9946. *
  9947. * @param {NodeBuilder} builder - The current node builder.
  9948. */
  9949. setup( builder ) {
  9950. const { geometry } = builder;
  9951. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9952. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  9953. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9954. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9955. // nodes
  9956. const { texture: bufferMap, stride, size } = getEntry( geometry );
  9957. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  9958. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  9959. const width = int( size.width );
  9960. Loop( morphTargetsCount, ( { i } ) => {
  9961. const influence = float( 0 ).toVar();
  9962. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  9963. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  9964. } else {
  9965. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  9966. }
  9967. if ( hasMorphPosition === true ) {
  9968. positionLocal.addAssign( getMorph( {
  9969. bufferMap,
  9970. influence,
  9971. stride,
  9972. width,
  9973. depth: i,
  9974. offset: int( 0 )
  9975. } ) );
  9976. }
  9977. if ( hasMorphNormals === true ) {
  9978. normalLocal.addAssign( getMorph( {
  9979. bufferMap,
  9980. influence,
  9981. stride,
  9982. width,
  9983. depth: i,
  9984. offset: int( 1 )
  9985. } ) );
  9986. }
  9987. } );
  9988. }
  9989. /**
  9990. * Updates the state of the morphed mesh by updating the base influence.
  9991. *
  9992. * @param {NodeFrame} frame - The current node frame.
  9993. */
  9994. update( /*frame*/ ) {
  9995. const morphBaseInfluence = this.morphBaseInfluence;
  9996. if ( this.mesh.geometry.morphTargetsRelative ) {
  9997. morphBaseInfluence.value = 1;
  9998. } else {
  9999. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  10000. }
  10001. }
  10002. }
  10003. /**
  10004. * TSL function for creating a morph node.
  10005. *
  10006. * @function
  10007. * @param {Mesh} mesh - The mesh holding the morph targets.
  10008. * @returns {MorphNode}
  10009. */
  10010. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  10011. /**
  10012. * Base class for lighting nodes.
  10013. *
  10014. * @augments Node
  10015. */
  10016. class LightingNode extends Node {
  10017. static get type() {
  10018. return 'LightingNode';
  10019. }
  10020. /**
  10021. * Constructs a new lighting node.
  10022. */
  10023. constructor() {
  10024. super( 'vec3' );
  10025. /**
  10026. * This flag can be used for type testing.
  10027. *
  10028. * @type {Boolean}
  10029. * @readonly
  10030. * @default true
  10031. */
  10032. this.isLightingNode = true;
  10033. }
  10034. }
  10035. /**
  10036. * A generic class that can be used by nodes which contribute
  10037. * ambient occlusion to the scene. E.g. an ambient occlusion map
  10038. * node can be used as input for this module. Used in {@link NodeMaterial}.
  10039. *
  10040. * @augments LightingNode
  10041. */
  10042. class AONode extends LightingNode {
  10043. static get type() {
  10044. return 'AONode';
  10045. }
  10046. /**
  10047. * Constructs a new AO node.
  10048. *
  10049. * @param {Node<float>?} [aoNode=null] - The ambient occlusion node.
  10050. */
  10051. constructor( aoNode = null ) {
  10052. super();
  10053. /**
  10054. * The ambient occlusion node.
  10055. *
  10056. * @type {Node<float>?}
  10057. * @default null
  10058. */
  10059. this.aoNode = aoNode;
  10060. }
  10061. setup( builder ) {
  10062. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  10063. }
  10064. }
  10065. /**
  10066. * `LightingContextNode` represents an extension of the {@link module:ContextNode~ContextNode} module
  10067. * by adding lighting specific context data. It represents the runtime context of
  10068. * {@link LightsNode}.
  10069. *
  10070. * @augments ContextNode
  10071. */
  10072. class LightingContextNode extends ContextNode {
  10073. static get type() {
  10074. return 'LightingContextNode';
  10075. }
  10076. /**
  10077. * Constructs a new lighting context node.
  10078. *
  10079. * @param {LightsNode} node - The lights node.
  10080. * @param {LightingModel?} [lightingModel=null] - The current lighting model.
  10081. * @param {Node<vec3>?} [backdropNode=null] - A backdrop node.
  10082. * @param {Node<float>?} [backdropAlphaNode=null] - A backdrop alpha node.
  10083. */
  10084. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  10085. super( node );
  10086. /**
  10087. * The current lighting model.
  10088. *
  10089. * @type {LightingModel?}
  10090. * @default null
  10091. */
  10092. this.lightingModel = lightingModel;
  10093. /**
  10094. * A backdrop node.
  10095. *
  10096. * @type {Node<vec3>?}
  10097. * @default null
  10098. */
  10099. this.backdropNode = backdropNode;
  10100. /**
  10101. * A backdrop alpha node.
  10102. *
  10103. * @type {Node<float>?}
  10104. * @default null
  10105. */
  10106. this.backdropAlphaNode = backdropAlphaNode;
  10107. this._value = null;
  10108. }
  10109. /**
  10110. * Returns a lighting context object.
  10111. *
  10112. * @return {{
  10113. * radiance: Node<vec3>,
  10114. * irradiance: Node<vec3>,
  10115. * iblIrradiance: Node<vec3>,
  10116. * ambientOcclusion: Node<float>,
  10117. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  10118. * backdrop: Node<vec3>,
  10119. * backdropAlpha: Node<float>
  10120. * }} The lighting context object.
  10121. */
  10122. getContext() {
  10123. const { backdropNode, backdropAlphaNode } = this;
  10124. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10125. directSpecular = vec3().toVar( 'directSpecular' ),
  10126. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10127. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10128. const reflectedLight = {
  10129. directDiffuse,
  10130. directSpecular,
  10131. indirectDiffuse,
  10132. indirectSpecular
  10133. };
  10134. const context = {
  10135. radiance: vec3().toVar( 'radiance' ),
  10136. irradiance: vec3().toVar( 'irradiance' ),
  10137. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10138. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10139. reflectedLight,
  10140. backdrop: backdropNode,
  10141. backdropAlpha: backdropAlphaNode
  10142. };
  10143. return context;
  10144. }
  10145. setup( builder ) {
  10146. this.value = this._value || ( this._value = this.getContext() );
  10147. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10148. return super.setup( builder );
  10149. }
  10150. }
  10151. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10152. /**
  10153. * A generic class that can be used by nodes which contribute
  10154. * irradiance to the scene. E.g. a light map node can be used
  10155. * as input for this module. Used in {@link NodeMaterial}.
  10156. *
  10157. * @augments LightingNode
  10158. */
  10159. class IrradianceNode extends LightingNode {
  10160. static get type() {
  10161. return 'IrradianceNode';
  10162. }
  10163. /**
  10164. * Constructs a new irradiance node.
  10165. *
  10166. * @param {Node<vec3>} node - A node contributing irradiance.
  10167. */
  10168. constructor( node ) {
  10169. super();
  10170. /**
  10171. * A node contributing irradiance.
  10172. *
  10173. * @type {Node<vec3>}
  10174. */
  10175. this.node = node;
  10176. }
  10177. setup( builder ) {
  10178. builder.context.irradiance.addAssign( this.node );
  10179. }
  10180. }
  10181. /** @module ScreenNode **/
  10182. let screenSizeVec, viewportVec;
  10183. /**
  10184. * This node provides a collection of screen related metrics.
  10185. * Depending on {@link module:ScreenNode~ScreenNode#scope}, the nodes can represent
  10186. * resolution or viewport data as well as fragment or uv coordinates.
  10187. *
  10188. * @augments Node
  10189. */
  10190. class ScreenNode extends Node {
  10191. static get type() {
  10192. return 'ScreenNode';
  10193. }
  10194. /**
  10195. * Constructs a new screen node.
  10196. *
  10197. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10198. */
  10199. constructor( scope ) {
  10200. super();
  10201. /**
  10202. * The node represents different metric depending on which scope is selected.
  10203. *
  10204. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10205. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10206. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10207. * - `ScreenNode.UV`: Normalized coordinates.
  10208. *
  10209. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10210. */
  10211. this.scope = scope;
  10212. /**
  10213. * This flag can be used for type testing.
  10214. *
  10215. * @type {Boolean}
  10216. * @readonly
  10217. * @default true
  10218. */
  10219. this.isViewportNode = true;
  10220. }
  10221. /**
  10222. * This method is overwritten since the node type depends on the selected scope.
  10223. *
  10224. * @return {('vec2'|'vec4')} The node type.
  10225. */
  10226. getNodeType() {
  10227. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10228. else return 'vec2';
  10229. }
  10230. /**
  10231. * This method is overwritten since the node's update type depends on the selected scope.
  10232. *
  10233. * @return {NodeUpdateType} The update type.
  10234. */
  10235. getUpdateType() {
  10236. let updateType = NodeUpdateType.NONE;
  10237. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10238. updateType = NodeUpdateType.RENDER;
  10239. }
  10240. this.updateType = updateType;
  10241. return updateType;
  10242. }
  10243. /**
  10244. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10245. * from the current renderer.
  10246. *
  10247. * @param {NodeFrame} frame - A reference to the current node frame.
  10248. */
  10249. update( { renderer } ) {
  10250. const renderTarget = renderer.getRenderTarget();
  10251. if ( this.scope === ScreenNode.VIEWPORT ) {
  10252. if ( renderTarget !== null ) {
  10253. viewportVec.copy( renderTarget.viewport );
  10254. } else {
  10255. renderer.getViewport( viewportVec );
  10256. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10257. }
  10258. } else {
  10259. if ( renderTarget !== null ) {
  10260. screenSizeVec.width = renderTarget.width;
  10261. screenSizeVec.height = renderTarget.height;
  10262. } else {
  10263. renderer.getDrawingBufferSize( screenSizeVec );
  10264. }
  10265. }
  10266. }
  10267. setup( /*builder*/ ) {
  10268. const scope = this.scope;
  10269. let output = null;
  10270. if ( scope === ScreenNode.SIZE ) {
  10271. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10272. } else if ( scope === ScreenNode.VIEWPORT ) {
  10273. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10274. } else {
  10275. output = vec2( screenCoordinate.div( screenSize ) );
  10276. }
  10277. return output;
  10278. }
  10279. generate( builder ) {
  10280. if ( this.scope === ScreenNode.COORDINATE ) {
  10281. let coord = builder.getFragCoord();
  10282. if ( builder.isFlipY() ) {
  10283. // follow webgpu standards
  10284. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10285. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10286. }
  10287. return coord;
  10288. }
  10289. return super.generate( builder );
  10290. }
  10291. }
  10292. ScreenNode.COORDINATE = 'coordinate';
  10293. ScreenNode.VIEWPORT = 'viewport';
  10294. ScreenNode.SIZE = 'size';
  10295. ScreenNode.UV = 'uv';
  10296. // Screen
  10297. /**
  10298. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10299. *
  10300. * @type {ScreenNode<vec2>}
  10301. */
  10302. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10303. /**
  10304. * TSL object that represents the screen resolution in physical pixel units.
  10305. *
  10306. * @type {ScreenNode<vec2>}
  10307. */
  10308. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10309. /**
  10310. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10311. *
  10312. * @type {ScreenNode<vec2>}
  10313. */
  10314. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10315. // Viewport
  10316. /**
  10317. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10318. *
  10319. * @type {ScreenNode<vec4>}
  10320. */
  10321. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10322. /**
  10323. * TSL object that represents the viewport resolution in physical pixel units.
  10324. *
  10325. * @type {ScreenNode<vec2>}
  10326. */
  10327. const viewportSize = viewport.zw;
  10328. /**
  10329. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10330. *
  10331. * @type {ScreenNode<vec2>}
  10332. */
  10333. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10334. /**
  10335. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10336. *
  10337. * @type {ScreenNode<vec2>}
  10338. */
  10339. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10340. // Deprecated
  10341. /**
  10342. * @deprecated since r169. Use {@link screenSize} instead.
  10343. */
  10344. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10345. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10346. return screenSize;
  10347. }, 'vec2' ).once() )();
  10348. /**
  10349. * @deprecated since r168. Use {@link screenUV} instead.
  10350. */
  10351. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10352. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10353. return screenUV;
  10354. }, 'vec2' ).once() )();
  10355. /**
  10356. * @deprecated since r168. Use `screenUV.flipY()` instead.
  10357. */
  10358. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10359. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10360. return screenUV.flipY();
  10361. }, 'vec2' ).once() )();
  10362. /** @module ViewportTextureNode **/
  10363. const _size$4 = /*@__PURE__*/ new Vector2();
  10364. /**
  10365. * A special type of texture node which represents the data of the current viewport
  10366. * as a texture. The module extracts data from the current bound framebuffer with
  10367. * a copy operation so no extra render pass is required to produce the texture data
  10368. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10369. * variety of effects like refractive or transmissive materials.
  10370. *
  10371. * @augments module:TextureNode~TextureNode
  10372. */
  10373. class ViewportTextureNode extends TextureNode {
  10374. static get type() {
  10375. return 'ViewportTextureNode';
  10376. }
  10377. /**
  10378. * Constructs a new viewport texture node.
  10379. *
  10380. * @param {Node} [uvNode=screenUV] - The uv node.
  10381. * @param {Node?} [levelNode=null] - The level node.
  10382. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10383. */
  10384. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10385. if ( framebufferTexture === null ) {
  10386. framebufferTexture = new FramebufferTexture();
  10387. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10388. }
  10389. super( framebufferTexture, uvNode, levelNode );
  10390. /**
  10391. * Whether to generate mipmaps or not.
  10392. *
  10393. * @type {Boolean}
  10394. * @default false
  10395. */
  10396. this.generateMipmaps = false;
  10397. /**
  10398. * This flag can be used for type testing.
  10399. *
  10400. * @type {Boolean}
  10401. * @readonly
  10402. * @default true
  10403. */
  10404. this.isOutputTextureNode = true;
  10405. /**
  10406. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10407. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10408. *
  10409. * @type {String}
  10410. * @default 'frame'
  10411. */
  10412. this.updateBeforeType = NodeUpdateType.FRAME;
  10413. }
  10414. updateBefore( frame ) {
  10415. const renderer = frame.renderer;
  10416. renderer.getDrawingBufferSize( _size$4 );
  10417. //
  10418. const framebufferTexture = this.value;
  10419. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10420. framebufferTexture.image.width = _size$4.width;
  10421. framebufferTexture.image.height = _size$4.height;
  10422. framebufferTexture.needsUpdate = true;
  10423. }
  10424. //
  10425. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10426. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10427. renderer.copyFramebufferToTexture( framebufferTexture );
  10428. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10429. }
  10430. clone() {
  10431. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10432. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10433. return viewportTextureNode;
  10434. }
  10435. }
  10436. /**
  10437. * TSL function for creating a viewport texture node.
  10438. *
  10439. * @function
  10440. * @param {Node} [uvNode=screenUV] - The uv node.
  10441. * @param {Node?} [levelNode=null] - The level node.
  10442. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10443. * @returns {ViewportTextureNode}
  10444. */
  10445. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10446. /**
  10447. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10448. *
  10449. * @function
  10450. * @param {Node} [uvNode=screenUV] - The uv node.
  10451. * @param {Node?} [levelNode=null] - The level node.
  10452. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10453. * @returns {ViewportTextureNode}
  10454. */
  10455. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10456. /** @module ViewportDepthTextureNode **/
  10457. let sharedDepthbuffer = null;
  10458. /**
  10459. * Represents the depth of the current viewport as a texture. This module
  10460. * can be used in combination with viewport texture to achieve effects
  10461. * that require depth evaluation.
  10462. *
  10463. * @augments module:ViewportTextureNode~ViewportTextureNode
  10464. */
  10465. class ViewportDepthTextureNode extends ViewportTextureNode {
  10466. static get type() {
  10467. return 'ViewportDepthTextureNode';
  10468. }
  10469. /**
  10470. * Constructs a new viewport depth texture node.
  10471. *
  10472. * @param {Node} [uvNode=screenUV] - The uv node.
  10473. * @param {Node?} [levelNode=null] - The level node.
  10474. */
  10475. constructor( uvNode = screenUV, levelNode = null ) {
  10476. if ( sharedDepthbuffer === null ) {
  10477. sharedDepthbuffer = new DepthTexture();
  10478. }
  10479. super( uvNode, levelNode, sharedDepthbuffer );
  10480. }
  10481. }
  10482. /**
  10483. * TSL function for a viewport depth texture node.
  10484. *
  10485. * @function
  10486. * @param {Node} [uvNode=screenUV] - The uv node.
  10487. * @param {Node?} [levelNode=null] - The level node.
  10488. * @returns {ViewportDepthTextureNode}
  10489. */
  10490. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10491. /** @module ViewportDepthNode **/
  10492. /**
  10493. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10494. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10495. * fragment or for depth evaluation purposes.
  10496. *
  10497. * @augments Node
  10498. */
  10499. class ViewportDepthNode extends Node {
  10500. static get type() {
  10501. return 'ViewportDepthNode';
  10502. }
  10503. /**
  10504. * Constructs a new viewport depth node.
  10505. *
  10506. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10507. * @param {Node?} [valueNode=null] - The value node.
  10508. */
  10509. constructor( scope, valueNode = null ) {
  10510. super( 'float' );
  10511. /**
  10512. * The node behaves differently depending on which scope is selected.
  10513. *
  10514. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10515. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10516. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10517. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  10518. *
  10519. * @type {('depth'|'depthBase'|'linearDepth')}
  10520. */
  10521. this.scope = scope;
  10522. /**
  10523. * Can be used to define a custom depth value.
  10524. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  10525. *
  10526. * @type {Node?}
  10527. * @default null
  10528. */
  10529. this.valueNode = valueNode;
  10530. /**
  10531. * This flag can be used for type testing.
  10532. *
  10533. * @type {Boolean}
  10534. * @readonly
  10535. * @default true
  10536. */
  10537. this.isViewportDepthNode = true;
  10538. }
  10539. generate( builder ) {
  10540. const { scope } = this;
  10541. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10542. return builder.getFragDepth();
  10543. }
  10544. return super.generate( builder );
  10545. }
  10546. setup( { camera } ) {
  10547. const { scope } = this;
  10548. const value = this.valueNode;
  10549. let node = null;
  10550. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10551. if ( value !== null ) {
  10552. node = depthBase().assign( value );
  10553. }
  10554. } else if ( scope === ViewportDepthNode.DEPTH ) {
  10555. if ( camera.isPerspectiveCamera ) {
  10556. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  10557. } else {
  10558. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10559. }
  10560. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  10561. if ( value !== null ) {
  10562. if ( camera.isPerspectiveCamera ) {
  10563. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  10564. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  10565. } else {
  10566. node = value;
  10567. }
  10568. } else {
  10569. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10570. }
  10571. }
  10572. return node;
  10573. }
  10574. }
  10575. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  10576. ViewportDepthNode.DEPTH = 'depth';
  10577. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  10578. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  10579. /**
  10580. * TSL function for converting a viewZ value to an orthographic depth value.
  10581. *
  10582. * @function
  10583. * @param {Node<float>} viewZ - The viewZ node.
  10584. * @param {Node<float>} near - The camera's near value.
  10585. * @param {Node<float>} far - The camera's far value.
  10586. * @returns {Node<float>}
  10587. */
  10588. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  10589. /**
  10590. * TSL function for converting an orthographic depth value to a viewZ value.
  10591. *
  10592. * @function
  10593. * @param {Node<float>} depth - The orthographic depth.
  10594. * @param {Node<float>} near - The camera's near value.
  10595. * @param {Node<float>} far - The camera's far value.
  10596. * @returns {Node<float>}
  10597. */
  10598. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  10599. /**
  10600. * TSL function for converting a viewZ value to a perspective depth value.
  10601. *
  10602. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  10603. *
  10604. * @function
  10605. * @param {Node<float>} viewZ - The viewZ node.
  10606. * @param {Node<float>} near - The camera's near value.
  10607. * @param {Node<float>} far - The camera's far value.
  10608. * @returns {Node<float>}
  10609. */
  10610. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  10611. /**
  10612. * TSL function for converting a perspective depth value to a viewZ value.
  10613. *
  10614. * @function
  10615. * @param {Node<float>} depth - The perspective depth.
  10616. * @param {Node<float>} near - The camera's near value.
  10617. * @param {Node<float>} far - The camera's far value.
  10618. * @returns {Node<float>}
  10619. */
  10620. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  10621. /**
  10622. * TSL function for converting a viewZ value to a logarithmic depth value.
  10623. *
  10624. * @function
  10625. * @param {Node<float>} viewZ - The viewZ node.
  10626. * @param {Node<float>} near - The camera's near value.
  10627. * @param {Node<float>} far - The camera's far value.
  10628. * @returns {Node<float>}
  10629. */
  10630. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  10631. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  10632. // The final logarithmic depth formula used here is adapted from one described in an
  10633. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  10634. // which was an improvement upon an earlier formula one described in an
  10635. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  10636. // Ulrich's formula is the following:
  10637. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  10638. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  10639. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  10640. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  10641. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  10642. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  10643. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  10644. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  10645. // be used, and ultimately Ulrich's "near plane" version was chosen.
  10646. // Outerra eventually made another improvement to their original "C-constant" variant,
  10647. // but it still does not incorporate the camera near plane (for this version,
  10648. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  10649. // Here we make 4 changes to Ulrich's formula:
  10650. // 1. Clamp the camera near plane so we don't divide by 0.
  10651. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  10652. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  10653. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  10654. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  10655. // so we do the same here, hence the 'viewZ.negate()' call.
  10656. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  10657. near = near.max( 1e-6 ).toVar();
  10658. const numerator = log2( viewZ.negate().div( near ) );
  10659. const denominator = log2( far.div( near ) );
  10660. return numerator.div( denominator );
  10661. };
  10662. /**
  10663. * TSL function for converting a logarithmic depth value to a viewZ value.
  10664. *
  10665. * @function
  10666. * @param {Node<float>} depth - The logarithmic depth.
  10667. * @param {Node<float>} near - The camera's near value.
  10668. * @param {Node<float>} far - The camera's far value.
  10669. * @returns {Node<float>}
  10670. */
  10671. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  10672. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  10673. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  10674. // a negative viewZ).
  10675. const exponent = depth.mul( log( far.div( near ) ) );
  10676. return float( Math.E ).pow( exponent ).mul( near ).negate();
  10677. };
  10678. /**
  10679. * TSL function for defining a value for the current fragment's depth.
  10680. *
  10681. * @function
  10682. * @param {Node<float>} value - The depth value to set.
  10683. * @returns {ViewportDepthNode<float>}
  10684. */
  10685. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  10686. /**
  10687. * TSL object that represents the depth value for the current fragment.
  10688. *
  10689. * @type {ViewportDepthNode}
  10690. */
  10691. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  10692. /**
  10693. * TSL function for converting a perspective depth value to linear depth.
  10694. *
  10695. * @function
  10696. * @param {Node<float>} value - The perspective depth.
  10697. * @returns {ViewportDepthNode<float>}
  10698. */
  10699. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  10700. /**
  10701. * TSL object that represents the linear (orthographic) depth value of the current fragment
  10702. *
  10703. * @type {ViewportDepthNode}
  10704. */
  10705. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  10706. depth.assign = ( value ) => depthBase( value );
  10707. /** @module BuiltinNode **/
  10708. /**
  10709. * The node allows to set values for built-in shader variables. That is
  10710. * required for features like hardware-accelerated vertex clipping.
  10711. *
  10712. * @augments Node
  10713. */
  10714. class BuiltinNode extends Node {
  10715. /**
  10716. * Constructs a new builtin node.
  10717. *
  10718. * @param {String} name - The name of the built-in shader variable.
  10719. */
  10720. constructor( name ) {
  10721. super( 'float' );
  10722. /**
  10723. * The name of the built-in shader variable.
  10724. *
  10725. * @type {String}
  10726. */
  10727. this.name = name;
  10728. /**
  10729. * This flag can be used for type testing.
  10730. *
  10731. * @type {Boolean}
  10732. * @readonly
  10733. * @default true
  10734. */
  10735. this.isBuiltinNode = true;
  10736. }
  10737. /**
  10738. * Generates the code snippet of the builtin node.
  10739. *
  10740. * @param {NodeBuilder} builder - The current node builder.
  10741. * @return {String} The generated code snippet.
  10742. */
  10743. generate( /* builder */ ) {
  10744. return this.name;
  10745. }
  10746. }
  10747. /**
  10748. * TSL function for creating a builtin node.
  10749. *
  10750. * @function
  10751. * @param {String} name - The name of the built-in shader variable.
  10752. * @returns {BuiltinNode}
  10753. */
  10754. const builtin = nodeProxy( BuiltinNode );
  10755. /** @module ClippingNode **/
  10756. /**
  10757. * ```
  10758. * This node is used in {@link NodeMaterial} to setup the clipping
  10759. * which can happen hardware-accelerated (if supported) and optionally
  10760. * use alpha-to-coverage for anti-aliasing clipped edges.
  10761. * ```
  10762. * @augments Node
  10763. */
  10764. class ClippingNode extends Node {
  10765. static get type() {
  10766. return 'ClippingNode';
  10767. }
  10768. /**
  10769. * Constructs a new clipping node.
  10770. *
  10771. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  10772. * the selected scope influences the behavior of the node and what type of code is generated.
  10773. */
  10774. constructor( scope = ClippingNode.DEFAULT ) {
  10775. super();
  10776. /**
  10777. * The node's scope. Similar to other nodes, the selected scope influences
  10778. * the behavior of the node and what type of code is generated.
  10779. *
  10780. * @type {('default'|'hardware'|'alphaToCoverage')}
  10781. */
  10782. this.scope = scope;
  10783. }
  10784. /**
  10785. * Setups the node depending on the selected scope.
  10786. *
  10787. * @param {NodeBuilder} builder - The current node builder.
  10788. * @return {Node} The result node.
  10789. */
  10790. setup( builder ) {
  10791. super.setup( builder );
  10792. const clippingContext = builder.clippingContext;
  10793. const { intersectionPlanes, unionPlanes } = clippingContext;
  10794. this.hardwareClipping = builder.material.hardwareClipping;
  10795. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  10796. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  10797. } else if ( this.scope === ClippingNode.HARDWARE ) {
  10798. return this.setupHardwareClipping( unionPlanes, builder );
  10799. } else {
  10800. return this.setupDefault( intersectionPlanes, unionPlanes );
  10801. }
  10802. }
  10803. /**
  10804. * Setups alpha to coverage.
  10805. *
  10806. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10807. * @param {Array<Vector4>} unionPlanes - The union planes.
  10808. * @return {Node} The result node.
  10809. */
  10810. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  10811. return Fn( () => {
  10812. const distanceToPlane = float().toVar( 'distanceToPlane' );
  10813. const distanceGradient = float().toVar( 'distanceToGradient' );
  10814. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  10815. const numUnionPlanes = unionPlanes.length;
  10816. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10817. const clippingPlanes = uniformArray( unionPlanes );
  10818. Loop( numUnionPlanes, ( { i } ) => {
  10819. const plane = clippingPlanes.element( i );
  10820. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10821. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10822. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  10823. } );
  10824. }
  10825. const numIntersectionPlanes = intersectionPlanes.length;
  10826. if ( numIntersectionPlanes > 0 ) {
  10827. const clippingPlanes = uniformArray( intersectionPlanes );
  10828. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  10829. Loop( numIntersectionPlanes, ( { i } ) => {
  10830. const plane = clippingPlanes.element( i );
  10831. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10832. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10833. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  10834. } );
  10835. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  10836. }
  10837. diffuseColor.a.mulAssign( clipOpacity );
  10838. diffuseColor.a.equal( 0.0 ).discard();
  10839. } )();
  10840. }
  10841. /**
  10842. * Setups the default clipping.
  10843. *
  10844. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10845. * @param {Array<Vector4>} unionPlanes - The union planes.
  10846. * @return {Node} The result node.
  10847. */
  10848. setupDefault( intersectionPlanes, unionPlanes ) {
  10849. return Fn( () => {
  10850. const numUnionPlanes = unionPlanes.length;
  10851. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10852. const clippingPlanes = uniformArray( unionPlanes );
  10853. Loop( numUnionPlanes, ( { i } ) => {
  10854. const plane = clippingPlanes.element( i );
  10855. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  10856. } );
  10857. }
  10858. const numIntersectionPlanes = intersectionPlanes.length;
  10859. if ( numIntersectionPlanes > 0 ) {
  10860. const clippingPlanes = uniformArray( intersectionPlanes );
  10861. const clipped = bool( true ).toVar( 'clipped' );
  10862. Loop( numIntersectionPlanes, ( { i } ) => {
  10863. const plane = clippingPlanes.element( i );
  10864. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  10865. } );
  10866. clipped.discard();
  10867. }
  10868. } )();
  10869. }
  10870. /**
  10871. * Setups hardware clipping.
  10872. *
  10873. * @param {Array<Vector4>} unionPlanes - The union planes.
  10874. * @param {NodeBuilder} builder - The current node builder.
  10875. * @return {Node} The result node.
  10876. */
  10877. setupHardwareClipping( unionPlanes, builder ) {
  10878. const numUnionPlanes = unionPlanes.length;
  10879. builder.enableHardwareClipping( numUnionPlanes );
  10880. return Fn( () => {
  10881. const clippingPlanes = uniformArray( unionPlanes );
  10882. const hw_clip_distances = builtin( builder.getClipDistance() );
  10883. Loop( numUnionPlanes, ( { i } ) => {
  10884. const plane = clippingPlanes.element( i );
  10885. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  10886. hw_clip_distances.element( i ).assign( distance );
  10887. } );
  10888. } )();
  10889. }
  10890. }
  10891. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  10892. ClippingNode.DEFAULT = 'default';
  10893. ClippingNode.HARDWARE = 'hardware';
  10894. /**
  10895. * TSL function for setting up the default clipping logic.
  10896. *
  10897. * @function
  10898. * @returns {ClippingNode}
  10899. */
  10900. const clipping = () => nodeObject( new ClippingNode() );
  10901. /**
  10902. * TSL function for setting up alpha to coverage.
  10903. *
  10904. * @function
  10905. * @returns {ClippingNode}
  10906. */
  10907. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  10908. /**
  10909. * TSL function for setting up hardware-based clipping.
  10910. *
  10911. * @function
  10912. * @returns {ClippingNode}
  10913. */
  10914. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  10915. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  10916. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  10917. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10918. 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 ) ) ) ) ) );
  10919. } );
  10920. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10921. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  10922. } );
  10923. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  10924. // Find the discretized derivatives of our coordinates
  10925. const maxDeriv = max$1(
  10926. length( dFdx( position.xyz ) ),
  10927. length( dFdy( position.xyz ) )
  10928. );
  10929. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  10930. // Find two nearest log-discretized noise scales
  10931. const pixScales = vec2(
  10932. exp2( floor( log2( pixScale ) ) ),
  10933. exp2( ceil( log2( pixScale ) ) )
  10934. );
  10935. // Compute alpha thresholds at our two noise scales
  10936. const alpha = vec2(
  10937. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  10938. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  10939. );
  10940. // Factor to interpolate lerp with
  10941. const lerpFactor = fract( log2( pixScale ) );
  10942. // Interpolate alpha threshold from noise at two scales
  10943. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  10944. // Pass into CDF to compute uniformly distrib threshold
  10945. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  10946. const cases = vec3(
  10947. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  10948. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  10949. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  10950. // Find our final, uniformly distributed alpha threshold (ατ)
  10951. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  10952. // Avoids ατ == 0. Could also do ατ =1-ατ
  10953. return clamp( threshold, 1.0e-6, 1.0 );
  10954. } ).setLayout( {
  10955. name: 'getAlphaHashThreshold',
  10956. type: 'float',
  10957. inputs: [
  10958. { name: 'position', type: 'vec3' }
  10959. ]
  10960. } );
  10961. /**
  10962. * Base class for all node materials.
  10963. *
  10964. * @augments Material
  10965. */
  10966. class NodeMaterial extends Material {
  10967. static get type() {
  10968. return 'NodeMaterial';
  10969. }
  10970. /**
  10971. * Represents the type of the node material.
  10972. *
  10973. * @type {String}
  10974. */
  10975. get type() {
  10976. return this.constructor.type;
  10977. }
  10978. set type( _value ) { /* */ }
  10979. /**
  10980. * Constructs a new node material.
  10981. */
  10982. constructor() {
  10983. super();
  10984. /**
  10985. * This flag can be used for type testing.
  10986. *
  10987. * @type {Boolean}
  10988. * @readonly
  10989. * @default true
  10990. */
  10991. this.isNodeMaterial = true;
  10992. /**
  10993. * Whether this material is affected by fog or not.
  10994. *
  10995. * @type {Boolean}
  10996. * @default true
  10997. */
  10998. this.fog = true;
  10999. /**
  11000. * Whether this material is affected by lights or not.
  11001. *
  11002. * @type {Boolean}
  11003. * @default false
  11004. */
  11005. this.lights = false;
  11006. /**
  11007. * Whether this material uses hardware clipping or not.
  11008. * This property is managed by the engine and should not be
  11009. * modified by apps.
  11010. *
  11011. * @type {Boolean}
  11012. * @default false
  11013. */
  11014. this.hardwareClipping = false;
  11015. /**
  11016. * Node materials which set their `lights` property to `true`
  11017. * are affected by all lights of the scene. Sometimes selective
  11018. * lighting is wanted which means only _some_ lights in the scene
  11019. * affect a material. This can be achieved by creating an instance
  11020. * of {@link module:LightsNode~LightsNode} with a list of selective
  11021. * lights and assign the node to this property.
  11022. *
  11023. * ```js
  11024. * const customLightsNode = lights( [ light1, light2 ] );
  11025. * material.lightsNode = customLightsNode;
  11026. * ```
  11027. *
  11028. * @type {LightsNode?}
  11029. * @default null
  11030. */
  11031. this.lightsNode = null;
  11032. /**
  11033. * The environment of node materials can be defined by an environment
  11034. * map assigned to the `envMap` property or by `Scene.environment`
  11035. * if the node material is a PBR material. This node property allows to overwrite
  11036. * the default behavior and define the environment with a custom node.
  11037. *
  11038. * ```js
  11039. * material.envNode = pmremTexture( renderTarget.texture );
  11040. * ```
  11041. *
  11042. * @type {Node<vec3>?}
  11043. * @default null
  11044. */
  11045. this.envNode = null;
  11046. /**
  11047. * The lighting of node materials might be influenced by ambient occlusion.
  11048. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  11049. * and the respective `aoMapIntensity`. This node property allows to overwrite
  11050. * the default and define the ambient occlusion with a custom node instead.
  11051. *
  11052. * If you don't want to overwrite the diffuse color but modify the existing
  11053. * values instead, use {@link module:MaterialNode.materialAO}.
  11054. *
  11055. * @type {Node<float>?}
  11056. * @default null
  11057. */
  11058. this.aoNode = null;
  11059. /**
  11060. * The diffuse color of node materials is by default inferred from the
  11061. * `color` and `map` properties. This node property allows to overwrite the default
  11062. * and define the diffuse color with a node instead.
  11063. *
  11064. * ```js
  11065. * material.colorNode = color( 0xff0000 ); // define red color
  11066. * ```
  11067. *
  11068. * If you don't want to overwrite the diffuse color but modify the existing
  11069. * values instead, use {@link module:MaterialNode.materialColor}.
  11070. *
  11071. * ```js
  11072. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  11073. * ```
  11074. *
  11075. * @type {Node<vec3>?}
  11076. * @default null
  11077. */
  11078. this.colorNode = null;
  11079. /**
  11080. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  11081. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  11082. * and define the normals with a node instead.
  11083. *
  11084. * If you don't want to overwrite the normals but modify the existing values instead,
  11085. * use {@link module:MaterialNode.materialNormal}.
  11086. *
  11087. * @type {Node<vec3>?}
  11088. * @default null
  11089. */
  11090. this.normalNode = null;
  11091. /**
  11092. * The opacity of node materials is by default inferred from the `opacity`
  11093. * and `alphaMap` properties. This node property allows to overwrite the default
  11094. * and define the opacity with a node instead.
  11095. *
  11096. * If you don't want to overwrite the normals but modify the existing
  11097. * value instead, use {@link module:MaterialNode.materialOpacity}.
  11098. *
  11099. * @type {Node<float>?}
  11100. * @default null
  11101. */
  11102. this.opacityNode = null;
  11103. /**
  11104. * This node can be used to to implement a variety of filter-like effects. The idea is
  11105. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  11106. * to create an arbitrary effect and then assign the node composition to this property.
  11107. * Everything behind the object using this material will now be affected by a filter.
  11108. *
  11109. * ```js
  11110. * const material = new NodeMaterial()
  11111. * material.transparent = true;
  11112. *
  11113. * // everything behind the object will be monochromatic
  11114. * material.backdropNode = viewportSharedTexture().rgb.saturation( 0 );
  11115. * ```
  11116. *
  11117. * Backdrop computations are part of the lighting so only lit materials can use this property.
  11118. *
  11119. * @type {Node<vec3>?}
  11120. * @default null
  11121. */
  11122. this.backdropNode = null;
  11123. /**
  11124. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  11125. *
  11126. * @type {Node<float>?}
  11127. * @default null
  11128. */
  11129. this.backdropAlphaNode = null;
  11130. /**
  11131. * The alpha test of node materials is by default inferred from the `alphaTest`
  11132. * property. This node property allows to overwrite the default and define the
  11133. * alpha test with a node instead.
  11134. *
  11135. * If you don't want to overwrite the alpha test but modify the existing
  11136. * value instead, use {@link module:MaterialNode.materialAlphaTest}.
  11137. *
  11138. * @type {Node<float>?}
  11139. * @default null
  11140. */
  11141. this.alphaTestNode = null;
  11142. /**
  11143. * The local vertex positions are computed based on multiple factors like the
  11144. * attribute data, morphing or skinning. This node property allows to overwrite
  11145. * the default and define local vertex positions with nodes instead.
  11146. *
  11147. * If you don't want to overwrite the vertex positions but modify the existing
  11148. * values instead, use {@link module:Position.positionLocal}.
  11149. *
  11150. *```js
  11151. * material.positionNode = positionLocal.add( displace );
  11152. * ```
  11153. *
  11154. * @type {Node<vec3>?}
  11155. * @default null
  11156. */
  11157. this.positionNode = null;
  11158. /**
  11159. * This node property is intended for logic which modifies geometry data once or per animation step.
  11160. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11161. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  11162. * can be implemented.
  11163. *
  11164. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11165. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11166. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11167. * eventually assigned to `geometryNode`.
  11168. *
  11169. * @type {Function}
  11170. * @default null
  11171. */
  11172. this.geometryNode = null;
  11173. /**
  11174. * Allows to overwrite depth values in the fragment shader.
  11175. *
  11176. * @type {Node<float>?}
  11177. * @default null
  11178. */
  11179. this.depthNode = null;
  11180. /**
  11181. * Allows to overwrite the position used for shadow map rendering which
  11182. * is by default {@link module:Position.positionWorld}, the vertex position
  11183. * in world space.
  11184. *
  11185. * @type {Node<float>?}
  11186. * @default null
  11187. */
  11188. this.shadowPositionNode = null;
  11189. /**
  11190. * This node can be used to influence how an object using this node material
  11191. * receive shadows.
  11192. *
  11193. * ```js
  11194. * const totalShadows = float( 1 ).toVar();
  11195. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11196. * totalShadows.mulAssign( shadow );
  11197. * //return float( 1 ); // bypass received shadows
  11198. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11199. * } );
  11200. *
  11201. * @type {Node<vec4>?}
  11202. * @default null
  11203. */
  11204. this.receivedShadowNode = null;
  11205. /**
  11206. * This node can be used to influence how an object using this node material
  11207. * casts shadows. To apply a color to shadows, you can simply do:
  11208. *
  11209. * ```js
  11210. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11211. * ```
  11212. *
  11213. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11214. * is also common to use the property with `Fn` function so checks are performed
  11215. * per fragment.
  11216. *
  11217. * ```js
  11218. * materialCustomShadow.castShadowNode = Fn( () => {
  11219. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11220. * return materialColor;
  11221. * } )();
  11222. * ```
  11223. *
  11224. * @type {Node<vec4>?}
  11225. * @default null
  11226. */
  11227. this.castShadowNode = null;
  11228. /**
  11229. * This node can be used to define the final output of the material.
  11230. *
  11231. * TODO: Explain the differences to `fragmentNode`.
  11232. *
  11233. * @type {Node<vec4>?}
  11234. * @default null
  11235. */
  11236. this.outputNode = null;
  11237. /**
  11238. * MRT configuration is done on renderer or pass level. This node allows to
  11239. * overwrite what values are written into MRT targets on material level. This
  11240. * can be useful for implementing selective FX features that should only affect
  11241. * specific objects.
  11242. *
  11243. * @type {MRTNode?}
  11244. * @default null
  11245. */
  11246. this.mrtNode = null;
  11247. /**
  11248. * This node property can be used if you need complete freedom in implementing
  11249. * the fragment shader. Assigning a node will replace the built-in material
  11250. * logic used in the fragment stage.
  11251. *
  11252. * @type {Node<vec4>?}
  11253. * @default null
  11254. */
  11255. this.fragmentNode = null;
  11256. /**
  11257. * This node property can be used if you need complete freedom in implementing
  11258. * the vertex shader. Assigning a node will replace the built-in material logic
  11259. * used in the vertex stage.
  11260. *
  11261. * @type {Node<vec4>?}
  11262. * @default null
  11263. */
  11264. this.vertexNode = null;
  11265. }
  11266. /**
  11267. * Allows to define a custom cache key that influence the material key computation
  11268. * for render objects.
  11269. *
  11270. * @return {String} The custom cache key.
  11271. */
  11272. customProgramCacheKey() {
  11273. return this.type + getCacheKey$1( this );
  11274. }
  11275. /**
  11276. * Builds this material with the given node builder.
  11277. *
  11278. * @param {NodeBuilder} builder - The current node builder.
  11279. */
  11280. build( builder ) {
  11281. this.setup( builder );
  11282. }
  11283. /**
  11284. * Setups a node material observer with the given builder.
  11285. *
  11286. * @param {NodeBuilder} builder - The current node builder.
  11287. * @return {NodeMaterialObserver} The node material observer.
  11288. */
  11289. setupObserver( builder ) {
  11290. return new NodeMaterialObserver( builder );
  11291. }
  11292. /**
  11293. * Setups the vertex and fragment stage of this node material.
  11294. *
  11295. * @param {NodeBuilder} builder - The current node builder.
  11296. */
  11297. setup( builder ) {
  11298. builder.context.setupNormal = () => this.setupNormal( builder );
  11299. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11300. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11301. const renderer = builder.renderer;
  11302. const renderTarget = renderer.getRenderTarget();
  11303. // < VERTEX STAGE >
  11304. builder.addStack();
  11305. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11306. builder.stack.outputNode = vertexNode;
  11307. this.setupHardwareClipping( builder );
  11308. if ( this.geometryNode !== null ) {
  11309. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11310. }
  11311. builder.addFlow( 'vertex', builder.removeStack() );
  11312. // < FRAGMENT STAGE >
  11313. builder.addStack();
  11314. let resultNode;
  11315. const clippingNode = this.setupClipping( builder );
  11316. if ( this.depthWrite === true || this.depthTest === true ) {
  11317. // only write depth if depth buffer is configured
  11318. if ( renderTarget !== null ) {
  11319. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11320. } else {
  11321. if ( renderer.depth === true ) this.setupDepth( builder );
  11322. }
  11323. }
  11324. if ( this.fragmentNode === null ) {
  11325. this.setupDiffuseColor( builder );
  11326. this.setupVariants( builder );
  11327. const outgoingLightNode = this.setupLighting( builder );
  11328. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11329. // force unsigned floats - useful for RenderTargets
  11330. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11331. resultNode = this.setupOutput( builder, basicOutput );
  11332. // OUTPUT NODE
  11333. output.assign( resultNode );
  11334. //
  11335. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11336. // MRT
  11337. if ( renderTarget !== null ) {
  11338. const mrt = renderer.getMRT();
  11339. const materialMRT = this.mrtNode;
  11340. if ( mrt !== null ) {
  11341. resultNode = mrt;
  11342. if ( materialMRT !== null ) {
  11343. resultNode = mrt.merge( materialMRT );
  11344. }
  11345. } else if ( materialMRT !== null ) {
  11346. resultNode = materialMRT;
  11347. }
  11348. }
  11349. } else {
  11350. let fragmentNode = this.fragmentNode;
  11351. if ( fragmentNode.isOutputStructNode !== true ) {
  11352. fragmentNode = vec4( fragmentNode );
  11353. }
  11354. resultNode = this.setupOutput( builder, fragmentNode );
  11355. }
  11356. builder.stack.outputNode = resultNode;
  11357. builder.addFlow( 'fragment', builder.removeStack() );
  11358. // < MONITOR >
  11359. builder.monitor = this.setupObserver( builder );
  11360. }
  11361. /**
  11362. * Setups the clipping node.
  11363. *
  11364. * @param {NodeBuilder} builder - The current node builder.
  11365. * @return {ClippingNode} The clipping node.
  11366. */
  11367. setupClipping( builder ) {
  11368. if ( builder.clippingContext === null ) return null;
  11369. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11370. let result = null;
  11371. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11372. const samples = builder.renderer.samples;
  11373. if ( this.alphaToCoverage && samples > 1 ) {
  11374. // to be added to flow when the color/alpha value has been determined
  11375. result = clippingAlpha();
  11376. } else {
  11377. builder.stack.add( clipping() );
  11378. }
  11379. }
  11380. return result;
  11381. }
  11382. /**
  11383. * Setups the hardware clipping if available on the current device.
  11384. *
  11385. * @param {NodeBuilder} builder - The current node builder.
  11386. */
  11387. setupHardwareClipping( builder ) {
  11388. this.hardwareClipping = false;
  11389. if ( builder.clippingContext === null ) return;
  11390. const candidateCount = builder.clippingContext.unionPlanes.length;
  11391. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11392. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11393. builder.stack.add( hardwareClipping() );
  11394. this.hardwareClipping = true;
  11395. }
  11396. return;
  11397. }
  11398. /**
  11399. * Setups the depth of this material.
  11400. *
  11401. * @param {NodeBuilder} builder - The current node builder.
  11402. */
  11403. setupDepth( builder ) {
  11404. const { renderer, camera } = builder;
  11405. // Depth
  11406. let depthNode = this.depthNode;
  11407. if ( depthNode === null ) {
  11408. const mrt = renderer.getMRT();
  11409. if ( mrt && mrt.has( 'depth' ) ) {
  11410. depthNode = mrt.get( 'depth' );
  11411. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11412. if ( camera.isPerspectiveCamera ) {
  11413. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11414. } else {
  11415. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11416. }
  11417. }
  11418. }
  11419. if ( depthNode !== null ) {
  11420. depth.assign( depthNode ).append();
  11421. }
  11422. }
  11423. /**
  11424. * Setups the position node in view space. This method exists
  11425. * so derived node materials can modify the implementation e.g. sprite materials.
  11426. *
  11427. * @param {NodeBuilder} builder - The current node builder.
  11428. * @return {Node<vec3>} The position in view space.
  11429. */
  11430. setupPositionView( /*builder*/ ) {
  11431. return modelViewMatrix.mul( positionLocal ).xyz;
  11432. }
  11433. /**
  11434. * Setups the position in clip space.
  11435. *
  11436. * @param {NodeBuilder} builder - The current node builder.
  11437. * @return {Node<vec4>} The position in view space.
  11438. */
  11439. setupModelViewProjection( /*builder*/ ) {
  11440. return cameraProjectionMatrix.mul( positionView );
  11441. }
  11442. /**
  11443. * Setups the logic for the vertex stage.
  11444. *
  11445. * @param {NodeBuilder} builder - The current node builder.
  11446. * @return {Node<vec4>} The position in clip space.
  11447. */
  11448. setupVertex( builder ) {
  11449. builder.addStack();
  11450. this.setupPosition( builder );
  11451. builder.context.vertex = builder.removeStack();
  11452. return modelViewProjection;
  11453. }
  11454. /**
  11455. * Setups the computation of the position in local space.
  11456. *
  11457. * @param {NodeBuilder} builder - The current node builder.
  11458. * @return {Node<vec3>} The position in local space.
  11459. */
  11460. setupPosition( builder ) {
  11461. const { object, geometry } = builder;
  11462. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11463. morphReference( object ).append();
  11464. }
  11465. if ( object.isSkinnedMesh === true ) {
  11466. skinningReference( object ).append();
  11467. }
  11468. if ( this.displacementMap ) {
  11469. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11470. const displacementScale = materialReference( 'displacementScale', 'float' );
  11471. const displacementBias = materialReference( 'displacementBias', 'float' );
  11472. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11473. }
  11474. if ( object.isBatchedMesh ) {
  11475. batch( object ).append();
  11476. }
  11477. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11478. instancedMesh( object ).append();
  11479. }
  11480. if ( this.positionNode !== null ) {
  11481. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11482. }
  11483. return positionLocal;
  11484. }
  11485. /**
  11486. * Setups the computation of the material's diffuse color.
  11487. *
  11488. * @param {NodeBuilder} builder - The current node builder.
  11489. * @param {BufferGeometry} geometry - The geometry.
  11490. */
  11491. setupDiffuseColor( { object, geometry } ) {
  11492. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11493. // VERTEX COLORS
  11494. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11495. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11496. }
  11497. // Instanced colors
  11498. if ( object.instanceColor ) {
  11499. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11500. colorNode = instanceColor.mul( colorNode );
  11501. }
  11502. if ( object.isBatchedMesh && object._colorsTexture ) {
  11503. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11504. colorNode = batchColor.mul( colorNode );
  11505. }
  11506. // COLOR
  11507. diffuseColor.assign( colorNode );
  11508. // OPACITY
  11509. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  11510. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  11511. // ALPHA TEST
  11512. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  11513. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  11514. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  11515. }
  11516. // ALPHA HASH
  11517. if ( this.alphaHash === true ) {
  11518. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  11519. }
  11520. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  11521. diffuseColor.a.assign( 1.0 );
  11522. }
  11523. }
  11524. /**
  11525. * Abstract interface method that can be implemented by derived materials
  11526. * to setup material-specific node variables.
  11527. *
  11528. * @abstract
  11529. * @param {NodeBuilder} builder - The current node builder.
  11530. */
  11531. setupVariants( /*builder*/ ) {
  11532. // Interface function.
  11533. }
  11534. /**
  11535. * Setups the outgoing light node variable
  11536. *
  11537. * @return {Node<vec3>} The outgoing light node.
  11538. */
  11539. setupOutgoingLight() {
  11540. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  11541. }
  11542. /**
  11543. * Setups the normal node from the material.
  11544. *
  11545. * @return {Node<vec3>} The normal node.
  11546. */
  11547. setupNormal() {
  11548. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  11549. }
  11550. /**
  11551. * Setups the environment node from the material.
  11552. *
  11553. * @param {NodeBuilder} builder - The current node builder.
  11554. * @return {Node<vec4>} The environment node.
  11555. */
  11556. setupEnvironment( /*builder*/ ) {
  11557. let node = null;
  11558. if ( this.envNode ) {
  11559. node = this.envNode;
  11560. } else if ( this.envMap ) {
  11561. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  11562. }
  11563. return node;
  11564. }
  11565. /**
  11566. * Setups the light map node from the material.
  11567. *
  11568. * @param {NodeBuilder} builder - The current node builder.
  11569. * @return {Node<vec3>} The light map node.
  11570. */
  11571. setupLightMap( builder ) {
  11572. let node = null;
  11573. if ( builder.material.lightMap ) {
  11574. node = new IrradianceNode( materialLightMap );
  11575. }
  11576. return node;
  11577. }
  11578. /**
  11579. * Setups the lights node based on the scene, environment and material.
  11580. *
  11581. * @param {NodeBuilder} builder - The current node builder.
  11582. * @return {LightsNode} The lights node.
  11583. */
  11584. setupLights( builder ) {
  11585. const materialLightsNode = [];
  11586. //
  11587. const envNode = this.setupEnvironment( builder );
  11588. if ( envNode && envNode.isLightingNode ) {
  11589. materialLightsNode.push( envNode );
  11590. }
  11591. const lightMapNode = this.setupLightMap( builder );
  11592. if ( lightMapNode && lightMapNode.isLightingNode ) {
  11593. materialLightsNode.push( lightMapNode );
  11594. }
  11595. if ( this.aoNode !== null || builder.material.aoMap ) {
  11596. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  11597. materialLightsNode.push( new AONode( aoNode ) );
  11598. }
  11599. let lightsN = this.lightsNode || builder.lightsNode;
  11600. if ( materialLightsNode.length > 0 ) {
  11601. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  11602. }
  11603. return lightsN;
  11604. }
  11605. /**
  11606. * This method should be implemented by most derived materials
  11607. * since it defines the material's lighting model.
  11608. *
  11609. * @abstract
  11610. * @param {NodeBuilder} builder - The current node builder.
  11611. * @return {LightingModel} The lighting model.
  11612. */
  11613. setupLightingModel( /*builder*/ ) {
  11614. // Interface function.
  11615. }
  11616. /**
  11617. * Setups the outgoing light node.
  11618. *
  11619. * @param {NodeBuilder} builder - The current node builder.
  11620. * @return {Node<vec3>} The outgoing light node.
  11621. */
  11622. setupLighting( builder ) {
  11623. const { material } = builder;
  11624. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  11625. // OUTGOING LIGHT
  11626. const lights = this.lights === true || this.lightsNode !== null;
  11627. const lightsNode = lights ? this.setupLights( builder ) : null;
  11628. let outgoingLightNode = this.setupOutgoingLight( builder );
  11629. if ( lightsNode && lightsNode.getScope().hasLights ) {
  11630. const lightingModel = this.setupLightingModel( builder );
  11631. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  11632. } else if ( backdropNode !== null ) {
  11633. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  11634. }
  11635. // EMISSIVE
  11636. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  11637. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  11638. outgoingLightNode = outgoingLightNode.add( emissive );
  11639. }
  11640. return outgoingLightNode;
  11641. }
  11642. /**
  11643. * Setups the output node.
  11644. *
  11645. * @param {NodeBuilder} builder - The current node builder.
  11646. * @param {Node<vec4>} outputNode - The existing output node.
  11647. * @return {Node<vec4>} The output node.
  11648. */
  11649. setupOutput( builder, outputNode ) {
  11650. // FOG
  11651. if ( this.fog === true ) {
  11652. const fogNode = builder.fogNode;
  11653. if ( fogNode ) {
  11654. output.assign( outputNode );
  11655. outputNode = vec4( fogNode );
  11656. }
  11657. }
  11658. return outputNode;
  11659. }
  11660. /**
  11661. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  11662. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  11663. * defining all material properties of the classic type in the node type.
  11664. *
  11665. * @param {Material} material - The material to copy properties with their values to this node material.
  11666. */
  11667. setDefaultValues( material ) {
  11668. // This approach is to reuse the native refreshUniforms*
  11669. // and turn available the use of features like transmission and environment in core
  11670. for ( const property in material ) {
  11671. const value = material[ property ];
  11672. if ( this[ property ] === undefined ) {
  11673. this[ property ] = value;
  11674. if ( value && value.clone ) this[ property ] = value.clone();
  11675. }
  11676. }
  11677. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  11678. for ( const key in descriptors ) {
  11679. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  11680. descriptors[ key ].get !== undefined ) {
  11681. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  11682. }
  11683. }
  11684. }
  11685. /**
  11686. * Serializes this material to JSON.
  11687. *
  11688. * @param {(Object|String)?} meta - The meta information for serialization.
  11689. * @return {Object} The serialized node.
  11690. */
  11691. toJSON( meta ) {
  11692. const isRoot = ( meta === undefined || typeof meta === 'string' );
  11693. if ( isRoot ) {
  11694. meta = {
  11695. textures: {},
  11696. images: {},
  11697. nodes: {}
  11698. };
  11699. }
  11700. const data = Material.prototype.toJSON.call( this, meta );
  11701. const nodeChildren = getNodeChildren( this );
  11702. data.inputNodes = {};
  11703. for ( const { property, childNode } of nodeChildren ) {
  11704. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  11705. }
  11706. // TODO: Copied from Object3D.toJSON
  11707. function extractFromCache( cache ) {
  11708. const values = [];
  11709. for ( const key in cache ) {
  11710. const data = cache[ key ];
  11711. delete data.metadata;
  11712. values.push( data );
  11713. }
  11714. return values;
  11715. }
  11716. if ( isRoot ) {
  11717. const textures = extractFromCache( meta.textures );
  11718. const images = extractFromCache( meta.images );
  11719. const nodes = extractFromCache( meta.nodes );
  11720. if ( textures.length > 0 ) data.textures = textures;
  11721. if ( images.length > 0 ) data.images = images;
  11722. if ( nodes.length > 0 ) data.nodes = nodes;
  11723. }
  11724. return data;
  11725. }
  11726. /**
  11727. * Copies the properties of the given node material to this instance.
  11728. *
  11729. * @param {NodeMaterial} source - The material to copy.
  11730. * @return {NodeMaterial} A reference to this node material.
  11731. */
  11732. copy( source ) {
  11733. this.lightsNode = source.lightsNode;
  11734. this.envNode = source.envNode;
  11735. this.colorNode = source.colorNode;
  11736. this.normalNode = source.normalNode;
  11737. this.opacityNode = source.opacityNode;
  11738. this.backdropNode = source.backdropNode;
  11739. this.backdropAlphaNode = source.backdropAlphaNode;
  11740. this.alphaTestNode = source.alphaTestNode;
  11741. this.positionNode = source.positionNode;
  11742. this.geometryNode = source.geometryNode;
  11743. this.depthNode = source.depthNode;
  11744. this.shadowPositionNode = source.shadowPositionNode;
  11745. this.receivedShadowNode = source.receivedShadowNode;
  11746. this.castShadowNode = source.castShadowNode;
  11747. this.outputNode = source.outputNode;
  11748. this.mrtNode = source.mrtNode;
  11749. this.fragmentNode = source.fragmentNode;
  11750. this.vertexNode = source.vertexNode;
  11751. return super.copy( source );
  11752. }
  11753. }
  11754. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  11755. /**
  11756. * Node material version of `LineBasicMaterial`.
  11757. *
  11758. * @augments NodeMaterial
  11759. */
  11760. class LineBasicNodeMaterial extends NodeMaterial {
  11761. static get type() {
  11762. return 'LineBasicNodeMaterial';
  11763. }
  11764. /**
  11765. * Constructs a new line basic node material.
  11766. *
  11767. * @param {Object?} parameters - The configuration parameter.
  11768. */
  11769. constructor( parameters ) {
  11770. super();
  11771. /**
  11772. * This flag can be used for type testing.
  11773. *
  11774. * @type {Boolean}
  11775. * @readonly
  11776. * @default true
  11777. */
  11778. this.isLineBasicNodeMaterial = true;
  11779. this.setDefaultValues( _defaultValues$d );
  11780. this.setValues( parameters );
  11781. }
  11782. }
  11783. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  11784. /**
  11785. * Node material version of `LineDashedMaterial`.
  11786. *
  11787. * @augments NodeMaterial
  11788. */
  11789. class LineDashedNodeMaterial extends NodeMaterial {
  11790. static get type() {
  11791. return 'LineDashedNodeMaterial';
  11792. }
  11793. /**
  11794. * Constructs a new line dashed node material.
  11795. *
  11796. * @param {Object?} parameters - The configuration parameter.
  11797. */
  11798. constructor( parameters ) {
  11799. super();
  11800. /**
  11801. * This flag can be used for type testing.
  11802. *
  11803. * @type {Boolean}
  11804. * @readonly
  11805. * @default true
  11806. */
  11807. this.isLineDashedNodeMaterial = true;
  11808. this.setDefaultValues( _defaultValues$c );
  11809. /**
  11810. * The dash offset.
  11811. *
  11812. * @type {Number}
  11813. * @default 0
  11814. */
  11815. this.dashOffset = 0;
  11816. /**
  11817. * The offset of dash materials is by default inferred from the `dashOffset`
  11818. * property. This node property allows to overwrite the default
  11819. * and define the offset with a node instead.
  11820. *
  11821. * If you don't want to overwrite the offset but modify the existing
  11822. * value instead, use {@link module:MaterialNode.materialLineDashOffset}.
  11823. *
  11824. * @type {Node<float>?}
  11825. * @default null
  11826. */
  11827. this.offsetNode = null;
  11828. /**
  11829. * The scale of dash materials is by default inferred from the `scale`
  11830. * property. This node property allows to overwrite the default
  11831. * and define the scale with a node instead.
  11832. *
  11833. * If you don't want to overwrite the scale but modify the existing
  11834. * value instead, use {@link module:MaterialNode.materialLineScale}.
  11835. *
  11836. * @type {Node<float>?}
  11837. * @default null
  11838. */
  11839. this.dashScaleNode = null;
  11840. /**
  11841. * The dash size of dash materials is by default inferred from the `dashSize`
  11842. * property. This node property allows to overwrite the default
  11843. * and define the dash size with a node instead.
  11844. *
  11845. * If you don't want to overwrite the dash size but modify the existing
  11846. * value instead, use {@link module:MaterialNode.materialLineDashSize}.
  11847. *
  11848. * @type {Node<float>?}
  11849. * @default null
  11850. */
  11851. this.dashSizeNode = null;
  11852. /**
  11853. * The gap size of dash materials is by default inferred from the `gapSize`
  11854. * property. This node property allows to overwrite the default
  11855. * and define the gap size with a node instead.
  11856. *
  11857. * If you don't want to overwrite the gap size but modify the existing
  11858. * value instead, use {@link module:MaterialNode.materialLineGapSize}.
  11859. *
  11860. * @type {Node<float>?}
  11861. * @default null
  11862. */
  11863. this.gapSizeNode = null;
  11864. this.setValues( parameters );
  11865. }
  11866. /**
  11867. * Setups the dash specific node variables.
  11868. *
  11869. * @param {NodeBuilder} builder - The current node builder.
  11870. */
  11871. setupVariants( /* builder */ ) {
  11872. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  11873. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  11874. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  11875. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  11876. dashSize.assign( dashSizeNode );
  11877. gapSize.assign( gapSizeNode );
  11878. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  11879. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  11880. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  11881. }
  11882. }
  11883. /** @module ViewportSharedTextureNode **/
  11884. let _sharedFramebuffer = null;
  11885. /**
  11886. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  11887. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  11888. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  11889. *
  11890. * @augments module:ViewportTextureNode~ViewportTextureNode
  11891. */
  11892. class ViewportSharedTextureNode extends ViewportTextureNode {
  11893. static get type() {
  11894. return 'ViewportSharedTextureNode';
  11895. }
  11896. /**
  11897. * Constructs a new viewport shared texture node.
  11898. *
  11899. * @param {Node} [uvNode=screenUV] - The uv node.
  11900. * @param {Node?} [levelNode=null] - The level node.
  11901. */
  11902. constructor( uvNode = screenUV, levelNode = null ) {
  11903. if ( _sharedFramebuffer === null ) {
  11904. _sharedFramebuffer = new FramebufferTexture();
  11905. }
  11906. super( uvNode, levelNode, _sharedFramebuffer );
  11907. }
  11908. updateReference() {
  11909. return this;
  11910. }
  11911. }
  11912. /**
  11913. * TSL function for creating a shared viewport texture node.
  11914. *
  11915. * @function
  11916. * @param {Node} [uvNode=screenUV] - The uv node.
  11917. * @param {Node?} [levelNode=null] - The level node.
  11918. * @returns {ViewportSharedTextureNode}
  11919. */
  11920. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  11921. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  11922. /**
  11923. * This node material can be used to render lines with a size larger than one
  11924. * by representing them as instanced meshes.
  11925. *
  11926. * @augments NodeMaterial
  11927. */
  11928. class Line2NodeMaterial extends NodeMaterial {
  11929. static get type() {
  11930. return 'Line2NodeMaterial';
  11931. }
  11932. /**
  11933. * Constructs a new node material for wide line rendering.
  11934. *
  11935. * @param {Object?} parameters - The configuration parameter.
  11936. */
  11937. constructor( parameters = {} ) {
  11938. super();
  11939. /**
  11940. * This flag can be used for type testing.
  11941. *
  11942. * @type {Boolean}
  11943. * @readonly
  11944. * @default true
  11945. */
  11946. this.isLine2NodeMaterial = true;
  11947. this.setDefaultValues( _defaultValues$b );
  11948. /**
  11949. * Whether vertex colors should be used or not.
  11950. *
  11951. * @type {Boolean}
  11952. * @default false
  11953. */
  11954. this.useColor = parameters.vertexColors;
  11955. /**
  11956. * The dash offset.
  11957. *
  11958. * @type {Number}
  11959. * @default 0
  11960. */
  11961. this.dashOffset = 0;
  11962. /**
  11963. * The line width.
  11964. *
  11965. * @type {Number}
  11966. * @default 0
  11967. */
  11968. this.lineWidth = 1;
  11969. /**
  11970. * Defines the lines color.
  11971. *
  11972. * @type {Node<vec3>?}
  11973. * @default null
  11974. */
  11975. this.lineColorNode = null;
  11976. /**
  11977. * Defines the offset.
  11978. *
  11979. * @type {Node<float>?}
  11980. * @default null
  11981. */
  11982. this.offsetNode = null;
  11983. /**
  11984. * Defines the dash scale.
  11985. *
  11986. * @type {Node<float>?}
  11987. * @default null
  11988. */
  11989. this.dashScaleNode = null;
  11990. /**
  11991. * Defines the dash size.
  11992. *
  11993. * @type {Node<float>?}
  11994. * @default null
  11995. */
  11996. this.dashSizeNode = null;
  11997. /**
  11998. * Defines the gap size.
  11999. *
  12000. * @type {Node<float>?}
  12001. * @default null
  12002. */
  12003. this.gapSizeNode = null;
  12004. /**
  12005. * Blending is set to `NoBlending` since transparency
  12006. * is not supported, yet.
  12007. *
  12008. * @type {Number}
  12009. * @default 0
  12010. */
  12011. this.blending = NoBlending;
  12012. this._useDash = parameters.dashed;
  12013. this._useAlphaToCoverage = true;
  12014. this._useWorldUnits = false;
  12015. this.setValues( parameters );
  12016. }
  12017. /**
  12018. * Setups the vertex and fragment stage of this node material.
  12019. *
  12020. * @param {NodeBuilder} builder - The current node builder.
  12021. */
  12022. setup( builder ) {
  12023. const { renderer } = builder;
  12024. const useAlphaToCoverage = this._useAlphaToCoverage;
  12025. const useColor = this.useColor;
  12026. const useDash = this._useDash;
  12027. const useWorldUnits = this._useWorldUnits;
  12028. const trimSegment = Fn( ( { start, end } ) => {
  12029. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12030. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12031. const nearEstimate = b.mul( - 0.5 ).div( a );
  12032. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12033. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12034. } ).setLayout( {
  12035. name: 'trimSegment',
  12036. type: 'vec4',
  12037. inputs: [
  12038. { name: 'start', type: 'vec4' },
  12039. { name: 'end', type: 'vec4' }
  12040. ]
  12041. } );
  12042. this.vertexNode = Fn( () => {
  12043. const instanceStart = attribute( 'instanceStart' );
  12044. const instanceEnd = attribute( 'instanceEnd' );
  12045. // camera space
  12046. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12047. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12048. if ( useDash ) {
  12049. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12050. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12051. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12052. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12053. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12054. lineDistance = lineDistance.add( offsetNode );
  12055. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12056. }
  12057. if ( useWorldUnits ) {
  12058. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12059. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12060. }
  12061. const aspect = viewport.z.div( viewport.w );
  12062. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12063. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12064. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12065. // perhaps there is a more elegant solution -- WestLangley
  12066. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  12067. If( perspective, () => {
  12068. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12069. end.assign( trimSegment( { start: start, end: end } ) );
  12070. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12071. start.assign( trimSegment( { start: end, end: start } ) );
  12072. } );
  12073. } );
  12074. // clip space
  12075. const clipStart = cameraProjectionMatrix.mul( start );
  12076. const clipEnd = cameraProjectionMatrix.mul( end );
  12077. // ndc space
  12078. const ndcStart = clipStart.xyz.div( clipStart.w );
  12079. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12080. // direction
  12081. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12082. // account for clip-space aspect ratio
  12083. dir.x.assign( dir.x.mul( aspect ) );
  12084. dir.assign( dir.normalize() );
  12085. const clip = vec4().toVar();
  12086. if ( useWorldUnits ) {
  12087. // get the offset direction as perpendicular to the view vector
  12088. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12089. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12090. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12091. const worldFwd = worldDir.cross( worldUp );
  12092. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12093. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12094. // height offset
  12095. const hw = materialLineWidth.mul( 0.5 );
  12096. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12097. // don't extend the line if we're rendering dashes because we
  12098. // won't be rendering the endcaps
  12099. if ( ! useDash ) {
  12100. // cap extension
  12101. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12102. // add width to the box
  12103. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12104. // endcaps
  12105. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12106. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12107. } );
  12108. }
  12109. // project the worldpos
  12110. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12111. // shift the depth of the projected points so the line
  12112. // segments overlap neatly
  12113. const clipPose = vec3().toVar();
  12114. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12115. clip.z.assign( clipPose.z.mul( clip.w ) );
  12116. } else {
  12117. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12118. // undo aspect ratio adjustment
  12119. dir.x.assign( dir.x.div( aspect ) );
  12120. offset.x.assign( offset.x.div( aspect ) );
  12121. // sign flip
  12122. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12123. // endcaps
  12124. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12125. offset.assign( offset.sub( dir ) );
  12126. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12127. offset.assign( offset.add( dir ) );
  12128. } );
  12129. // adjust for linewidth
  12130. offset.assign( offset.mul( materialLineWidth ) );
  12131. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12132. offset.assign( offset.div( viewport.w ) );
  12133. // select end
  12134. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12135. // back to clip space
  12136. offset.assign( offset.mul( clip.w ) );
  12137. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12138. }
  12139. return clip;
  12140. } )();
  12141. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12142. const p13 = p1.sub( p3 );
  12143. const p43 = p4.sub( p3 );
  12144. const p21 = p2.sub( p1 );
  12145. const d1343 = p13.dot( p43 );
  12146. const d4321 = p43.dot( p21 );
  12147. const d1321 = p13.dot( p21 );
  12148. const d4343 = p43.dot( p43 );
  12149. const d2121 = p21.dot( p21 );
  12150. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12151. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12152. const mua = numer.div( denom ).clamp();
  12153. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12154. return vec2( mua, mub );
  12155. } );
  12156. this.colorNode = Fn( () => {
  12157. const vUv = uv();
  12158. if ( useDash ) {
  12159. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12160. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12161. dashSize.assign( dashSizeNode );
  12162. gapSize.assign( gapSizeNode );
  12163. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12164. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12165. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12166. }
  12167. const alpha = float( 1 ).toVar( 'alpha' );
  12168. if ( useWorldUnits ) {
  12169. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12170. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12171. // Find the closest points on the view ray and the line segment
  12172. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12173. const lineDir = worldEnd.sub( worldStart );
  12174. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12175. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12176. const p2 = rayEnd.mul( params.y );
  12177. const delta = p1.sub( p2 );
  12178. const len = delta.length();
  12179. const norm = len.div( materialLineWidth );
  12180. if ( ! useDash ) {
  12181. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12182. const dnorm = norm.fwidth();
  12183. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12184. } else {
  12185. norm.greaterThan( 0.5 ).discard();
  12186. }
  12187. }
  12188. } else {
  12189. // round endcaps
  12190. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12191. const a = vUv.x;
  12192. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12193. const len2 = a.mul( a ).add( b.mul( b ) );
  12194. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12195. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12196. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12197. } );
  12198. } else {
  12199. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12200. const a = vUv.x;
  12201. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12202. const len2 = a.mul( a ).add( b.mul( b ) );
  12203. len2.greaterThan( 1.0 ).discard();
  12204. } );
  12205. }
  12206. }
  12207. let lineColorNode;
  12208. if ( this.lineColorNode ) {
  12209. lineColorNode = this.lineColorNode;
  12210. } else {
  12211. if ( useColor ) {
  12212. const instanceColorStart = attribute( 'instanceColorStart' );
  12213. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12214. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12215. lineColorNode = instanceColor.mul( materialColor );
  12216. } else {
  12217. lineColorNode = materialColor;
  12218. }
  12219. }
  12220. return vec4( lineColorNode, alpha );
  12221. } )();
  12222. if ( this.transparent ) {
  12223. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12224. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12225. }
  12226. super.setup( builder );
  12227. }
  12228. /**
  12229. * Whether the lines should sized in world units or not.
  12230. * When set to `false` the unit is pixel.
  12231. *
  12232. * @type {Boolean}
  12233. * @default false
  12234. */
  12235. get worldUnits() {
  12236. return this._useWorldUnits;
  12237. }
  12238. set worldUnits( value ) {
  12239. if ( this._useWorldUnits !== value ) {
  12240. this._useWorldUnits = value;
  12241. this.needsUpdate = true;
  12242. }
  12243. }
  12244. /**
  12245. * Whether the lines should be dashed or not.
  12246. *
  12247. * @type {Boolean}
  12248. * @default false
  12249. */
  12250. get dashed() {
  12251. return this._useDash;
  12252. }
  12253. set dashed( value ) {
  12254. if ( this._useDash !== value ) {
  12255. this._useDash = value;
  12256. this.needsUpdate = true;
  12257. }
  12258. }
  12259. /**
  12260. * Whether alpha to coverage should be used or not.
  12261. *
  12262. * @type {Boolean}
  12263. * @default true
  12264. */
  12265. get alphaToCoverage() {
  12266. return this._useAlphaToCoverage;
  12267. }
  12268. set alphaToCoverage( value ) {
  12269. if ( this._useAlphaToCoverage !== value ) {
  12270. this._useAlphaToCoverage = value;
  12271. this.needsUpdate = true;
  12272. }
  12273. }
  12274. }
  12275. /** @module Packing **/
  12276. /**
  12277. * Packs a direction vector into a color value.
  12278. *
  12279. * @method
  12280. * @param {Node<vec3>} node - The direction to pack.
  12281. * @return {Node<vec3>} The color.
  12282. */
  12283. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12284. /**
  12285. * Unpacks a color value into a direction vector.
  12286. *
  12287. * @method
  12288. * @param {Node<vec3>} node - The color to unpack.
  12289. * @return {Node<vec3>} The direction.
  12290. */
  12291. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12292. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12293. /**
  12294. * Node material version of `MeshNormalMaterial`.
  12295. *
  12296. * @augments NodeMaterial
  12297. */
  12298. class MeshNormalNodeMaterial extends NodeMaterial {
  12299. static get type() {
  12300. return 'MeshNormalNodeMaterial';
  12301. }
  12302. /**
  12303. * Constructs a new mesh normal node material.
  12304. *
  12305. * @param {Object?} parameters - The configuration parameter.
  12306. */
  12307. constructor( parameters ) {
  12308. super();
  12309. /**
  12310. * This flag can be used for type testing.
  12311. *
  12312. * @type {Boolean}
  12313. * @readonly
  12314. * @default true
  12315. */
  12316. this.isMeshNormalNodeMaterial = true;
  12317. this.setDefaultValues( _defaultValues$a );
  12318. this.setValues( parameters );
  12319. }
  12320. /**
  12321. * Overwrites the default implementation by computing the diffuse color
  12322. * based on the normal data.
  12323. */
  12324. setupDiffuseColor() {
  12325. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12326. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12327. }
  12328. }
  12329. /** @module EquirectUVNode **/
  12330. /**
  12331. * Can be used to compute texture coordinates for projecting an
  12332. * equirectangular texture onto a mesh for using it as the scene's
  12333. * background.
  12334. *
  12335. * ```js
  12336. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12337. * ```
  12338. *
  12339. * @augments TempNode
  12340. */
  12341. class EquirectUVNode extends TempNode {
  12342. static get type() {
  12343. return 'EquirectUVNode';
  12344. }
  12345. /**
  12346. * Constructs a new equirect uv node.
  12347. *
  12348. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12349. */
  12350. constructor( dirNode = positionWorldDirection ) {
  12351. super( 'vec2' );
  12352. /**
  12353. * A direction vector for sampling why is by default `positionWorldDirection`.
  12354. *
  12355. * @type {Node<vec3>}
  12356. */
  12357. this.dirNode = dirNode;
  12358. }
  12359. setup() {
  12360. const dir = this.dirNode;
  12361. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12362. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12363. return vec2( u, v );
  12364. }
  12365. }
  12366. /**
  12367. * TSL function for creating an equirect uv node.
  12368. *
  12369. * @function
  12370. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12371. * @returns {EquirectUVNode}
  12372. */
  12373. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12374. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12375. /**
  12376. * This class represents a cube render target. It is a special version
  12377. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12378. *
  12379. * @augments WebGLCubeRenderTarget
  12380. */
  12381. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12382. constructor( size = 1, options = {} ) {
  12383. super( size, options );
  12384. this.isCubeRenderTarget = true;
  12385. }
  12386. /**
  12387. * Converts the given equirectangular texture to a cube map.
  12388. *
  12389. * @param {Renderer} renderer - The renderer.
  12390. * @param {Texture} texture - The equirectangular texture.
  12391. * @return {CubeRenderTarget} A reference to this cube render target.
  12392. */
  12393. fromEquirectangularTexture( renderer, texture$1 ) {
  12394. const currentMinFilter = texture$1.minFilter;
  12395. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12396. texture$1.generateMipmaps = true;
  12397. this.texture.type = texture$1.type;
  12398. this.texture.colorSpace = texture$1.colorSpace;
  12399. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12400. this.texture.minFilter = texture$1.minFilter;
  12401. this.texture.magFilter = texture$1.magFilter;
  12402. const geometry = new BoxGeometry( 5, 5, 5 );
  12403. const uvNode = equirectUV( positionWorldDirection );
  12404. const material = new NodeMaterial();
  12405. material.colorNode = texture( texture$1, uvNode, 0 );
  12406. material.side = BackSide;
  12407. material.blending = NoBlending;
  12408. const mesh = new Mesh( geometry, material );
  12409. const scene = new Scene();
  12410. scene.add( mesh );
  12411. // Avoid blurred poles
  12412. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12413. const camera = new CubeCamera( 1, 10, this );
  12414. const currentMRT = renderer.getMRT();
  12415. renderer.setMRT( null );
  12416. camera.update( renderer, scene );
  12417. renderer.setMRT( currentMRT );
  12418. texture$1.minFilter = currentMinFilter;
  12419. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12420. mesh.geometry.dispose();
  12421. mesh.material.dispose();
  12422. return this;
  12423. }
  12424. }
  12425. /** @module CubeMapNode **/
  12426. const _cache$1 = new WeakMap();
  12427. /**
  12428. * This node can be used to automatically convert environment maps in the
  12429. * equirectangular format into the cube map format.
  12430. *
  12431. * @augments TempNode
  12432. */
  12433. class CubeMapNode extends TempNode {
  12434. static get type() {
  12435. return 'CubeMapNode';
  12436. }
  12437. /**
  12438. * Constructs a new cube map node.
  12439. *
  12440. * @param {Node} envNode - The node representing the environment map.
  12441. */
  12442. constructor( envNode ) {
  12443. super( 'vec3' );
  12444. /**
  12445. * The node representing the environment map.
  12446. *
  12447. * @type {Node}
  12448. */
  12449. this.envNode = envNode;
  12450. /**
  12451. * A reference to the internal cube texture.
  12452. *
  12453. * @private
  12454. * @type {CubeTexture}
  12455. * @default null
  12456. */
  12457. this._cubeTexture = null;
  12458. /**
  12459. * A reference to the internal cube texture node.
  12460. *
  12461. * @private
  12462. * @type {CubeTextureNode}
  12463. */
  12464. this._cubeTextureNode = cubeTexture();
  12465. const defaultTexture = new CubeTexture();
  12466. defaultTexture.isRenderTargetTexture = true;
  12467. /**
  12468. * A default cube texture that acts as a placeholder.
  12469. * It is used when the conversion from equirectangular to cube
  12470. * map has not finished yet for a given texture.
  12471. *
  12472. * @private
  12473. * @type {CubeTexture}
  12474. */
  12475. this._defaultTexture = defaultTexture;
  12476. /**
  12477. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12478. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12479. *
  12480. * @type {String}
  12481. * @default 'render'
  12482. */
  12483. this.updateBeforeType = NodeUpdateType.RENDER;
  12484. }
  12485. updateBefore( frame ) {
  12486. const { renderer, material } = frame;
  12487. const envNode = this.envNode;
  12488. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12489. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12490. if ( texture && texture.isTexture ) {
  12491. const mapping = texture.mapping;
  12492. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12493. // check for converted cubemap map
  12494. if ( _cache$1.has( texture ) ) {
  12495. const cubeMap = _cache$1.get( texture );
  12496. mapTextureMapping( cubeMap, texture.mapping );
  12497. this._cubeTexture = cubeMap;
  12498. } else {
  12499. // create cube map from equirectangular map
  12500. const image = texture.image;
  12501. if ( isEquirectangularMapReady$1( image ) ) {
  12502. const renderTarget = new CubeRenderTarget( image.height );
  12503. renderTarget.fromEquirectangularTexture( renderer, texture );
  12504. mapTextureMapping( renderTarget.texture, texture.mapping );
  12505. this._cubeTexture = renderTarget.texture;
  12506. _cache$1.set( texture, renderTarget.texture );
  12507. texture.addEventListener( 'dispose', onTextureDispose );
  12508. } else {
  12509. // default cube texture as fallback when equirectangular texture is not yet loaded
  12510. this._cubeTexture = this._defaultTexture;
  12511. }
  12512. }
  12513. //
  12514. this._cubeTextureNode.value = this._cubeTexture;
  12515. } else {
  12516. // envNode already refers to a cube map
  12517. this._cubeTextureNode = this.envNode;
  12518. }
  12519. }
  12520. }
  12521. }
  12522. setup( builder ) {
  12523. this.updateBefore( builder );
  12524. return this._cubeTextureNode;
  12525. }
  12526. }
  12527. /**
  12528. * Returns true if the given equirectangular image has been fully loaded
  12529. * and is ready for further processing.
  12530. *
  12531. * @private
  12532. * @param {Image} image - The equirectangular image to check.
  12533. * @return {Boolean} Whether the image is ready or not.
  12534. */
  12535. function isEquirectangularMapReady$1( image ) {
  12536. if ( image === null || image === undefined ) return false;
  12537. return image.height > 0;
  12538. }
  12539. /**
  12540. * This function is executed when `dispose()` is called on the equirectangular
  12541. * texture. In this case, the generated cube map with its render target
  12542. * is deleted as well.
  12543. *
  12544. * @private
  12545. * @param {Object} event - The event object.
  12546. */
  12547. function onTextureDispose( event ) {
  12548. const texture = event.target;
  12549. texture.removeEventListener( 'dispose', onTextureDispose );
  12550. const renderTarget = _cache$1.get( texture );
  12551. if ( renderTarget !== undefined ) {
  12552. _cache$1.delete( texture );
  12553. renderTarget.dispose();
  12554. }
  12555. }
  12556. /**
  12557. * This function makes sure the generated cube map uses the correct
  12558. * texture mapping that corresponds to the equirectangular original.
  12559. *
  12560. * @private
  12561. * @param {Texture} texture - The cube texture.
  12562. * @param {Number} mapping - The original texture mapping.
  12563. */
  12564. function mapTextureMapping( texture, mapping ) {
  12565. if ( mapping === EquirectangularReflectionMapping ) {
  12566. texture.mapping = CubeReflectionMapping;
  12567. } else if ( mapping === EquirectangularRefractionMapping ) {
  12568. texture.mapping = CubeRefractionMapping;
  12569. }
  12570. }
  12571. /**
  12572. * TSL function for creating a cube map node.
  12573. *
  12574. * @function
  12575. * @param {Node} envNode - The node representing the environment map.
  12576. * @returns {CubeMapNode}
  12577. */
  12578. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  12579. /**
  12580. * Represents a basic model for Image-based lighting (IBL). The environment
  12581. * is defined via environment maps in the equirectangular or cube map format.
  12582. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  12583. * or {@link MeshPhongNodeMaterial}.
  12584. *
  12585. * @augments LightingNode
  12586. */
  12587. class BasicEnvironmentNode extends LightingNode {
  12588. static get type() {
  12589. return 'BasicEnvironmentNode';
  12590. }
  12591. /**
  12592. * Constructs a new basic environment node.
  12593. *
  12594. * @param {Node} [envNode=null] - A node representing the environment.
  12595. */
  12596. constructor( envNode = null ) {
  12597. super();
  12598. /**
  12599. * A node representing the environment.
  12600. *
  12601. * @type {Node}
  12602. * @default null
  12603. */
  12604. this.envNode = envNode;
  12605. }
  12606. setup( builder ) {
  12607. // environment property is used in the finish() method of BasicLightingModel
  12608. builder.context.environment = cubeMapNode( this.envNode );
  12609. }
  12610. }
  12611. /**
  12612. * A specific version of {@link IrradianceNode} that is only relevant
  12613. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  12614. * requires a special scaling factor for the light map.
  12615. *
  12616. * @augments LightingNode
  12617. */
  12618. class BasicLightMapNode extends LightingNode {
  12619. static get type() {
  12620. return 'BasicLightMapNode';
  12621. }
  12622. /**
  12623. * Constructs a new basic light map node.
  12624. *
  12625. * @param {Node<vec3>?} [lightMapNode=null] - The light map node.
  12626. */
  12627. constructor( lightMapNode = null ) {
  12628. super();
  12629. /**
  12630. * The light map node.
  12631. *
  12632. * @type {Node<vec3>?}
  12633. */
  12634. this.lightMapNode = lightMapNode;
  12635. }
  12636. setup( builder ) {
  12637. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  12638. const RECIPROCAL_PI = float( 1 / Math.PI );
  12639. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  12640. }
  12641. }
  12642. /**
  12643. * Abstract class for implementing lighting models. The module defines
  12644. * multiple methods that concrete lighting models can implement. These
  12645. * methods are executed at different points during the light evaluation
  12646. * process.
  12647. */
  12648. class LightingModel {
  12649. /**
  12650. * This method is intended for setting up lighting model and context data
  12651. * which are later used in the evaluation process.
  12652. *
  12653. * @abstract
  12654. * @param {ContextNode} input - The current node context.
  12655. * @param {StackNode} stack - The current stack.
  12656. * @param {NodeBuilder} builder - The current node builder.
  12657. */
  12658. start( /*input, stack, builder*/ ) { }
  12659. /**
  12660. * This method is intended for executing final tasks like final updates
  12661. * to the outgoing light.
  12662. *
  12663. * @abstract
  12664. * @param {ContextNode} input - The current node context.
  12665. * @param {StackNode} stack - The current stack.
  12666. * @param {NodeBuilder} builder - The current node builder.
  12667. */
  12668. finish( /*input, stack, builder*/ ) { }
  12669. /**
  12670. * This method is intended for implementing the direct light term and
  12671. * executed during the build process of directional, point and spot light nodes.
  12672. *
  12673. * @abstract
  12674. * @param {Object} input - The input data.
  12675. * @param {StackNode} stack - The current stack.
  12676. * @param {NodeBuilder} builder - The current node builder.
  12677. */
  12678. direct( /*input, stack, builder*/ ) { }
  12679. /**
  12680. * This method is intended for implementing the direct light term for
  12681. * rect area light nodes.
  12682. *
  12683. * @abstract
  12684. * @param {Object} input - The input data.
  12685. * @param {StackNode} stack - The current stack.
  12686. * @param {NodeBuilder} builder - The current node builder.
  12687. */
  12688. directRectArea( /*input, stack, builder*/ ) {}
  12689. /**
  12690. * This method is intended for implementing the indirect light term.
  12691. *
  12692. * @abstract
  12693. * @param {ContextNode} input - The current node context.
  12694. * @param {StackNode} stack - The current stack.
  12695. * @param {NodeBuilder} builder - The current node builder.
  12696. */
  12697. indirect( /*input, stack, builder*/ ) { }
  12698. /**
  12699. * This method is intended for implementing the ambient occlusion term.
  12700. * Unlike other methods, this method must be called manually by the lighting
  12701. * model in its indirect term.
  12702. *
  12703. * @abstract
  12704. * @param {ContextNode} input - The current node context.
  12705. * @param {StackNode} stack - The current stack.
  12706. * @param {NodeBuilder} builder - The current node builder.
  12707. */
  12708. ambientOcclusion( /*input, stack, builder*/ ) { }
  12709. }
  12710. /**
  12711. * Represents the lighting model for unlit materials. The only light contribution
  12712. * is baked indirect lighting modulated with ambient occlusion and the material's
  12713. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  12714. *
  12715. * @augments LightingModel
  12716. */
  12717. class BasicLightingModel extends LightingModel {
  12718. /**
  12719. * Constructs a new basic lighting model.
  12720. */
  12721. constructor() {
  12722. super();
  12723. }
  12724. /**
  12725. * Implements the baked indirect lighting with its modulation.
  12726. *
  12727. * @param {ContextNode} context - The current node context.
  12728. * @param {StackNode} stack - The current stack.
  12729. * @param {NodeBuilder} builder - The current node builder.
  12730. */
  12731. indirect( context, stack, builder ) {
  12732. const ambientOcclusion = context.ambientOcclusion;
  12733. const reflectedLight = context.reflectedLight;
  12734. const irradianceLightMap = builder.context.irradianceLightMap;
  12735. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  12736. // accumulation (baked indirect lighting only)
  12737. if ( irradianceLightMap ) {
  12738. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  12739. } else {
  12740. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  12741. }
  12742. // modulation
  12743. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12744. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  12745. }
  12746. /**
  12747. * Implements the environment mapping.
  12748. *
  12749. * @param {ContextNode} context - The current node context.
  12750. * @param {StackNode} stack - The current stack.
  12751. * @param {NodeBuilder} builder - The current node builder.
  12752. */
  12753. finish( context, stack, builder ) {
  12754. const material = builder.material;
  12755. const outgoingLight = context.outgoingLight;
  12756. const envNode = builder.context.environment;
  12757. if ( envNode ) {
  12758. switch ( material.combine ) {
  12759. case MultiplyOperation:
  12760. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  12761. break;
  12762. case MixOperation:
  12763. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  12764. break;
  12765. case AddOperation:
  12766. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  12767. break;
  12768. default:
  12769. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  12770. break;
  12771. }
  12772. }
  12773. }
  12774. }
  12775. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  12776. /**
  12777. * Node material version of `MeshBasicMaterial`.
  12778. *
  12779. * @augments NodeMaterial
  12780. */
  12781. class MeshBasicNodeMaterial extends NodeMaterial {
  12782. static get type() {
  12783. return 'MeshBasicNodeMaterial';
  12784. }
  12785. /**
  12786. * Constructs a new mesh basic node material.
  12787. *
  12788. * @param {Object?} parameters - The configuration parameter.
  12789. */
  12790. constructor( parameters ) {
  12791. super();
  12792. /**
  12793. * This flag can be used for type testing.
  12794. *
  12795. * @type {Boolean}
  12796. * @readonly
  12797. * @default true
  12798. */
  12799. this.isMeshBasicNodeMaterial = true;
  12800. /**
  12801. * Although the basic material is by definition unlit, we set
  12802. * this property to `true` since we use a lighting model to compute
  12803. * the outgoing light of the fragment shader.
  12804. *
  12805. * @type {Boolean}
  12806. * @default true
  12807. */
  12808. this.lights = true;
  12809. this.setDefaultValues( _defaultValues$9 );
  12810. this.setValues( parameters );
  12811. }
  12812. /**
  12813. * Basic materials are not affected by normal and bump maps so we
  12814. * return by default {@link module:Normal.normalView}.
  12815. *
  12816. * @return {Node<vec3>} The normal node.
  12817. */
  12818. setupNormal() {
  12819. return normalView; // see #28839
  12820. }
  12821. /**
  12822. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12823. * to implement the default environment mapping.
  12824. *
  12825. * @param {NodeBuilder} builder - The current node builder.
  12826. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12827. */
  12828. setupEnvironment( builder ) {
  12829. const envNode = super.setupEnvironment( builder );
  12830. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12831. }
  12832. /**
  12833. * This method must be overwritten since light maps are evaluated
  12834. * with a special scaling factor for basic materials.
  12835. *
  12836. * @param {NodeBuilder} builder - The current node builder.
  12837. * @return {BasicLightMapNode<vec3>?} The light map node.
  12838. */
  12839. setupLightMap( builder ) {
  12840. let node = null;
  12841. if ( builder.material.lightMap ) {
  12842. node = new BasicLightMapNode( materialLightMap );
  12843. }
  12844. return node;
  12845. }
  12846. /**
  12847. * The material overwrites this method because `lights` is set to `true` but
  12848. * we still want to return the diffuse color as the outgoing light.
  12849. *
  12850. * @return {Node<vec3>} The outgoing light node.
  12851. */
  12852. setupOutgoingLight() {
  12853. return diffuseColor.rgb;
  12854. }
  12855. /**
  12856. * Setups the lighting model.
  12857. *
  12858. * @return {BasicLightingModel} The lighting model.
  12859. */
  12860. setupLightingModel() {
  12861. return new BasicLightingModel();
  12862. }
  12863. }
  12864. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  12865. // Original approximation by Christophe Schlick '94
  12866. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  12867. // Optimized variant (presented by Epic at SIGGRAPH '13)
  12868. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  12869. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  12870. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  12871. } ); // validated
  12872. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  12873. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  12874. } ); // validated
  12875. const G_BlinnPhong_Implicit = () => float( 0.25 );
  12876. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  12877. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  12878. } );
  12879. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  12880. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  12881. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  12882. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  12883. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  12884. const G = G_BlinnPhong_Implicit();
  12885. const D = D_BlinnPhong( { dotNH } );
  12886. return F.mul( G ).mul( D );
  12887. } );
  12888. /**
  12889. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  12890. *
  12891. * @augments BasicLightingModel
  12892. */
  12893. class PhongLightingModel extends BasicLightingModel {
  12894. /**
  12895. * Constructs a new phong lighting model.
  12896. *
  12897. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  12898. */
  12899. constructor( specular = true ) {
  12900. super();
  12901. /**
  12902. * Whether specular is supported or not. Set this to `false` if you are
  12903. * looking for a Lambert-like material meaning a material for non-shiny
  12904. * surfaces, without specular highlights.
  12905. *
  12906. * @type {Boolean}
  12907. * @default true
  12908. */
  12909. this.specular = specular;
  12910. }
  12911. /**
  12912. * Implements the direct lighting. The specular portion is optional an can be controlled
  12913. * with the {@link PhongLightingModel#specular} flag.
  12914. *
  12915. * @param {Object} input - The input data.
  12916. * @param {StackNode} stack - The current stack.
  12917. * @param {NodeBuilder} builder - The current node builder.
  12918. */
  12919. direct( { lightDirection, lightColor, reflectedLight } ) {
  12920. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  12921. const irradiance = dotNL.mul( lightColor );
  12922. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  12923. if ( this.specular === true ) {
  12924. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  12925. }
  12926. }
  12927. /**
  12928. * Implements the indirect lighting.
  12929. *
  12930. * @param {ContextNode} input - The current node context.
  12931. * @param {StackNode} stack - The current stack.
  12932. * @param {NodeBuilder} builder - The current node builder.
  12933. */
  12934. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  12935. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  12936. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12937. }
  12938. }
  12939. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  12940. /**
  12941. * Node material version of `MeshLambertMaterial`.
  12942. *
  12943. * @augments NodeMaterial
  12944. */
  12945. class MeshLambertNodeMaterial extends NodeMaterial {
  12946. static get type() {
  12947. return 'MeshLambertNodeMaterial';
  12948. }
  12949. /**
  12950. * Constructs a new mesh lambert node material.
  12951. *
  12952. * @param {Object?} parameters - The configuration parameter.
  12953. */
  12954. constructor( parameters ) {
  12955. super();
  12956. /**
  12957. * This flag can be used for type testing.
  12958. *
  12959. * @type {Boolean}
  12960. * @readonly
  12961. * @default true
  12962. */
  12963. this.isMeshLambertNodeMaterial = true;
  12964. /**
  12965. * Set to `true` because lambert materials react on lights.
  12966. *
  12967. * @type {Boolean}
  12968. * @default true
  12969. */
  12970. this.lights = true;
  12971. this.setDefaultValues( _defaultValues$8 );
  12972. this.setValues( parameters );
  12973. }
  12974. /**
  12975. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12976. * to implement the default environment mapping.
  12977. *
  12978. * @param {NodeBuilder} builder - The current node builder.
  12979. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12980. */
  12981. setupEnvironment( builder ) {
  12982. const envNode = super.setupEnvironment( builder );
  12983. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12984. }
  12985. /**
  12986. * Setups the lighting model.
  12987. *
  12988. * @return {PhongLightingModel} The lighting model.
  12989. */
  12990. setupLightingModel( /*builder*/ ) {
  12991. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  12992. }
  12993. }
  12994. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  12995. /**
  12996. * Node material version of `MeshPhongMaterial`.
  12997. *
  12998. * @augments NodeMaterial
  12999. */
  13000. class MeshPhongNodeMaterial extends NodeMaterial {
  13001. static get type() {
  13002. return 'MeshPhongNodeMaterial';
  13003. }
  13004. /**
  13005. * Constructs a new mesh lambert node material.
  13006. *
  13007. * @param {Object?} parameters - The configuration parameter.
  13008. */
  13009. constructor( parameters ) {
  13010. super();
  13011. /**
  13012. * This flag can be used for type testing.
  13013. *
  13014. * @type {Boolean}
  13015. * @readonly
  13016. * @default true
  13017. */
  13018. this.isMeshPhongNodeMaterial = true;
  13019. /**
  13020. * Set to `true` because phong materials react on lights.
  13021. *
  13022. * @type {Boolean}
  13023. * @default true
  13024. */
  13025. this.lights = true;
  13026. /**
  13027. * The shininess of phong materials is by default inferred from the `shininess`
  13028. * property. This node property allows to overwrite the default
  13029. * and define the shininess with a node instead.
  13030. *
  13031. * If you don't want to overwrite the shininess but modify the existing
  13032. * value instead, use {@link module:MaterialNode.materialShininess}.
  13033. *
  13034. * @type {Node<float>?}
  13035. * @default null
  13036. */
  13037. this.shininessNode = null;
  13038. /**
  13039. * The specular color of phong materials is by default inferred from the
  13040. * `specular` property. This node property allows to overwrite the default
  13041. * and define the specular color with a node instead.
  13042. *
  13043. * If you don't want to overwrite the specular color but modify the existing
  13044. * value instead, use {@link module:MaterialNode.materialSpecular}.
  13045. *
  13046. * @type {Node<vec3>?}
  13047. * @default null
  13048. */
  13049. this.specularNode = null;
  13050. this.setDefaultValues( _defaultValues$7 );
  13051. this.setValues( parameters );
  13052. }
  13053. /**
  13054. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13055. * to implement the default environment mapping.
  13056. *
  13057. * @param {NodeBuilder} builder - The current node builder.
  13058. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13059. */
  13060. setupEnvironment( builder ) {
  13061. const envNode = super.setupEnvironment( builder );
  13062. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13063. }
  13064. /**
  13065. * Setups the lighting model.
  13066. *
  13067. * @return {PhongLightingModel} The lighting model.
  13068. */
  13069. setupLightingModel( /*builder*/ ) {
  13070. return new PhongLightingModel();
  13071. }
  13072. /**
  13073. * Setups the phong specific node variables.
  13074. *
  13075. * @param {NodeBuilder} builder - The current node builder.
  13076. */
  13077. setupVariants( /*builder*/ ) {
  13078. // SHININESS
  13079. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13080. shininess.assign( shininessNode );
  13081. // SPECULAR COLOR
  13082. const specularNode = this.specularNode || materialSpecular;
  13083. specularColor.assign( specularNode );
  13084. }
  13085. copy( source ) {
  13086. this.shininessNode = source.shininessNode;
  13087. this.specularNode = source.specularNode;
  13088. return super.copy( source );
  13089. }
  13090. }
  13091. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13092. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13093. return float( 0 );
  13094. }
  13095. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13096. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13097. return geometryRoughness;
  13098. } );
  13099. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13100. const { roughness } = inputs;
  13101. const geometryRoughness = getGeometryRoughness();
  13102. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13103. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13104. roughnessFactor = roughnessFactor.min( 1.0 );
  13105. return roughnessFactor;
  13106. } );
  13107. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13108. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13109. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13110. const a2 = alpha.pow2();
  13111. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13112. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13113. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13114. } ).setLayout( {
  13115. name: 'V_GGX_SmithCorrelated',
  13116. type: 'float',
  13117. inputs: [
  13118. { name: 'alpha', type: 'float' },
  13119. { name: 'dotNL', type: 'float' },
  13120. { name: 'dotNV', type: 'float' }
  13121. ]
  13122. } ); // validated
  13123. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13124. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13125. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13126. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13127. const v = div( 0.5, gv.add( gl ) );
  13128. return v.saturate();
  13129. } ).setLayout( {
  13130. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13131. type: 'float',
  13132. inputs: [
  13133. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13134. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13135. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13136. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13137. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13138. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13139. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13140. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13141. ]
  13142. } );
  13143. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13144. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13145. // alpha is "roughness squared" in Disney’s reparameterization
  13146. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13147. const a2 = alpha.pow2();
  13148. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13149. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13150. } ).setLayout( {
  13151. name: 'D_GGX',
  13152. type: 'float',
  13153. inputs: [
  13154. { name: 'alpha', type: 'float' },
  13155. { name: 'dotNH', type: 'float' }
  13156. ]
  13157. } ); // validated
  13158. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13159. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13160. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13161. const a2 = alphaT.mul( alphaB );
  13162. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13163. const v2 = v.dot( v );
  13164. const w2 = a2.div( v2 );
  13165. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13166. } ).setLayout( {
  13167. name: 'D_GGX_Anisotropic',
  13168. type: 'float',
  13169. inputs: [
  13170. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13171. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13172. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13173. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13174. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13175. ]
  13176. } );
  13177. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13178. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13179. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13180. const normalView = inputs.normalView || transformedNormalView;
  13181. const alpha = roughness.pow2(); // UE4's roughness
  13182. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13183. const dotNL = normalView.dot( lightDirection ).clamp();
  13184. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13185. const dotNH = normalView.dot( halfDir ).clamp();
  13186. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13187. let F = F_Schlick( { f0, f90, dotVH } );
  13188. let V, D;
  13189. if ( defined( USE_IRIDESCENCE ) ) {
  13190. F = iridescence.mix( F, f );
  13191. }
  13192. if ( defined( USE_ANISOTROPY ) ) {
  13193. const dotTL = anisotropyT.dot( lightDirection );
  13194. const dotTV = anisotropyT.dot( positionViewDirection );
  13195. const dotTH = anisotropyT.dot( halfDir );
  13196. const dotBL = anisotropyB.dot( lightDirection );
  13197. const dotBV = anisotropyB.dot( positionViewDirection );
  13198. const dotBH = anisotropyB.dot( halfDir );
  13199. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13200. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13201. } else {
  13202. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13203. D = D_GGX( { alpha, dotNH } );
  13204. }
  13205. return F.mul( V ).mul( D );
  13206. } ); // validated
  13207. // Analytical approximation of the DFG LUT, one half of the
  13208. // split-sum approximation used in indirect specular lighting.
  13209. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13210. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13211. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13212. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  13213. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  13214. const r = roughness.mul( c0 ).add( c1 );
  13215. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  13216. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  13217. return fab;
  13218. } ).setLayout( {
  13219. name: 'DFGApprox',
  13220. type: 'vec2',
  13221. inputs: [
  13222. { name: 'roughness', type: 'float' },
  13223. { name: 'dotNV', type: 'vec3' }
  13224. ]
  13225. } );
  13226. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13227. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13228. const fab = DFGApprox( { dotNV, roughness } );
  13229. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13230. } );
  13231. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13232. const x = dotVH.oneMinus().saturate();
  13233. const x2 = x.mul( x );
  13234. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13235. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13236. } ).setLayout( {
  13237. name: 'Schlick_to_F0',
  13238. type: 'vec3',
  13239. inputs: [
  13240. { name: 'f', type: 'vec3' },
  13241. { name: 'f90', type: 'float' },
  13242. { name: 'dotVH', type: 'float' }
  13243. ]
  13244. } );
  13245. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13246. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13247. const alpha = roughness.pow2();
  13248. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13249. const invAlpha = float( 1.0 ).div( alpha );
  13250. const cos2h = dotNH.pow2();
  13251. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13252. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13253. } ).setLayout( {
  13254. name: 'D_Charlie',
  13255. type: 'float',
  13256. inputs: [
  13257. { name: 'roughness', type: 'float' },
  13258. { name: 'dotNH', type: 'float' }
  13259. ]
  13260. } );
  13261. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13262. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13263. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13264. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13265. } ).setLayout( {
  13266. name: 'V_Neubelt',
  13267. type: 'float',
  13268. inputs: [
  13269. { name: 'dotNV', type: 'float' },
  13270. { name: 'dotNL', type: 'float' }
  13271. ]
  13272. } );
  13273. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13274. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13275. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13276. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13277. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13278. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13279. const V = V_Neubelt( { dotNV, dotNL } );
  13280. return sheen.mul( D ).mul( V );
  13281. } );
  13282. // Rect Area Light
  13283. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13284. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13285. // code: https://github.com/selfshadow/ltc_code/
  13286. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13287. const LUT_SIZE = 64.0;
  13288. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13289. const LUT_BIAS = 0.5 / LUT_SIZE;
  13290. const dotNV = N.dot( V ).saturate();
  13291. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13292. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13293. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13294. return uv;
  13295. } ).setLayout( {
  13296. name: 'LTC_Uv',
  13297. type: 'vec2',
  13298. inputs: [
  13299. { name: 'N', type: 'vec3' },
  13300. { name: 'V', type: 'vec3' },
  13301. { name: 'roughness', type: 'float' }
  13302. ]
  13303. } );
  13304. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13305. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13306. // An approximation of the form factor of a horizon-clipped rectangle.
  13307. const l = f.length();
  13308. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13309. } ).setLayout( {
  13310. name: 'LTC_ClippedSphereFormFactor',
  13311. type: 'float',
  13312. inputs: [
  13313. { name: 'f', type: 'vec3' }
  13314. ]
  13315. } );
  13316. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13317. const x = v1.dot( v2 );
  13318. const y = x.abs().toVar();
  13319. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13320. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13321. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13322. const v = a.div( b );
  13323. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13324. return v1.cross( v2 ).mul( theta_sintheta );
  13325. } ).setLayout( {
  13326. name: 'LTC_EdgeVectorFormFactor',
  13327. type: 'vec3',
  13328. inputs: [
  13329. { name: 'v1', type: 'vec3' },
  13330. { name: 'v2', type: 'vec3' }
  13331. ]
  13332. } );
  13333. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13334. // bail if point is on back side of plane of light
  13335. // assumes ccw winding order of light vertices
  13336. const v1 = p1.sub( p0 ).toVar();
  13337. const v2 = p3.sub( p0 ).toVar();
  13338. const lightNormal = v1.cross( v2 );
  13339. const result = vec3().toVar();
  13340. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13341. // construct orthonormal basis around N
  13342. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13343. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13344. // compute transform
  13345. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13346. // transform rect
  13347. // & project rect onto sphere
  13348. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13349. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13350. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13351. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13352. // calculate vector form factor
  13353. const vectorFormFactor = vec3( 0 ).toVar();
  13354. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13355. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13356. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13357. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13358. // adjust for horizon clipping
  13359. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13360. } );
  13361. return result;
  13362. } ).setLayout( {
  13363. name: 'LTC_Evaluate',
  13364. type: 'vec3',
  13365. inputs: [
  13366. { name: 'N', type: 'vec3' },
  13367. { name: 'V', type: 'vec3' },
  13368. { name: 'P', type: 'vec3' },
  13369. { name: 'mInv', type: 'mat3' },
  13370. { name: 'p0', type: 'vec3' },
  13371. { name: 'p1', type: 'vec3' },
  13372. { name: 'p2', type: 'vec3' },
  13373. { name: 'p3', type: 'vec3' }
  13374. ]
  13375. } );
  13376. /** @module TextureBicubic **/
  13377. // Mipped Bicubic Texture Filtering by N8
  13378. // https://www.shadertoy.com/view/Dl2SDW
  13379. const bC = 1.0 / 6.0;
  13380. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13381. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13382. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13383. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13384. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13385. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13386. // h0 and h1 are the two offset functions
  13387. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13388. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13389. const bicubic = ( textureNode, texelSize, lod ) => {
  13390. const uv = textureNode.uvNode;
  13391. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13392. const iuv = floor( uvScaled );
  13393. const fuv = fract( uvScaled );
  13394. const g0x = g0( fuv.x );
  13395. const g1x = g1( fuv.x );
  13396. const h0x = h0( fuv.x );
  13397. const h1x = h1( fuv.x );
  13398. const h0y = h0( fuv.y );
  13399. const h1y = h1( fuv.y );
  13400. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13401. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13402. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13403. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13404. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13405. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13406. return a.add( b );
  13407. };
  13408. /**
  13409. * Applies mipped bicubic texture filtering to the given texture node.
  13410. *
  13411. * @method
  13412. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13413. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13414. * @return {Node} The filtered texture sample.
  13415. */
  13416. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13417. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13418. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13419. const fLodSizeInv = div( 1.0, fLodSize );
  13420. const cLodSizeInv = div( 1.0, cLodSize );
  13421. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13422. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13423. return fract( lodNode ).mix( fSample, cSample );
  13424. } );
  13425. //
  13426. // Transmission
  13427. //
  13428. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13429. // Direction of refracted light.
  13430. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13431. // Compute rotation-independent scaling of the model matrix.
  13432. const modelScale = vec3(
  13433. length( modelMatrix[ 0 ].xyz ),
  13434. length( modelMatrix[ 1 ].xyz ),
  13435. length( modelMatrix[ 2 ].xyz )
  13436. );
  13437. // The thickness is specified in local space.
  13438. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13439. } ).setLayout( {
  13440. name: 'getVolumeTransmissionRay',
  13441. type: 'vec3',
  13442. inputs: [
  13443. { name: 'n', type: 'vec3' },
  13444. { name: 'v', type: 'vec3' },
  13445. { name: 'thickness', type: 'float' },
  13446. { name: 'ior', type: 'float' },
  13447. { name: 'modelMatrix', type: 'mat4' }
  13448. ]
  13449. } );
  13450. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13451. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13452. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13453. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13454. } ).setLayout( {
  13455. name: 'applyIorToRoughness',
  13456. type: 'float',
  13457. inputs: [
  13458. { name: 'roughness', type: 'float' },
  13459. { name: 'ior', type: 'float' }
  13460. ]
  13461. } );
  13462. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13463. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13464. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13465. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13466. const transmissionSample = vTexture.sample( fragCoord );
  13467. //const transmissionSample = viewportMipTexture( fragCoord );
  13468. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13469. return textureBicubic( transmissionSample, lod );
  13470. } );
  13471. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13472. If( attenuationDistance.notEqual( 0 ), () => {
  13473. // Compute light attenuation using Beer's law.
  13474. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13475. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13476. return transmittance;
  13477. } );
  13478. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13479. return vec3( 1.0 );
  13480. } ).setLayout( {
  13481. name: 'volumeAttenuation',
  13482. type: 'vec3',
  13483. inputs: [
  13484. { name: 'transmissionDistance', type: 'float' },
  13485. { name: 'attenuationColor', type: 'vec3' },
  13486. { name: 'attenuationDistance', type: 'float' }
  13487. ]
  13488. } );
  13489. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13490. let transmittedLight, transmittance;
  13491. if ( dispersion ) {
  13492. transmittedLight = vec4().toVar();
  13493. transmittance = vec3().toVar();
  13494. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13495. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13496. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13497. const ior = iors.element( i );
  13498. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13499. const refractedRayExit = position.add( transmissionRay );
  13500. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13501. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13502. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13503. refractionCoords.addAssign( 1.0 );
  13504. refractionCoords.divAssign( 2.0 );
  13505. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13506. // Sample framebuffer to get pixel the refracted ray hits.
  13507. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  13508. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  13509. transmittedLight.a.addAssign( transmissionSample.a );
  13510. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  13511. } );
  13512. transmittedLight.a.divAssign( 3.0 );
  13513. } else {
  13514. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13515. const refractedRayExit = position.add( transmissionRay );
  13516. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13517. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13518. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13519. refractionCoords.addAssign( 1.0 );
  13520. refractionCoords.divAssign( 2.0 );
  13521. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13522. // Sample framebuffer to get pixel the refracted ray hits.
  13523. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  13524. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  13525. }
  13526. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  13527. const dotNV = n.dot( v ).clamp();
  13528. // Get the specular component.
  13529. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  13530. dotNV,
  13531. specularColor,
  13532. specularF90,
  13533. roughness
  13534. } ) );
  13535. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  13536. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  13537. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  13538. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  13539. } );
  13540. //
  13541. // Iridescence
  13542. //
  13543. // XYZ to linear-sRGB color space
  13544. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  13545. 3.2404542, - 0.9692660, 0.0556434,
  13546. - 1.5371385, 1.8760108, - 0.2040259,
  13547. - 0.4985314, 0.0415560, 1.0572252
  13548. );
  13549. // Assume air interface for top
  13550. // Note: We don't handle the case fresnel0 == 1
  13551. const Fresnel0ToIor = ( fresnel0 ) => {
  13552. const sqrtF0 = fresnel0.sqrt();
  13553. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  13554. };
  13555. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  13556. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  13557. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  13558. };
  13559. // Fresnel equations for dielectric/dielectric interfaces.
  13560. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  13561. // Evaluation XYZ sensitivity curves in Fourier space
  13562. const evalSensitivity = ( OPD, shift ) => {
  13563. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  13564. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  13565. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  13566. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  13567. 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() );
  13568. 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() );
  13569. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  13570. const rgb = XYZ_TO_REC709.mul( xyz );
  13571. return rgb;
  13572. };
  13573. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  13574. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  13575. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  13576. // Evaluate the cosTheta on the base layer (Snell law)
  13577. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  13578. // Handle TIR:
  13579. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  13580. If( cosTheta2Sq.lessThan( 0 ), () => {
  13581. return vec3( 1.0 );
  13582. } );
  13583. const cosTheta2 = cosTheta2Sq.sqrt();
  13584. // First interface
  13585. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  13586. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  13587. //const R21 = R12;
  13588. const T121 = R12.oneMinus();
  13589. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  13590. const phi21 = float( Math.PI ).sub( phi12 );
  13591. // Second interface
  13592. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  13593. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  13594. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  13595. const phi23 = vec3(
  13596. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13597. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13598. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  13599. );
  13600. // Phase shift
  13601. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  13602. const phi = vec3( phi21 ).add( phi23 );
  13603. // Compound terms
  13604. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  13605. const r123 = R123.sqrt();
  13606. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  13607. // Reflectance term for m = 0 (DC term amplitude)
  13608. const C0 = R12.add( Rs );
  13609. const I = C0.toVar();
  13610. // Reflectance term for m > 0 (pairs of diracs)
  13611. const Cm = Rs.sub( T121 ).toVar();
  13612. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  13613. Cm.mulAssign( r123 );
  13614. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  13615. I.addAssign( Cm.mul( Sm ) );
  13616. } );
  13617. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  13618. return I.max( vec3( 0.0 ) );
  13619. } ).setLayout( {
  13620. name: 'evalIridescence',
  13621. type: 'vec3',
  13622. inputs: [
  13623. { name: 'outsideIOR', type: 'float' },
  13624. { name: 'eta2', type: 'float' },
  13625. { name: 'cosTheta1', type: 'float' },
  13626. { name: 'thinFilmThickness', type: 'float' },
  13627. { name: 'baseF0', type: 'vec3' }
  13628. ]
  13629. } );
  13630. //
  13631. // Sheen
  13632. //
  13633. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  13634. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  13635. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  13636. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  13637. const dotNV = normal.dot( viewDir ).saturate();
  13638. const r2 = roughness.pow2();
  13639. const a = select(
  13640. roughness.lessThan( 0.25 ),
  13641. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  13642. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  13643. );
  13644. const b = select(
  13645. roughness.lessThan( 0.25 ),
  13646. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  13647. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  13648. );
  13649. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  13650. return DG.mul( 1.0 / Math.PI ).saturate();
  13651. } );
  13652. const clearcoatF0 = vec3( 0.04 );
  13653. const clearcoatF90 = float( 1 );
  13654. /**
  13655. * Represents the lighting model for a PBR material.
  13656. *
  13657. * @augments LightingModel
  13658. */
  13659. class PhysicalLightingModel extends LightingModel {
  13660. /**
  13661. * Constructs a new physical lighting model.
  13662. *
  13663. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  13664. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  13665. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  13666. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  13667. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  13668. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  13669. */
  13670. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  13671. super();
  13672. /**
  13673. * Whether clearcoat is supported or not.
  13674. *
  13675. * @type {Boolean}
  13676. * @default false
  13677. */
  13678. this.clearcoat = clearcoat;
  13679. /**
  13680. * Whether sheen is supported or not.
  13681. *
  13682. * @type {Boolean}
  13683. * @default false
  13684. */
  13685. this.sheen = sheen;
  13686. /**
  13687. * Whether iridescence is supported or not.
  13688. *
  13689. * @type {Boolean}
  13690. * @default false
  13691. */
  13692. this.iridescence = iridescence;
  13693. /**
  13694. * Whether anisotropy is supported or not.
  13695. *
  13696. * @type {Boolean}
  13697. * @default false
  13698. */
  13699. this.anisotropy = anisotropy;
  13700. /**
  13701. * Whether transmission is supported or not.
  13702. *
  13703. * @type {Boolean}
  13704. * @default false
  13705. */
  13706. this.transmission = transmission;
  13707. /**
  13708. * Whether dispersion is supported or not.
  13709. *
  13710. * @type {Boolean}
  13711. * @default false
  13712. */
  13713. this.dispersion = dispersion;
  13714. /**
  13715. * The clear coat radiance.
  13716. *
  13717. * @type {Node?}
  13718. * @default null
  13719. */
  13720. this.clearcoatRadiance = null;
  13721. /**
  13722. * The clear coat specular direct.
  13723. *
  13724. * @type {Node?}
  13725. * @default null
  13726. */
  13727. this.clearcoatSpecularDirect = null;
  13728. /**
  13729. * The clear coat specular indirect.
  13730. *
  13731. * @type {Node?}
  13732. * @default null
  13733. */
  13734. this.clearcoatSpecularIndirect = null;
  13735. /**
  13736. * The sheen specular direct.
  13737. *
  13738. * @type {Node?}
  13739. * @default null
  13740. */
  13741. this.sheenSpecularDirect = null;
  13742. /**
  13743. * The sheen specular indirect.
  13744. *
  13745. * @type {Node?}
  13746. * @default null
  13747. */
  13748. this.sheenSpecularIndirect = null;
  13749. /**
  13750. * The iridescence Fresnel.
  13751. *
  13752. * @type {Node?}
  13753. * @default null
  13754. */
  13755. this.iridescenceFresnel = null;
  13756. /**
  13757. * The iridescence F0.
  13758. *
  13759. * @type {Node?}
  13760. * @default null
  13761. */
  13762. this.iridescenceF0 = null;
  13763. }
  13764. /**
  13765. * Depending on what features are requested, the method prepares certain node variables
  13766. * which are later used for lighting computations.
  13767. *
  13768. * @param {ContextNode} context - The current node context.
  13769. */
  13770. start( context ) {
  13771. if ( this.clearcoat === true ) {
  13772. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  13773. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  13774. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  13775. }
  13776. if ( this.sheen === true ) {
  13777. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  13778. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  13779. }
  13780. if ( this.iridescence === true ) {
  13781. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  13782. this.iridescenceFresnel = evalIridescence( {
  13783. outsideIOR: float( 1.0 ),
  13784. eta2: iridescenceIOR,
  13785. cosTheta1: dotNVi,
  13786. thinFilmThickness: iridescenceThickness,
  13787. baseF0: specularColor
  13788. } );
  13789. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  13790. }
  13791. if ( this.transmission === true ) {
  13792. const position = positionWorld;
  13793. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  13794. const n = transformedNormalWorld;
  13795. context.backdrop = getIBLVolumeRefraction(
  13796. n,
  13797. v,
  13798. roughness,
  13799. diffuseColor,
  13800. specularColor,
  13801. specularF90, // specularF90
  13802. position, // positionWorld
  13803. modelWorldMatrix, // modelMatrix
  13804. cameraViewMatrix, // viewMatrix
  13805. cameraProjectionMatrix, // projMatrix
  13806. ior,
  13807. thickness,
  13808. attenuationColor,
  13809. attenuationDistance,
  13810. this.dispersion ? dispersion : null
  13811. );
  13812. context.backdropAlpha = transmission;
  13813. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  13814. }
  13815. }
  13816. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  13817. // Approximates multi-scattering in order to preserve energy.
  13818. // http://www.jcgt.org/published/0008/01/03/
  13819. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  13820. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13821. const fab = DFGApprox( { roughness, dotNV } );
  13822. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  13823. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13824. const Ess = fab.x.add( fab.y );
  13825. const Ems = Ess.oneMinus();
  13826. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  13827. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  13828. singleScatter.addAssign( FssEss );
  13829. multiScatter.addAssign( Fms.mul( Ems ) );
  13830. }
  13831. /**
  13832. * Implements the direct light.
  13833. *
  13834. * @param {Object} input - The input data.
  13835. * @param {StackNode} stack - The current stack.
  13836. * @param {NodeBuilder} builder - The current node builder.
  13837. */
  13838. direct( { lightDirection, lightColor, reflectedLight } ) {
  13839. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13840. const irradiance = dotNL.mul( lightColor );
  13841. if ( this.sheen === true ) {
  13842. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  13843. }
  13844. if ( this.clearcoat === true ) {
  13845. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  13846. const ccIrradiance = dotNLcc.mul( lightColor );
  13847. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  13848. }
  13849. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13850. 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 } ) ) );
  13851. }
  13852. /**
  13853. * This method is intended for implementing the direct light term for
  13854. * rect area light nodes.
  13855. *
  13856. * @param {Object} input - The input data.
  13857. * @param {StackNode} stack - The current stack.
  13858. * @param {NodeBuilder} builder - The current node builder.
  13859. */
  13860. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  13861. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  13862. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  13863. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  13864. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  13865. const N = transformedNormalView;
  13866. const V = positionViewDirection;
  13867. const P = positionView.toVar();
  13868. const uv = LTC_Uv( { N, V, roughness } );
  13869. const t1 = ltc_1.sample( uv ).toVar();
  13870. const t2 = ltc_2.sample( uv ).toVar();
  13871. const mInv = mat3(
  13872. vec3( t1.x, 0, t1.y ),
  13873. vec3( 0, 1, 0 ),
  13874. vec3( t1.z, 0, t1.w )
  13875. ).toVar();
  13876. // LTC Fresnel Approximation by Stephen Hill
  13877. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  13878. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  13879. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  13880. 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 } ) ) );
  13881. }
  13882. /**
  13883. * Implements the indirect lighting.
  13884. *
  13885. * @param {ContextNode} context - The current node context.
  13886. * @param {StackNode} stack - The current stack.
  13887. * @param {NodeBuilder} builder - The current node builder.
  13888. */
  13889. indirect( context, stack, builder ) {
  13890. this.indirectDiffuse( context, stack, builder );
  13891. this.indirectSpecular( context, stack, builder );
  13892. this.ambientOcclusion( context, stack, builder );
  13893. }
  13894. /**
  13895. * Implements the indirect diffuse term.
  13896. *
  13897. * @param {ContextNode} input - The current node context.
  13898. * @param {StackNode} stack - The current stack.
  13899. * @param {NodeBuilder} builder - The current node builder.
  13900. */
  13901. indirectDiffuse( { irradiance, reflectedLight } ) {
  13902. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13903. }
  13904. /**
  13905. * Implements the indirect specular term.
  13906. *
  13907. * @param {ContextNode} input - The current node context.
  13908. * @param {StackNode} stack - The current stack.
  13909. * @param {NodeBuilder} builder - The current node builder.
  13910. */
  13911. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  13912. if ( this.sheen === true ) {
  13913. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  13914. sheen,
  13915. IBLSheenBRDF( {
  13916. normal: transformedNormalView,
  13917. viewDir: positionViewDirection,
  13918. roughness: sheenRoughness
  13919. } )
  13920. ) );
  13921. }
  13922. if ( this.clearcoat === true ) {
  13923. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13924. const clearcoatEnv = EnvironmentBRDF( {
  13925. dotNV: dotNVcc,
  13926. specularColor: clearcoatF0,
  13927. specularF90: clearcoatF90,
  13928. roughness: clearcoatRoughness
  13929. } );
  13930. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  13931. }
  13932. // Both indirect specular and indirect diffuse light accumulate here
  13933. const singleScattering = vec3().toVar( 'singleScattering' );
  13934. const multiScattering = vec3().toVar( 'multiScattering' );
  13935. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  13936. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  13937. const totalScattering = singleScattering.add( multiScattering );
  13938. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  13939. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  13940. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  13941. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  13942. }
  13943. /**
  13944. * Implements the ambient occlusion term.
  13945. *
  13946. * @param {ContextNode} input - The current node context.
  13947. * @param {StackNode} stack - The current stack.
  13948. * @param {NodeBuilder} builder - The current node builder.
  13949. */
  13950. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  13951. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13952. const aoNV = dotNV.add( ambientOcclusion );
  13953. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  13954. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  13955. if ( this.clearcoat === true ) {
  13956. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  13957. }
  13958. if ( this.sheen === true ) {
  13959. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  13960. }
  13961. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13962. reflectedLight.indirectSpecular.mulAssign( aoNode );
  13963. }
  13964. /**
  13965. * Used for final lighting accumulations depending on the requested features.
  13966. *
  13967. * @param {ContextNode} context - The current node context.
  13968. * @param {StackNode} stack - The current stack.
  13969. * @param {NodeBuilder} builder - The current node builder.
  13970. */
  13971. finish( context ) {
  13972. const { outgoingLight } = context;
  13973. if ( this.clearcoat === true ) {
  13974. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13975. const Fcc = F_Schlick( {
  13976. dotVH: dotNVcc,
  13977. f0: clearcoatF0,
  13978. f90: clearcoatF90
  13979. } );
  13980. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  13981. outgoingLight.assign( clearcoatLight );
  13982. }
  13983. if ( this.sheen === true ) {
  13984. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  13985. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  13986. outgoingLight.assign( sheenLight );
  13987. }
  13988. }
  13989. }
  13990. // These defines must match with PMREMGenerator
  13991. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  13992. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  13993. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  13994. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  13995. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  13996. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  13997. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  13998. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  13999. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14000. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14001. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14002. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14003. // These shader functions convert between the UV coordinates of a single face of
  14004. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14005. // sampling a textureCube (not generally normalized ).
  14006. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14007. const absDirection = vec3( abs( direction ) ).toVar();
  14008. const face = float( - 1.0 ).toVar();
  14009. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14010. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14011. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14012. } ).Else( () => {
  14013. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14014. } );
  14015. } ).Else( () => {
  14016. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14017. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14018. } ).Else( () => {
  14019. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14020. } );
  14021. } );
  14022. return face;
  14023. } ).setLayout( {
  14024. name: 'getFace',
  14025. type: 'float',
  14026. inputs: [
  14027. { name: 'direction', type: 'vec3' }
  14028. ]
  14029. } );
  14030. // RH coordinate system; PMREM face-indexing convention
  14031. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14032. const uv = vec2().toVar();
  14033. If( face.equal( 0.0 ), () => {
  14034. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14035. } ).ElseIf( face.equal( 1.0 ), () => {
  14036. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14037. } ).ElseIf( face.equal( 2.0 ), () => {
  14038. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14039. } ).ElseIf( face.equal( 3.0 ), () => {
  14040. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14041. } ).ElseIf( face.equal( 4.0 ), () => {
  14042. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14043. } ).Else( () => {
  14044. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14045. } );
  14046. return mul( 0.5, uv.add( 1.0 ) );
  14047. } ).setLayout( {
  14048. name: 'getUV',
  14049. type: 'vec2',
  14050. inputs: [
  14051. { name: 'direction', type: 'vec3' },
  14052. { name: 'face', type: 'float' }
  14053. ]
  14054. } );
  14055. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14056. const mip = float( 0.0 ).toVar();
  14057. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14058. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14059. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14060. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14061. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14062. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14063. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14064. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14065. } ).Else( () => {
  14066. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14067. } );
  14068. return mip;
  14069. } ).setLayout( {
  14070. name: 'roughnessToMip',
  14071. type: 'float',
  14072. inputs: [
  14073. { name: 'roughness', type: 'float' }
  14074. ]
  14075. } );
  14076. // RH coordinate system; PMREM face-indexing convention
  14077. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14078. const uv = uv_immutable.toVar();
  14079. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14080. const direction = vec3( uv, 1.0 ).toVar();
  14081. If( face.equal( 0.0 ), () => {
  14082. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14083. } ).ElseIf( face.equal( 1.0 ), () => {
  14084. direction.assign( direction.xzy );
  14085. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  14086. } ).ElseIf( face.equal( 2.0 ), () => {
  14087. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  14088. } ).ElseIf( face.equal( 3.0 ), () => {
  14089. direction.assign( direction.zyx );
  14090. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  14091. } ).ElseIf( face.equal( 4.0 ), () => {
  14092. direction.assign( direction.xzy );
  14093. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  14094. } ).ElseIf( face.equal( 5.0 ), () => {
  14095. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  14096. } );
  14097. return direction;
  14098. } ).setLayout( {
  14099. name: 'getDirection',
  14100. type: 'vec3',
  14101. inputs: [
  14102. { name: 'uv', type: 'vec2' },
  14103. { name: 'face', type: 'float' }
  14104. ]
  14105. } );
  14106. //
  14107. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14108. const roughness = float( roughness_immutable );
  14109. const sampleDir = vec3( sampleDir_immutable );
  14110. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14111. const mipF = fract( mip );
  14112. const mipInt = floor( mip );
  14113. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14114. If( mipF.notEqual( 0.0 ), () => {
  14115. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14116. color0.assign( mix( color0, color1, mipF ) );
  14117. } );
  14118. return color0;
  14119. } );
  14120. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14121. const mipInt = float( mipInt_immutable ).toVar();
  14122. const direction = vec3( direction_immutable );
  14123. const face = float( getFace( direction ) ).toVar();
  14124. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14125. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14126. const faceSize = float( exp2( mipInt ) ).toVar();
  14127. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14128. If( face.greaterThan( 2.0 ), () => {
  14129. uv.y.addAssign( faceSize );
  14130. face.subAssign( 3.0 );
  14131. } );
  14132. uv.x.addAssign( face.mul( faceSize ) );
  14133. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14134. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14135. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14136. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14137. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14138. } );
  14139. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14140. const cosTheta = cos( theta );
  14141. // Rodrigues' axis-angle rotation
  14142. const sampleDirection = outputDirection.mul( cosTheta )
  14143. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14144. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14145. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14146. } );
  14147. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14148. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14149. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14150. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14151. } );
  14152. axis.assign( normalize( axis ) );
  14153. const gl_FragColor = vec3().toVar();
  14154. 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 } ) ) );
  14155. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14156. If( i.greaterThanEqual( samples ), () => {
  14157. Break();
  14158. } );
  14159. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14160. 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 } ) ) );
  14161. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14162. } );
  14163. return vec4( gl_FragColor, 1 );
  14164. } );
  14165. /** @module PMREMNode **/
  14166. let _generator = null;
  14167. const _cache = new WeakMap();
  14168. /**
  14169. * Generates the cubeUV size based on the given image height.
  14170. *
  14171. * @private
  14172. * @param {Number} imageHeight - The image height.
  14173. * @return {{texelWidth: Number,texelHeight: Number, maxMip: Number}} The result object.
  14174. */
  14175. function _generateCubeUVSize( imageHeight ) {
  14176. const maxMip = Math.log2( imageHeight ) - 2;
  14177. const texelHeight = 1.0 / imageHeight;
  14178. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14179. return { texelWidth, texelHeight, maxMip };
  14180. }
  14181. /**
  14182. * Generates a PMREM from the given texture .
  14183. *
  14184. * @private
  14185. * @param {Texture} texture - The texture to create the PMREM for.
  14186. * @return {Texture} The PMREM.
  14187. */
  14188. function _getPMREMFromTexture( texture ) {
  14189. let cacheTexture = _cache.get( texture );
  14190. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  14191. if ( pmremVersion !== texture.pmremVersion ) {
  14192. const image = texture.image;
  14193. if ( texture.isCubeTexture ) {
  14194. if ( isCubeMapReady( image ) ) {
  14195. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14196. } else {
  14197. return null;
  14198. }
  14199. } else {
  14200. if ( isEquirectangularMapReady( image ) ) {
  14201. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14202. } else {
  14203. return null;
  14204. }
  14205. }
  14206. cacheTexture.pmremVersion = texture.pmremVersion;
  14207. _cache.set( texture, cacheTexture );
  14208. }
  14209. return cacheTexture.texture;
  14210. }
  14211. /**
  14212. * This node represents a PMREM which is a special type of preprocessed
  14213. * environment map intended for PBR materials.
  14214. *
  14215. * ```js
  14216. * const material = new MeshStandardNodeMaterial();
  14217. * material.envNode = pmremTexture( envMap );
  14218. * ```
  14219. *
  14220. * @augments TempNode
  14221. */
  14222. class PMREMNode extends TempNode {
  14223. static get type() {
  14224. return 'PMREMNode';
  14225. }
  14226. /**
  14227. * Constructs a new function overloading node.
  14228. *
  14229. * @param {Texture} value - The input texture.
  14230. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14231. * @param {Node<float>} [levelNode=null] - The level node.
  14232. */
  14233. constructor( value, uvNode = null, levelNode = null ) {
  14234. super( 'vec3' );
  14235. /**
  14236. * Reference to the input texture.
  14237. *
  14238. * @private
  14239. * @type {Texture}
  14240. */
  14241. this._value = value;
  14242. /**
  14243. * Reference to the generated PMREM.
  14244. *
  14245. * @private
  14246. * @type {Texture | null}
  14247. * @default null
  14248. */
  14249. this._pmrem = null;
  14250. /**
  14251. * The uv node.
  14252. *
  14253. * @type {Node<vec2>}
  14254. */
  14255. this.uvNode = uvNode;
  14256. /**
  14257. * The level node.
  14258. *
  14259. * @type {Node<float>}
  14260. */
  14261. this.levelNode = levelNode;
  14262. /**
  14263. * Reference to a PMREM generator.
  14264. *
  14265. * @private
  14266. * @type {PMREMGenerator}
  14267. * @default null
  14268. */
  14269. this._generator = null;
  14270. const defaultTexture = new Texture();
  14271. defaultTexture.isRenderTargetTexture = true;
  14272. /**
  14273. * The texture node holding the generated PMREM.
  14274. *
  14275. * @private
  14276. * @type {TextureNode}
  14277. */
  14278. this._texture = texture( defaultTexture );
  14279. /**
  14280. * A uniform representing the PMREM's width.
  14281. *
  14282. * @private
  14283. * @type {UniformNode<float>}
  14284. */
  14285. this._width = uniform( 0 );
  14286. /**
  14287. * A uniform representing the PMREM's height.
  14288. *
  14289. * @private
  14290. * @type {UniformNode<float>}
  14291. */
  14292. this._height = uniform( 0 );
  14293. /**
  14294. * A uniform representing the PMREM's max Mip.
  14295. *
  14296. * @private
  14297. * @type {UniformNode<float>}
  14298. */
  14299. this._maxMip = uniform( 0 );
  14300. /**
  14301. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14302. *
  14303. * @type {String}
  14304. * @default 'render'
  14305. */
  14306. this.updateBeforeType = NodeUpdateType.RENDER;
  14307. }
  14308. set value( value ) {
  14309. this._value = value;
  14310. this._pmrem = null;
  14311. }
  14312. /**
  14313. * The node's texture value.
  14314. *
  14315. * @type {Texture}
  14316. */
  14317. get value() {
  14318. return this._value;
  14319. }
  14320. /**
  14321. * Uses the given PMREM texture to update internal values.
  14322. *
  14323. * @param {Texture} texture - The PMREM texture.
  14324. */
  14325. updateFromTexture( texture ) {
  14326. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14327. this._texture.value = texture;
  14328. this._width.value = cubeUVSize.texelWidth;
  14329. this._height.value = cubeUVSize.texelHeight;
  14330. this._maxMip.value = cubeUVSize.maxMip;
  14331. }
  14332. updateBefore() {
  14333. let pmrem = this._pmrem;
  14334. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  14335. const texture = this._value;
  14336. if ( pmremVersion !== texture.pmremVersion ) {
  14337. if ( texture.isPMREMTexture === true ) {
  14338. pmrem = texture;
  14339. } else {
  14340. pmrem = _getPMREMFromTexture( texture );
  14341. }
  14342. if ( pmrem !== null ) {
  14343. this._pmrem = pmrem;
  14344. this.updateFromTexture( pmrem );
  14345. }
  14346. }
  14347. }
  14348. setup( builder ) {
  14349. if ( _generator === null ) {
  14350. _generator = builder.createPMREMGenerator();
  14351. }
  14352. //
  14353. this.updateBefore( builder );
  14354. //
  14355. let uvNode = this.uvNode;
  14356. if ( uvNode === null && builder.context.getUV ) {
  14357. uvNode = builder.context.getUV( this );
  14358. }
  14359. //
  14360. const texture = this.value;
  14361. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14362. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14363. }
  14364. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14365. //
  14366. let levelNode = this.levelNode;
  14367. if ( levelNode === null && builder.context.getTextureLevel ) {
  14368. levelNode = builder.context.getTextureLevel( this );
  14369. }
  14370. //
  14371. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14372. }
  14373. }
  14374. /**
  14375. * Returns `true` if the given cube map image has been fully loaded.
  14376. *
  14377. * @private
  14378. * @param {Array<(Image|Object)>} image - The cube map image.
  14379. * @return {Boolean} Whether the given cube map is ready or not.
  14380. */
  14381. function isCubeMapReady( image ) {
  14382. if ( image === null || image === undefined ) return false;
  14383. let count = 0;
  14384. const length = 6;
  14385. for ( let i = 0; i < length; i ++ ) {
  14386. if ( image[ i ] !== undefined ) count ++;
  14387. }
  14388. return count === length;
  14389. }
  14390. /**
  14391. * Returns `true` if the given equirectangular image has been fully loaded.
  14392. *
  14393. * @private
  14394. * @param {(Image|Object)} image - The equirectangular image.
  14395. * @return {Boolean} Whether the given cube map is ready or not.
  14396. */
  14397. function isEquirectangularMapReady( image ) {
  14398. if ( image === null || image === undefined ) return false;
  14399. return image.height > 0;
  14400. }
  14401. /**
  14402. * TSL function for creating a PMREM node.
  14403. *
  14404. * @function
  14405. * @param {Texture} value - The input texture.
  14406. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14407. * @param {Node<float>} [levelNode=null] - The level node.
  14408. * @returns {PMREMNode}
  14409. */
  14410. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14411. const _envNodeCache = new WeakMap();
  14412. /**
  14413. * Represents a physical model for Image-based lighting (IBL). The environment
  14414. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14415. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14416. *
  14417. * @augments LightingNode
  14418. */
  14419. class EnvironmentNode extends LightingNode {
  14420. static get type() {
  14421. return 'EnvironmentNode';
  14422. }
  14423. /**
  14424. * Constructs a new environment node.
  14425. *
  14426. * @param {Node} [envNode=null] - A node representing the environment.
  14427. */
  14428. constructor( envNode = null ) {
  14429. super();
  14430. /**
  14431. * A node representing the environment.
  14432. *
  14433. * @type {Node?}
  14434. * @default null
  14435. */
  14436. this.envNode = envNode;
  14437. }
  14438. setup( builder ) {
  14439. const { material } = builder;
  14440. let envNode = this.envNode;
  14441. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14442. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14443. let cacheEnvNode = _envNodeCache.get( value );
  14444. if ( cacheEnvNode === undefined ) {
  14445. cacheEnvNode = pmremTexture( value );
  14446. _envNodeCache.set( value, cacheEnvNode );
  14447. }
  14448. envNode = cacheEnvNode;
  14449. }
  14450. //
  14451. const envMap = material.envMap;
  14452. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14453. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14454. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14455. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14456. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14457. const isolateRadiance = cache( radiance );
  14458. const isolateIrradiance = cache( irradiance );
  14459. //
  14460. builder.context.radiance.addAssign( isolateRadiance );
  14461. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14462. //
  14463. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14464. if ( clearcoatRadiance ) {
  14465. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14466. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14467. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14468. }
  14469. }
  14470. }
  14471. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14472. let reflectVec = null;
  14473. return {
  14474. getUV: () => {
  14475. if ( reflectVec === null ) {
  14476. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14477. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14478. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14479. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14480. }
  14481. return reflectVec;
  14482. },
  14483. getTextureLevel: () => {
  14484. return roughnessNode;
  14485. }
  14486. };
  14487. };
  14488. const createIrradianceContext = ( normalWorldNode ) => {
  14489. return {
  14490. getUV: () => {
  14491. return normalWorldNode;
  14492. },
  14493. getTextureLevel: () => {
  14494. return float( 1.0 );
  14495. }
  14496. };
  14497. };
  14498. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14499. /**
  14500. * Node material version of `MeshStandardMaterial`.
  14501. *
  14502. * @augments NodeMaterial
  14503. */
  14504. class MeshStandardNodeMaterial extends NodeMaterial {
  14505. static get type() {
  14506. return 'MeshStandardNodeMaterial';
  14507. }
  14508. /**
  14509. * Constructs a new mesh standard node material.
  14510. *
  14511. * @param {Object?} parameters - The configuration parameter.
  14512. */
  14513. constructor( parameters ) {
  14514. super();
  14515. /**
  14516. * This flag can be used for type testing.
  14517. *
  14518. * @type {Boolean}
  14519. * @readonly
  14520. * @default true
  14521. */
  14522. this.isMeshStandardNodeMaterial = true;
  14523. /**
  14524. * Set to `true` because standard materials react on lights.
  14525. *
  14526. * @type {Boolean}
  14527. * @default true
  14528. */
  14529. this.lights = true;
  14530. /**
  14531. * The emissive color of standard materials is by default inferred from the `emissive`,
  14532. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  14533. * overwrite the default and define the emissive color with a node instead.
  14534. *
  14535. * If you don't want to overwrite the emissive color but modify the existing
  14536. * value instead, use {@link module:MaterialNode.materialEmissive}.
  14537. *
  14538. * @type {Node<vec3>?}
  14539. * @default null
  14540. */
  14541. this.emissiveNode = null;
  14542. /**
  14543. * The metalness of standard materials is by default inferred from the `metalness`,
  14544. * and `metalnessMap` properties. This node property allows to
  14545. * overwrite the default and define the metalness with a node instead.
  14546. *
  14547. * If you don't want to overwrite the metalness but modify the existing
  14548. * value instead, use {@link module:MaterialNode.materialMetalness}.
  14549. *
  14550. * @type {Node<float>?}
  14551. * @default null
  14552. */
  14553. this.metalnessNode = null;
  14554. /**
  14555. * The roughness of standard materials is by default inferred from the `roughness`,
  14556. * and `roughnessMap` properties. This node property allows to
  14557. * overwrite the default and define the roughness with a node instead.
  14558. *
  14559. * If you don't want to overwrite the roughness but modify the existing
  14560. * value instead, use {@link module:MaterialNode.materialRoughness}.
  14561. *
  14562. * @type {Node<float>?}
  14563. * @default null
  14564. */
  14565. this.roughnessNode = null;
  14566. this.setDefaultValues( _defaultValues$6 );
  14567. this.setValues( parameters );
  14568. }
  14569. /**
  14570. * Overwritten since this type of material uses {@link EnvironmentNode}
  14571. * to implement the PBR (PMREM based) environment mapping. Besides, the
  14572. * method honors `Scene.environment`.
  14573. *
  14574. * @param {NodeBuilder} builder - The current node builder.
  14575. * @return {EnvironmentNode<vec3>?} The environment node.
  14576. */
  14577. setupEnvironment( builder ) {
  14578. let envNode = super.setupEnvironment( builder );
  14579. if ( envNode === null && builder.environmentNode ) {
  14580. envNode = builder.environmentNode;
  14581. }
  14582. return envNode ? new EnvironmentNode( envNode ) : null;
  14583. }
  14584. /**
  14585. * Setups the lighting model.
  14586. *
  14587. * @return {PhysicalLightingModel} The lighting model.
  14588. */
  14589. setupLightingModel( /*builder*/ ) {
  14590. return new PhysicalLightingModel();
  14591. }
  14592. /**
  14593. * Setups the specular related node variables.
  14594. */
  14595. setupSpecular() {
  14596. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  14597. specularColor.assign( specularColorNode );
  14598. specularF90.assign( 1.0 );
  14599. }
  14600. /**
  14601. * Setups the standard specific node variables.
  14602. *
  14603. * @param {NodeBuilder} builder - The current node builder.
  14604. */
  14605. setupVariants() {
  14606. // METALNESS
  14607. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  14608. metalness.assign( metalnessNode );
  14609. // ROUGHNESS
  14610. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  14611. roughnessNode = getRoughness( { roughness: roughnessNode } );
  14612. roughness.assign( roughnessNode );
  14613. // SPECULAR COLOR
  14614. this.setupSpecular();
  14615. // DIFFUSE COLOR
  14616. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  14617. }
  14618. copy( source ) {
  14619. this.emissiveNode = source.emissiveNode;
  14620. this.metalnessNode = source.metalnessNode;
  14621. this.roughnessNode = source.roughnessNode;
  14622. return super.copy( source );
  14623. }
  14624. }
  14625. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  14626. /**
  14627. * Node material version of `MeshPhysicalMaterial`.
  14628. *
  14629. * @augments MeshStandardNodeMaterial
  14630. */
  14631. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  14632. static get type() {
  14633. return 'MeshPhysicalNodeMaterial';
  14634. }
  14635. /**
  14636. * Constructs a new mesh physical node material.
  14637. *
  14638. * @param {Object?} parameters - The configuration parameter.
  14639. */
  14640. constructor( parameters ) {
  14641. super();
  14642. /**
  14643. * This flag can be used for type testing.
  14644. *
  14645. * @type {Boolean}
  14646. * @readonly
  14647. * @default true
  14648. */
  14649. this.isMeshPhysicalNodeMaterial = true;
  14650. /**
  14651. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  14652. * and `clearcoatMap` properties. This node property allows to overwrite the default
  14653. * and define the clearcoat with a node instead.
  14654. *
  14655. * If you don't want to overwrite the clearcoat but modify the existing
  14656. * value instead, use {@link module:MaterialNode.materialClearcoat}.
  14657. *
  14658. * @type {Node<float>?}
  14659. * @default null
  14660. */
  14661. this.clearcoatNode = null;
  14662. /**
  14663. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  14664. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  14665. * and define the clearcoat roughness with a node instead.
  14666. *
  14667. * If you don't want to overwrite the clearcoat roughness but modify the existing
  14668. * value instead, use {@link module:MaterialNode.materialClearcoatRoughness}.
  14669. *
  14670. * @type {Node<float>?}
  14671. * @default null
  14672. */
  14673. this.clearcoatRoughnessNode = null;
  14674. /**
  14675. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  14676. * property. This node property allows to overwrite the default
  14677. * and define the clearcoat normal with a node instead.
  14678. *
  14679. * If you don't want to overwrite the clearcoat normal but modify the existing
  14680. * value instead, use {@link module:MaterialNode.materialClearcoatNormal}.
  14681. *
  14682. * @type {Node<vec3>?}
  14683. * @default null
  14684. */
  14685. this.clearcoatNormalNode = null;
  14686. /**
  14687. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  14688. * and `sheenColorMap` properties. This node property allows to overwrite the default
  14689. * and define the sheen with a node instead.
  14690. *
  14691. * If you don't want to overwrite the sheen but modify the existing
  14692. * value instead, use {@link module:MaterialNode.materialSheen}.
  14693. *
  14694. * @type {Node<vec3>?}
  14695. * @default null
  14696. */
  14697. this.sheenNode = null;
  14698. /**
  14699. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  14700. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  14701. * and define the sheen roughness with a node instead.
  14702. *
  14703. * If you don't want to overwrite the sheen roughness but modify the existing
  14704. * value instead, use {@link module:MaterialNode.materialSheenRoughness}.
  14705. *
  14706. * @type {Node<float>?}
  14707. * @default null
  14708. */
  14709. this.sheenRoughnessNode = null;
  14710. /**
  14711. * The iridescence of physical materials is by default inferred from the `iridescence`
  14712. * property. This node property allows to overwrite the default
  14713. * and define the iridescence with a node instead.
  14714. *
  14715. * If you don't want to overwrite the iridescence but modify the existing
  14716. * value instead, use {@link module:MaterialNode.materialIridescence}.
  14717. *
  14718. * @type {Node<float>?}
  14719. * @default null
  14720. */
  14721. this.iridescenceNode = null;
  14722. /**
  14723. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  14724. * property. This node property allows to overwrite the default
  14725. * and define the iridescence IOR with a node instead.
  14726. *
  14727. * If you don't want to overwrite the iridescence IOR but modify the existing
  14728. * value instead, use {@link module:MaterialNode.materialIridescenceIOR}.
  14729. *
  14730. * @type {Node<float>?}
  14731. * @default null
  14732. */
  14733. this.iridescenceIORNode = null;
  14734. /**
  14735. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  14736. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  14737. * and define the iridescence thickness with a node instead.
  14738. *
  14739. * If you don't want to overwrite the iridescence thickness but modify the existing
  14740. * value instead, use {@link module:MaterialNode.materialIridescenceThickness}.
  14741. *
  14742. * @type {Node<float>?}
  14743. * @default null
  14744. */
  14745. this.iridescenceThicknessNode = null;
  14746. /**
  14747. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  14748. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  14749. * and define the specular intensity with a node instead.
  14750. *
  14751. * If you don't want to overwrite the specular intensity but modify the existing
  14752. * value instead, use {@link module:MaterialNode.materialSpecularIntensity}.
  14753. *
  14754. * @type {Node<float>?}
  14755. * @default null
  14756. */
  14757. this.specularIntensityNode = null;
  14758. /**
  14759. * The specular color of physical materials is by default inferred from the `specularColor`
  14760. * and `specularColorMap` properties. This node property allows to overwrite the default
  14761. * and define the specular color with a node instead.
  14762. *
  14763. * If you don't want to overwrite the specular color but modify the existing
  14764. * value instead, use {@link module:MaterialNode.materialSpecularColor}.
  14765. *
  14766. * @type {Node<vec3>?}
  14767. * @default null
  14768. */
  14769. this.specularColorNode = null;
  14770. /**
  14771. * The ior of physical materials is by default inferred from the `ior`
  14772. * property. This node property allows to overwrite the default
  14773. * and define the ior with a node instead.
  14774. *
  14775. * If you don't want to overwrite the ior but modify the existing
  14776. * value instead, use {@link module:MaterialNode.materialIOR}.
  14777. *
  14778. * @type {Node<float>?}
  14779. * @default null
  14780. */
  14781. this.iorNode = null;
  14782. /**
  14783. * The transmission of physical materials is by default inferred from the `transmission` and
  14784. * `transmissionMap` properties. This node property allows to overwrite the default
  14785. * and define the transmission with a node instead.
  14786. *
  14787. * If you don't want to overwrite the transmission but modify the existing
  14788. * value instead, use {@link module:MaterialNode.materialTransmission}.
  14789. *
  14790. * @type {Node<float>?}
  14791. * @default null
  14792. */
  14793. this.transmissionNode = null;
  14794. /**
  14795. * The thickness of physical materials is by default inferred from the `thickness` and
  14796. * `thicknessMap` properties. This node property allows to overwrite the default
  14797. * and define the thickness with a node instead.
  14798. *
  14799. * If you don't want to overwrite the thickness but modify the existing
  14800. * value instead, use {@link module:MaterialNode.materialThickness}.
  14801. *
  14802. * @type {Node<float>?}
  14803. * @default null
  14804. */
  14805. this.thicknessNode = null;
  14806. /**
  14807. * The attenuation distance of physical materials is by default inferred from the
  14808. * `attenuationDistance` property. This node property allows to overwrite the default
  14809. * and define the attenuation distance with a node instead.
  14810. *
  14811. * If you don't want to overwrite the attenuation distance but modify the existing
  14812. * value instead, use {@link module:MaterialNode.materialAttenuationDistance}.
  14813. *
  14814. * @type {Node<float>?}
  14815. * @default null
  14816. */
  14817. this.attenuationDistanceNode = null;
  14818. /**
  14819. * The attenuation color of physical materials is by default inferred from the
  14820. * `attenuationColor` property. This node property allows to overwrite the default
  14821. * and define the attenuation color with a node instead.
  14822. *
  14823. * If you don't want to overwrite the attenuation color but modify the existing
  14824. * value instead, use {@link module:MaterialNode.materialAttenuationColor}.
  14825. *
  14826. * @type {Node<vec3>?}
  14827. * @default null
  14828. */
  14829. this.attenuationColorNode = null;
  14830. /**
  14831. * The dispersion of physical materials is by default inferred from the
  14832. * `dispersion` property. This node property allows to overwrite the default
  14833. * and define the dispersion with a node instead.
  14834. *
  14835. * If you don't want to overwrite the dispersion but modify the existing
  14836. * value instead, use {@link module:MaterialNode.materialDispersion}.
  14837. *
  14838. * @type {Node<float>?}
  14839. * @default null
  14840. */
  14841. this.dispersionNode = null;
  14842. /**
  14843. * The anisotropy of physical materials is by default inferred from the
  14844. * `anisotropy` property. This node property allows to overwrite the default
  14845. * and define the anisotropy with a node instead.
  14846. *
  14847. * If you don't want to overwrite the anisotropy but modify the existing
  14848. * value instead, use {@link module:MaterialNode.materialAnisotropy}.
  14849. *
  14850. * @type {Node<float>?}
  14851. * @default null
  14852. */
  14853. this.anisotropyNode = null;
  14854. this.setDefaultValues( _defaultValues$5 );
  14855. this.setValues( parameters );
  14856. }
  14857. /**
  14858. * Whether the lighting model should use clearcoat or not.
  14859. *
  14860. * @type {Boolean}
  14861. * @default true
  14862. */
  14863. get useClearcoat() {
  14864. return this.clearcoat > 0 || this.clearcoatNode !== null;
  14865. }
  14866. /**
  14867. * Whether the lighting model should use iridescence or not.
  14868. *
  14869. * @type {Boolean}
  14870. * @default true
  14871. */
  14872. get useIridescence() {
  14873. return this.iridescence > 0 || this.iridescenceNode !== null;
  14874. }
  14875. /**
  14876. * Whether the lighting model should use sheen or not.
  14877. *
  14878. * @type {Boolean}
  14879. * @default true
  14880. */
  14881. get useSheen() {
  14882. return this.sheen > 0 || this.sheenNode !== null;
  14883. }
  14884. /**
  14885. * Whether the lighting model should use anisotropy or not.
  14886. *
  14887. * @type {Boolean}
  14888. * @default true
  14889. */
  14890. get useAnisotropy() {
  14891. return this.anisotropy > 0 || this.anisotropyNode !== null;
  14892. }
  14893. /**
  14894. * Whether the lighting model should use transmission or not.
  14895. *
  14896. * @type {Boolean}
  14897. * @default true
  14898. */
  14899. get useTransmission() {
  14900. return this.transmission > 0 || this.transmissionNode !== null;
  14901. }
  14902. /**
  14903. * Whether the lighting model should use dispersion or not.
  14904. *
  14905. * @type {Boolean}
  14906. * @default true
  14907. */
  14908. get useDispersion() {
  14909. return this.dispersion > 0 || this.dispersionNode !== null;
  14910. }
  14911. /**
  14912. * Setups the specular related node variables.
  14913. */
  14914. setupSpecular() {
  14915. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  14916. ior.assign( iorNode );
  14917. 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 ) );
  14918. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  14919. }
  14920. /**
  14921. * Setups the lighting model.
  14922. *
  14923. * @return {PhysicalLightingModel} The lighting model.
  14924. */
  14925. setupLightingModel( /*builder*/ ) {
  14926. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  14927. }
  14928. /**
  14929. * Setups the physical specific node variables.
  14930. *
  14931. * @param {NodeBuilder} builder - The current node builder.
  14932. */
  14933. setupVariants( builder ) {
  14934. super.setupVariants( builder );
  14935. // CLEARCOAT
  14936. if ( this.useClearcoat ) {
  14937. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  14938. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  14939. clearcoat.assign( clearcoatNode );
  14940. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  14941. }
  14942. // SHEEN
  14943. if ( this.useSheen ) {
  14944. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  14945. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  14946. sheen.assign( sheenNode );
  14947. sheenRoughness.assign( sheenRoughnessNode );
  14948. }
  14949. // IRIDESCENCE
  14950. if ( this.useIridescence ) {
  14951. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  14952. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  14953. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  14954. iridescence.assign( iridescenceNode );
  14955. iridescenceIOR.assign( iridescenceIORNode );
  14956. iridescenceThickness.assign( iridescenceThicknessNode );
  14957. }
  14958. // ANISOTROPY
  14959. if ( this.useAnisotropy ) {
  14960. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  14961. anisotropy.assign( anisotropyV.length() );
  14962. If( anisotropy.equal( 0.0 ), () => {
  14963. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  14964. } ).Else( () => {
  14965. anisotropyV.divAssign( vec2( anisotropy ) );
  14966. anisotropy.assign( anisotropy.saturate() );
  14967. } );
  14968. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  14969. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  14970. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  14971. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  14972. }
  14973. // TRANSMISSION
  14974. if ( this.useTransmission ) {
  14975. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  14976. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  14977. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  14978. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  14979. transmission.assign( transmissionNode );
  14980. thickness.assign( thicknessNode );
  14981. attenuationDistance.assign( attenuationDistanceNode );
  14982. attenuationColor.assign( attenuationColorNode );
  14983. if ( this.useDispersion ) {
  14984. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  14985. dispersion.assign( dispersionNode );
  14986. }
  14987. }
  14988. }
  14989. /**
  14990. * Setups the clearcoat normal node.
  14991. *
  14992. * @return {Node<vec3>} The clearcoat normal.
  14993. */
  14994. setupClearcoatNormal() {
  14995. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  14996. }
  14997. setup( builder ) {
  14998. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  14999. super.setup( builder );
  15000. }
  15001. copy( source ) {
  15002. this.clearcoatNode = source.clearcoatNode;
  15003. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  15004. this.clearcoatNormalNode = source.clearcoatNormalNode;
  15005. this.sheenNode = source.sheenNode;
  15006. this.sheenRoughnessNode = source.sheenRoughnessNode;
  15007. this.iridescenceNode = source.iridescenceNode;
  15008. this.iridescenceIORNode = source.iridescenceIORNode;
  15009. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  15010. this.specularIntensityNode = source.specularIntensityNode;
  15011. this.specularColorNode = source.specularColorNode;
  15012. this.transmissionNode = source.transmissionNode;
  15013. this.thicknessNode = source.thicknessNode;
  15014. this.attenuationDistanceNode = source.attenuationDistanceNode;
  15015. this.attenuationColorNode = source.attenuationColorNode;
  15016. this.dispersionNode = source.dispersionNode;
  15017. this.anisotropyNode = source.anisotropyNode;
  15018. return super.copy( source );
  15019. }
  15020. }
  15021. /** @module MeshSSSNodeMaterial **/
  15022. /**
  15023. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  15024. *
  15025. * @augments PhysicalLightingModel
  15026. */
  15027. class SSSLightingModel extends PhysicalLightingModel {
  15028. /**
  15029. * Constructs a new physical lighting model.
  15030. *
  15031. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15032. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  15033. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  15034. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15035. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  15036. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  15037. * @param {Boolean} [sss=false] - Whether SSS is supported or not.
  15038. */
  15039. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  15040. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  15041. /**
  15042. * Whether the lighting model should use SSS or not.
  15043. *
  15044. * @type {Boolean}
  15045. * @default false
  15046. */
  15047. this.useSSS = sss;
  15048. }
  15049. /**
  15050. * Extends the default implementation with a SSS term.
  15051. *
  15052. * 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/}
  15053. *
  15054. * @param {Object} input - The input data.
  15055. * @param {StackNode} stack - The current stack.
  15056. * @param {NodeBuilder} builder - The current node builder.
  15057. */
  15058. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15059. if ( this.useSSS === true ) {
  15060. const material = builder.material;
  15061. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  15062. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  15063. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  15064. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  15065. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  15066. }
  15067. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  15068. }
  15069. }
  15070. /**
  15071. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  15072. * that implements a Subsurface scattering (SSS) term.
  15073. *
  15074. * @augments MeshPhysicalNodeMaterial
  15075. */
  15076. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15077. static get type() {
  15078. return 'MeshSSSNodeMaterial';
  15079. }
  15080. /**
  15081. * Constructs a new mesh SSS node material.
  15082. *
  15083. * @param {Object?} parameters - The configuration parameter.
  15084. */
  15085. constructor( parameters ) {
  15086. super( parameters );
  15087. /**
  15088. * Represents the thickness color.
  15089. *
  15090. * @type {Node<vec3>?}
  15091. * @default null
  15092. */
  15093. this.thicknessColorNode = null;
  15094. /**
  15095. * Represents the distortion factor.
  15096. *
  15097. * @type {Node<float>?}
  15098. */
  15099. this.thicknessDistortionNode = float( 0.1 );
  15100. /**
  15101. * Represents the thickness ambient factor.
  15102. *
  15103. * @type {Node<float>?}
  15104. */
  15105. this.thicknessAmbientNode = float( 0.0 );
  15106. /**
  15107. * Represents the thickness attenuation.
  15108. *
  15109. * @type {Node<float>?}
  15110. */
  15111. this.thicknessAttenuationNode = float( .1 );
  15112. /**
  15113. * Represents the thickness power.
  15114. *
  15115. * @type {Node<float>?}
  15116. */
  15117. this.thicknessPowerNode = float( 2.0 );
  15118. /**
  15119. * Represents the thickness scale.
  15120. *
  15121. * @type {Node<float>?}
  15122. */
  15123. this.thicknessScaleNode = float( 10.0 );
  15124. }
  15125. /**
  15126. * Whether the lighting model should use SSS or not.
  15127. *
  15128. * @type {Boolean}
  15129. * @default true
  15130. */
  15131. get useSSS() {
  15132. return this.thicknessColorNode !== null;
  15133. }
  15134. /**
  15135. * Setups the lighting model.
  15136. *
  15137. * @return {SSSLightingModel} The lighting model.
  15138. */
  15139. setupLightingModel( /*builder*/ ) {
  15140. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15141. }
  15142. copy( source ) {
  15143. this.thicknessColorNode = source.thicknessColorNode;
  15144. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15145. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15146. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15147. this.thicknessPowerNode = source.thicknessPowerNode;
  15148. this.thicknessScaleNode = source.thicknessScaleNode;
  15149. return super.copy( source );
  15150. }
  15151. }
  15152. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15153. // dotNL will be from -1.0 to 1.0
  15154. const dotNL = normal.dot( lightDirection );
  15155. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15156. if ( builder.material.gradientMap ) {
  15157. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15158. return vec3( gradientMap.r );
  15159. } else {
  15160. const fw = coord.fwidth().mul( 0.5 );
  15161. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15162. }
  15163. } );
  15164. /**
  15165. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15166. *
  15167. * @augments LightingModel
  15168. */
  15169. class ToonLightingModel extends LightingModel {
  15170. /**
  15171. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15172. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15173. *
  15174. * @param {Object} input - The input data.
  15175. * @param {StackNode} stack - The current stack.
  15176. * @param {NodeBuilder} builder - The current node builder.
  15177. */
  15178. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15179. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15180. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15181. }
  15182. /**
  15183. * Implements the indirect lighting.
  15184. *
  15185. * @param {ContextNode} input - The current node context.
  15186. * @param {StackNode} stack - The current stack.
  15187. * @param {NodeBuilder} builder - The current node builder.
  15188. */
  15189. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15190. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15191. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15192. }
  15193. }
  15194. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15195. /**
  15196. * Node material version of `MeshToonMaterial`.
  15197. *
  15198. * @augments NodeMaterial
  15199. */
  15200. class MeshToonNodeMaterial extends NodeMaterial {
  15201. static get type() {
  15202. return 'MeshToonNodeMaterial';
  15203. }
  15204. /**
  15205. * Constructs a new mesh toon node material.
  15206. *
  15207. * @param {Object?} parameters - The configuration parameter.
  15208. */
  15209. constructor( parameters ) {
  15210. super();
  15211. /**
  15212. * This flag can be used for type testing.
  15213. *
  15214. * @type {Boolean}
  15215. * @readonly
  15216. * @default true
  15217. */
  15218. this.isMeshToonNodeMaterial = true;
  15219. /**
  15220. * Set to `true` because toon materials react on lights.
  15221. *
  15222. * @type {Boolean}
  15223. * @default true
  15224. */
  15225. this.lights = true;
  15226. this.setDefaultValues( _defaultValues$4 );
  15227. this.setValues( parameters );
  15228. }
  15229. /**
  15230. * Setups the lighting model.
  15231. *
  15232. * @return {ToonLightingModel} The lighting model.
  15233. */
  15234. setupLightingModel( /*builder*/ ) {
  15235. return new ToonLightingModel();
  15236. }
  15237. }
  15238. /** @module MatcapUVNode **/
  15239. /**
  15240. * Can be used to compute texture coordinates for projecting a
  15241. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15242. *
  15243. * @augments TempNode
  15244. */
  15245. class MatcapUVNode extends TempNode {
  15246. static get type() {
  15247. return 'MatcapUVNode';
  15248. }
  15249. /**
  15250. * Constructs a new matcap uv node.
  15251. */
  15252. constructor() {
  15253. super( 'vec2' );
  15254. }
  15255. setup() {
  15256. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15257. const y = positionViewDirection.cross( x );
  15258. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15259. }
  15260. }
  15261. /**
  15262. * TSL function for creating a matcap uv node.
  15263. *
  15264. * @function
  15265. * @returns {MatcapUVNode}
  15266. */
  15267. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15268. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15269. /**
  15270. * Node material version of `MeshMatcapMaterial`.
  15271. *
  15272. * @augments NodeMaterial
  15273. */
  15274. class MeshMatcapNodeMaterial extends NodeMaterial {
  15275. static get type() {
  15276. return 'MeshMatcapNodeMaterial';
  15277. }
  15278. /**
  15279. * Constructs a new mesh normal node material.
  15280. *
  15281. * @param {Object?} parameters - The configuration parameter.
  15282. */
  15283. constructor( parameters ) {
  15284. super();
  15285. /**
  15286. * This flag can be used for type testing.
  15287. *
  15288. * @type {Boolean}
  15289. * @readonly
  15290. * @default true
  15291. */
  15292. this.isMeshMatcapNodeMaterial = true;
  15293. this.setDefaultValues( _defaultValues$3 );
  15294. this.setValues( parameters );
  15295. }
  15296. /**
  15297. * Setups the matcap specific node variables.
  15298. *
  15299. * @param {NodeBuilder} builder - The current node builder.
  15300. */
  15301. setupVariants( builder ) {
  15302. const uv = matcapUV;
  15303. let matcapColor;
  15304. if ( builder.material.matcap ) {
  15305. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15306. } else {
  15307. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15308. }
  15309. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15310. }
  15311. }
  15312. /** @module RotateNode **/
  15313. /**
  15314. * Applies a rotation to the given position node.
  15315. *
  15316. * @augments TempNode
  15317. */
  15318. class RotateNode extends TempNode {
  15319. static get type() {
  15320. return 'RotateNode';
  15321. }
  15322. /**
  15323. * Constructs a new rotate node.
  15324. *
  15325. * @param {Node} positionNode - The position node.
  15326. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15327. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15328. */
  15329. constructor( positionNode, rotationNode ) {
  15330. super();
  15331. /**
  15332. * The position node.
  15333. *
  15334. * @type {Node}
  15335. */
  15336. this.positionNode = positionNode;
  15337. /**
  15338. * Represents the rotation that is applied to the position node.
  15339. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15340. *
  15341. * @type {Node}
  15342. */
  15343. this.rotationNode = rotationNode;
  15344. }
  15345. /**
  15346. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15347. *
  15348. * @param {NodeBuilder} builder - The current node builder.
  15349. * @return {String} The node's type.
  15350. */
  15351. getNodeType( builder ) {
  15352. return this.positionNode.getNodeType( builder );
  15353. }
  15354. setup( builder ) {
  15355. const { rotationNode, positionNode } = this;
  15356. const nodeType = this.getNodeType( builder );
  15357. if ( nodeType === 'vec2' ) {
  15358. const cosAngle = rotationNode.cos();
  15359. const sinAngle = rotationNode.sin();
  15360. const rotationMatrix = mat2(
  15361. cosAngle, sinAngle,
  15362. sinAngle.negate(), cosAngle
  15363. );
  15364. return rotationMatrix.mul( positionNode );
  15365. } else {
  15366. const rotation = rotationNode;
  15367. 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 ) );
  15368. 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 ) );
  15369. 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 ) );
  15370. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15371. }
  15372. }
  15373. }
  15374. /**
  15375. * TSL function for creating a rotate node.
  15376. *
  15377. * @function
  15378. * @param {Node} positionNode - The position node.
  15379. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15380. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15381. * @returns {RotateNode}
  15382. */
  15383. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15384. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  15385. /**
  15386. * Node material version of `SpriteMaterial`.
  15387. *
  15388. * @augments NodeMaterial
  15389. */
  15390. class SpriteNodeMaterial extends NodeMaterial {
  15391. static get type() {
  15392. return 'SpriteNodeMaterial';
  15393. }
  15394. /**
  15395. * Constructs a new sprite node material.
  15396. *
  15397. * @param {Object?} parameters - The configuration parameter.
  15398. */
  15399. constructor( parameters ) {
  15400. super();
  15401. /**
  15402. * This flag can be used for type testing.
  15403. *
  15404. * @type {Boolean}
  15405. * @readonly
  15406. * @default true
  15407. */
  15408. this.isSpriteNodeMaterial = true;
  15409. this._useSizeAttenuation = true;
  15410. /**
  15411. * This property makes it possible to define the position of the sprite with a
  15412. * node. That can be useful when the material is used with instanced rendering
  15413. * and node data are defined with an instanced attribute node:
  15414. * ```js
  15415. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15416. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15417. * ```
  15418. * Another possibility is to compute the instanced data with a compute shader:
  15419. * ```js
  15420. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15421. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15422. * ```
  15423. *
  15424. * @type {Node<vec2>?}
  15425. * @default null
  15426. */
  15427. this.positionNode = null;
  15428. /**
  15429. * The rotation of sprite materials is by default inferred from the `rotation`,
  15430. * property. This node property allows to overwrite the default and define
  15431. * the rotation with a node instead.
  15432. *
  15433. * If you don't want to overwrite the rotation but modify the existing
  15434. * value instead, use {@link module:MaterialNode.materialRotation}.
  15435. *
  15436. * @type {Node<float>?}
  15437. * @default null
  15438. */
  15439. this.rotationNode = null;
  15440. /**
  15441. * This node property provides an additional way to scale sprites next to
  15442. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15443. * is multiplied with the scale value of this node in the vertex shader.
  15444. *
  15445. * @type {Node<vec2>?}
  15446. * @default null
  15447. */
  15448. this.scaleNode = null;
  15449. this.setDefaultValues( _defaultValues$2 );
  15450. this.setValues( parameters );
  15451. }
  15452. /**
  15453. * Setups the position node in view space. This method implements
  15454. * the sprite specific vertex shader.
  15455. *
  15456. * @param {NodeBuilder} builder - The current node builder.
  15457. * @return {Node<vec3>} The position in view space.
  15458. */
  15459. setupPositionView( builder ) {
  15460. const { object, camera } = builder;
  15461. const sizeAttenuation = this.sizeAttenuation;
  15462. const { positionNode, rotationNode, scaleNode } = this;
  15463. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15464. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15465. if ( scaleNode !== null ) {
  15466. scale = scale.mul( float( scaleNode ) );
  15467. }
  15468. if ( sizeAttenuation === false ) {
  15469. if ( camera.isPerspectiveCamera ) {
  15470. scale = scale.mul( mvPosition.z.negate() );
  15471. } else {
  15472. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15473. scale = scale.mul( orthoScale.mul( 2 ) );
  15474. }
  15475. }
  15476. let alignedPosition = positionGeometry.xy;
  15477. if ( object.center && object.center.isVector2 === true ) {
  15478. const center = reference$1( 'center', 'vec2', object );
  15479. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15480. }
  15481. alignedPosition = alignedPosition.mul( scale );
  15482. const rotation = float( rotationNode || materialRotation );
  15483. const rotatedPosition = rotate( alignedPosition, rotation );
  15484. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15485. }
  15486. copy( source ) {
  15487. this.positionNode = source.positionNode;
  15488. this.rotationNode = source.rotationNode;
  15489. this.scaleNode = source.scaleNode;
  15490. return super.copy( source );
  15491. }
  15492. /**
  15493. * Whether to use size attenuation or not.
  15494. *
  15495. * @type {Boolean}
  15496. * @default true
  15497. */
  15498. get sizeAttenuation() {
  15499. return this._useSizeAttenuation;
  15500. }
  15501. set sizeAttenuation( value ) {
  15502. if ( this._useSizeAttenuation !== value ) {
  15503. this._useSizeAttenuation = value;
  15504. this.needsUpdate = true;
  15505. }
  15506. }
  15507. }
  15508. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  15509. /**
  15510. * Node material version of `PointsMaterial`.
  15511. *
  15512. * @augments NodeMaterial
  15513. */
  15514. class PointsNodeMaterial extends SpriteNodeMaterial {
  15515. static get type() {
  15516. return 'PointsNodeMaterial';
  15517. }
  15518. /**
  15519. * Constructs a new points node material.
  15520. *
  15521. * @param {Object?} parameters - The configuration parameter.
  15522. */
  15523. constructor( parameters ) {
  15524. super();
  15525. /**
  15526. * This node property provides an additional way to set the point size.
  15527. *
  15528. * @type {Node<vec2>?}
  15529. * @default null
  15530. */
  15531. this.sizeNode = null;
  15532. /**
  15533. * This flag can be used for type testing.
  15534. *
  15535. * @type {Boolean}
  15536. * @readonly
  15537. * @default true
  15538. */
  15539. this.isPointsNodeMaterial = true;
  15540. this.setDefaultValues( _defaultValues$1 );
  15541. this.setValues( parameters );
  15542. }
  15543. setupPositionView() {
  15544. const { positionNode } = this;
  15545. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  15546. }
  15547. setupVertex( builder ) {
  15548. const mvp = super.setupVertex( builder );
  15549. // skip further processing if the material is not a node material
  15550. if ( builder.material.isNodeMaterial !== true ) {
  15551. return mvp;
  15552. }
  15553. // ndc space
  15554. const { rotationNode, scaleNode, sizeNode } = this;
  15555. const alignedPosition = positionGeometry.xy.toVar();
  15556. const aspect = viewport.z.div( viewport.w );
  15557. // rotation
  15558. if ( rotationNode && rotationNode.isNode ) {
  15559. const rotation = float( rotationNode );
  15560. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  15561. }
  15562. // point size
  15563. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  15564. if ( this.sizeAttenuation === true ) {
  15565. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  15566. }
  15567. // scale
  15568. if ( scaleNode && scaleNode.isNode ) {
  15569. pointSize = pointSize.mul( vec2( scaleNode ) );
  15570. }
  15571. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  15572. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  15573. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  15574. // back to clip space
  15575. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  15576. //clipPos.xy += offset;
  15577. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  15578. return mvp;
  15579. }
  15580. /**
  15581. * Whether alpha to coverage should be used or not.
  15582. *
  15583. * @type {Boolean}
  15584. * @default true
  15585. */
  15586. get alphaToCoverage() {
  15587. return this._useAlphaToCoverage;
  15588. }
  15589. set alphaToCoverage( value ) {
  15590. if ( this._useAlphaToCoverage !== value ) {
  15591. this._useAlphaToCoverage = value;
  15592. this.needsUpdate = true;
  15593. }
  15594. }
  15595. }
  15596. /**
  15597. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  15598. *
  15599. * @augments LightingModel
  15600. */
  15601. class ShadowMaskModel extends LightingModel {
  15602. /**
  15603. * Constructs a new shadow mask model.
  15604. */
  15605. constructor() {
  15606. super();
  15607. /**
  15608. * The shadow mask node.
  15609. *
  15610. * @type {Node}
  15611. */
  15612. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  15613. }
  15614. /**
  15615. * Only used to save the shadow mask.
  15616. *
  15617. * @param {Object} input - The input data.
  15618. */
  15619. direct( { shadowMask } ) {
  15620. this.shadowNode.mulAssign( shadowMask );
  15621. }
  15622. /**
  15623. * Uses the shadow mask to produce the final color.
  15624. *
  15625. * @param {ContextNode} context - The current node context.
  15626. */
  15627. finish( context ) {
  15628. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  15629. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  15630. }
  15631. }
  15632. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  15633. /**
  15634. * Node material version of `ShadowMaterial`.
  15635. *
  15636. * @augments NodeMaterial
  15637. */
  15638. class ShadowNodeMaterial extends NodeMaterial {
  15639. static get type() {
  15640. return 'ShadowNodeMaterial';
  15641. }
  15642. /**
  15643. * Constructs a new shadow node material.
  15644. *
  15645. * @param {Object?} parameters - The configuration parameter.
  15646. */
  15647. constructor( parameters ) {
  15648. super();
  15649. /**
  15650. * This flag can be used for type testing.
  15651. *
  15652. * @type {Boolean}
  15653. * @readonly
  15654. * @default true
  15655. */
  15656. this.isShadowNodeMaterial = true;
  15657. /**
  15658. * Set to `true` because so it's possible to implement
  15659. * the shadow mask effect.
  15660. *
  15661. * @type {Boolean}
  15662. * @default true
  15663. */
  15664. this.lights = true;
  15665. this.setDefaultValues( _defaultValues );
  15666. this.setValues( parameters );
  15667. }
  15668. /**
  15669. * Setups the lighting model.
  15670. *
  15671. * @return {ShadowMaskModel} The lighting model.
  15672. */
  15673. setupLightingModel( /*builder*/ ) {
  15674. return new ShadowMaskModel();
  15675. }
  15676. }
  15677. /** @module Texture3DNode **/
  15678. const normal = Fn( ( { texture, uv } ) => {
  15679. const epsilon = 0.0001;
  15680. const ret = vec3().toVar();
  15681. If( uv.x.lessThan( epsilon ), () => {
  15682. ret.assign( vec3( 1, 0, 0 ) );
  15683. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  15684. ret.assign( vec3( 0, 1, 0 ) );
  15685. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  15686. ret.assign( vec3( 0, 0, 1 ) );
  15687. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  15688. ret.assign( vec3( - 1, 0, 0 ) );
  15689. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  15690. ret.assign( vec3( 0, - 1, 0 ) );
  15691. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  15692. ret.assign( vec3( 0, 0, - 1 ) );
  15693. } ).Else( () => {
  15694. const step = 0.01;
  15695. 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 );
  15696. 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 );
  15697. 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 );
  15698. ret.assign( vec3( x, y, z ) );
  15699. } );
  15700. return ret.normalize();
  15701. } );
  15702. /**
  15703. * This type of uniform node represents a 3D texture.
  15704. *
  15705. * @augments module:TextureNode~TextureNode
  15706. */
  15707. class Texture3DNode extends TextureNode {
  15708. static get type() {
  15709. return 'Texture3DNode';
  15710. }
  15711. /**
  15712. * Constructs a new 3D texture node.
  15713. *
  15714. * @param {Data3DTexture} value - The 3D texture.
  15715. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15716. * @param {Node<int>?} [levelNode=null] - The level node.
  15717. */
  15718. constructor( value, uvNode = null, levelNode = null ) {
  15719. super( value, uvNode, levelNode );
  15720. /**
  15721. * This flag can be used for type testing.
  15722. *
  15723. * @type {Boolean}
  15724. * @readonly
  15725. * @default true
  15726. */
  15727. this.isTexture3DNode = true;
  15728. }
  15729. /**
  15730. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  15731. *
  15732. * @param {NodeBuilder} builder - The current node builder.
  15733. * @return {String} The input type.
  15734. */
  15735. getInputType( /*builder*/ ) {
  15736. return 'texture3D';
  15737. }
  15738. /**
  15739. * Returns a default uv node which is in context of 3D textures a three-dimensional
  15740. * uv node.
  15741. *
  15742. * @return {Node<vec3>} The default uv node.
  15743. */
  15744. getDefaultUV() {
  15745. return vec3( 0.5, 0.5, 0.5 );
  15746. }
  15747. /**
  15748. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  15749. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  15750. *
  15751. * @param {Boolean} value - The update toggle.
  15752. */
  15753. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  15754. /**
  15755. * Overwrites the default implementation to return the unmodified uv node.
  15756. *
  15757. * @param {NodeBuilder} builder - The current node builder.
  15758. * @param {Node} uvNode - The uv node to setup.
  15759. * @return {Node} The unmodified uv node.
  15760. */
  15761. setupUV( builder, uvNode ) {
  15762. const texture = this.value;
  15763. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  15764. if ( this.sampler ) {
  15765. uvNode = uvNode.flipY();
  15766. } else {
  15767. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  15768. }
  15769. }
  15770. return uvNode;
  15771. }
  15772. /**
  15773. * Generates the uv code snippet.
  15774. *
  15775. * @param {NodeBuilder} builder - The current node builder.
  15776. * @param {Node} uvNode - The uv node to generate code for.
  15777. * @return {String} The generated code snippet.
  15778. */
  15779. generateUV( builder, uvNode ) {
  15780. return uvNode.build( builder, 'vec3' );
  15781. }
  15782. /**
  15783. * TODO.
  15784. *
  15785. * @param {Node<vec3>} uvNode - The uv node .
  15786. * @return {Node<vec3>} TODO.
  15787. */
  15788. normal( uvNode ) {
  15789. return normal( { texture: this, uv: uvNode } );
  15790. }
  15791. }
  15792. /**
  15793. * TSL function for creating a 3D texture node.
  15794. *
  15795. * @function
  15796. * @param {Data3DTexture} value - The 3D texture.
  15797. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15798. * @param {Node<int>?} [levelNode=null] - The level node.
  15799. * @returns {Texture3DNode}
  15800. */
  15801. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  15802. /** @module VolumeNodeMaterial **/
  15803. /**
  15804. * Node material intended for volume rendering. The volumetric data are
  15805. * defined with an instance of {@link Data3DTexture}.
  15806. *
  15807. * @augments NodeMaterial
  15808. */
  15809. class VolumeNodeMaterial extends NodeMaterial {
  15810. static get type() {
  15811. return 'VolumeNodeMaterial';
  15812. }
  15813. /**
  15814. * Constructs a new volume node material.
  15815. *
  15816. * @param {Object?} parameters - The configuration parameter.
  15817. */
  15818. constructor( parameters ) {
  15819. super();
  15820. /**
  15821. * This flag can be used for type testing.
  15822. *
  15823. * @type {Boolean}
  15824. * @readonly
  15825. * @default true
  15826. */
  15827. this.isVolumeNodeMaterial = true;
  15828. /**
  15829. * The base color of the volume.
  15830. *
  15831. * @type {Color}
  15832. * @default 100
  15833. */
  15834. this.base = new Color( 0xffffff );
  15835. /**
  15836. * A 3D data texture holding the volumetric data.
  15837. *
  15838. * @type {Data3DTexture?}
  15839. * @default null
  15840. */
  15841. this.map = null;
  15842. /**
  15843. * This number of samples for each ray that hits the mesh's surface
  15844. * and travels through the volume.
  15845. *
  15846. * @type {Number}
  15847. * @default 100
  15848. */
  15849. this.steps = 100;
  15850. /**
  15851. * Callback for {@link VolumeNodeMaterial#testNode}.
  15852. *
  15853. * @callback testNodeCallback
  15854. * @param {Data3DTexture<float>} map - The 3D texture.
  15855. * @param {Node<float>} mapValue - The sampled value inside the volume.
  15856. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  15857. * @param {Node<vec4>} finalColor - The final color.
  15858. */
  15859. /**
  15860. * The volume rendering of this material works by shooting rays
  15861. * from the camera position through each fragment of the mesh's
  15862. * surface and sample the inner volume in a raymarching fashion
  15863. * multiple times.
  15864. *
  15865. * This node can be used to assign a callback function of type `Fn`
  15866. * that will be executed per sample. The callback receives the
  15867. * texture, the sampled texture value as well as position on the surface
  15868. * where the rays enters the volume. The last parameter is a color
  15869. * that allows the callback to determine the final color.
  15870. *
  15871. * @type {testNodeCallback?}
  15872. * @default null
  15873. */
  15874. this.testNode = null;
  15875. this.setValues( parameters );
  15876. }
  15877. /**
  15878. * Setups the vertex and fragment stage of this node material.
  15879. *
  15880. * @param {NodeBuilder} builder - The current node builder.
  15881. */
  15882. setup( builder ) {
  15883. const map = texture3D( this.map, null, 0 );
  15884. const hitBox = Fn( ( { orig, dir } ) => {
  15885. const box_min = vec3( - 0.5 );
  15886. const box_max = vec3( 0.5 );
  15887. const inv_dir = dir.reciprocal();
  15888. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  15889. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  15890. const tmin = min$1( tmin_tmp, tmax_tmp );
  15891. const tmax = max$1( tmin_tmp, tmax_tmp );
  15892. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  15893. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  15894. return vec2( t0, t1 );
  15895. } );
  15896. this.fragmentNode = Fn( () => {
  15897. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  15898. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  15899. const rayDir = vDirection.normalize();
  15900. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  15901. bounds.x.greaterThan( bounds.y ).discard();
  15902. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  15903. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  15904. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  15905. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  15906. delta.divAssign( materialReference( 'steps', 'float' ) );
  15907. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  15908. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  15909. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  15910. if ( this.testNode !== null ) {
  15911. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  15912. } else {
  15913. // default to show surface of mesh
  15914. ac.a.assign( 1 );
  15915. Break();
  15916. }
  15917. p.addAssign( rayDir.mul( delta ) );
  15918. } );
  15919. ac.a.equal( 0 ).discard();
  15920. return vec4( ac );
  15921. } )();
  15922. super.setup( builder );
  15923. }
  15924. }
  15925. /**
  15926. * This module manages the internal animation loop of the renderer.
  15927. *
  15928. * @private
  15929. */
  15930. class Animation {
  15931. /**
  15932. * Constructs a new animation loop management component.
  15933. *
  15934. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  15935. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  15936. */
  15937. constructor( nodes, info ) {
  15938. /**
  15939. * Renderer component for managing nodes related logic.
  15940. *
  15941. * @type {Nodes}
  15942. */
  15943. this.nodes = nodes;
  15944. /**
  15945. * Renderer component for managing metrics and monitoring data.
  15946. *
  15947. * @type {Info}
  15948. */
  15949. this.info = info;
  15950. /**
  15951. * A reference to the context from `requestAnimationFrame()` can
  15952. * be called (usually `window`).
  15953. *
  15954. * @type {Window|XRSession}
  15955. */
  15956. this._context = self;
  15957. /**
  15958. * The user-defined animation loop.
  15959. *
  15960. * @type {Function?}
  15961. * @default null
  15962. */
  15963. this._animationLoop = null;
  15964. /**
  15965. * The requestId which is returned from the `requestAnimationFrame()` call.
  15966. * Can be used to cancel the stop the animation loop.
  15967. *
  15968. * @type {Number?}
  15969. * @default null
  15970. */
  15971. this._requestId = null;
  15972. }
  15973. /**
  15974. * Starts the internal animation loop.
  15975. */
  15976. start() {
  15977. const update = ( time, frame ) => {
  15978. this._requestId = this._context.requestAnimationFrame( update );
  15979. if ( this.info.autoReset === true ) this.info.reset();
  15980. this.nodes.nodeFrame.update();
  15981. this.info.frame = this.nodes.nodeFrame.frameId;
  15982. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  15983. };
  15984. update();
  15985. }
  15986. /**
  15987. * Stops the internal animation loop.
  15988. */
  15989. stop() {
  15990. this._context.cancelAnimationFrame( this._requestId );
  15991. this._requestId = null;
  15992. }
  15993. /**
  15994. * Defines the user-level animation loop.
  15995. *
  15996. * @param {Function} callback - The animation loop.
  15997. */
  15998. setAnimationLoop( callback ) {
  15999. this._animationLoop = callback;
  16000. }
  16001. /**
  16002. * Defines the context in which `requestAnimationFrame()` is executed.
  16003. *
  16004. * @param {Window|XRSession} context - The context to set.
  16005. */
  16006. setContext( context ) {
  16007. this._context = context;
  16008. }
  16009. /**
  16010. * Frees all internal resources and stops the animation loop.
  16011. */
  16012. dispose() {
  16013. this.stop();
  16014. }
  16015. }
  16016. /**
  16017. * Data structure for the renderer. It allows defining values
  16018. * with chained, hierarchical keys. Keys are meant to be
  16019. * objects since the module internally works with Weak Maps
  16020. * for performance reasons.
  16021. *
  16022. * @private
  16023. */
  16024. class ChainMap {
  16025. /**
  16026. * Constructs a new Chain Map.
  16027. */
  16028. constructor() {
  16029. /**
  16030. * The root Weak Map.
  16031. *
  16032. * @type {WeakMap}
  16033. */
  16034. this.weakMap = new WeakMap();
  16035. }
  16036. /**
  16037. * Returns the value for the given array of keys.
  16038. *
  16039. * @param {Array<Object>} keys - List of keys.
  16040. * @return {Any} The value. Returns `undefined` if no value was found.
  16041. */
  16042. get( keys ) {
  16043. let map = this.weakMap;
  16044. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16045. map = map.get( keys[ i ] );
  16046. if ( map === undefined ) return undefined;
  16047. }
  16048. return map.get( keys[ keys.length - 1 ] );
  16049. }
  16050. /**
  16051. * Sets the value for the given keys.
  16052. *
  16053. * @param {Array<Object>} keys - List of keys.
  16054. * @param {Any} value - The value to set.
  16055. * @return {ChainMap} A reference to this Chain Map.
  16056. */
  16057. set( keys, value ) {
  16058. let map = this.weakMap;
  16059. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16060. const key = keys[ i ];
  16061. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  16062. map = map.get( key );
  16063. }
  16064. map.set( keys[ keys.length - 1 ], value );
  16065. return this;
  16066. }
  16067. /**
  16068. * Deletes a value for the given keys.
  16069. *
  16070. * @param {Array<Object>} keys - The keys.
  16071. * @return {Boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  16072. */
  16073. delete( keys ) {
  16074. let map = this.weakMap;
  16075. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16076. map = map.get( keys[ i ] );
  16077. if ( map === undefined ) return false;
  16078. }
  16079. return map.delete( keys[ keys.length - 1 ] );
  16080. }
  16081. }
  16082. let _id$9 = 0;
  16083. function getKeys( obj ) {
  16084. const keys = Object.keys( obj );
  16085. let proto = Object.getPrototypeOf( obj );
  16086. while ( proto ) {
  16087. const descriptors = Object.getOwnPropertyDescriptors( proto );
  16088. for ( const key in descriptors ) {
  16089. if ( descriptors[ key ] !== undefined ) {
  16090. const descriptor = descriptors[ key ];
  16091. if ( descriptor && typeof descriptor.get === 'function' ) {
  16092. keys.push( key );
  16093. }
  16094. }
  16095. }
  16096. proto = Object.getPrototypeOf( proto );
  16097. }
  16098. return keys;
  16099. }
  16100. /**
  16101. * A render object is the renderer's representation of single entity that gets drawn
  16102. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  16103. * scene since render objects also depend from the used material, the current render context
  16104. * and the current scene's lighting.
  16105. *
  16106. * In general, the basic process of the renderer is:
  16107. *
  16108. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  16109. * - Process the render lists by calling one or more render commands for each render item.
  16110. * - For each render command, request a render object and perform the draw.
  16111. *
  16112. * The module provides an interface to get data required for the draw command like the actual
  16113. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  16114. * creating render objects should only be done when necessary.
  16115. *
  16116. * @private
  16117. */
  16118. class RenderObject {
  16119. /**
  16120. * Constructs a new render object.
  16121. *
  16122. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16123. * @param {Geometries} geometries - Renderer component for managing geometries.
  16124. * @param {Renderer} renderer - The renderer.
  16125. * @param {Object3D} object - The 3D object.
  16126. * @param {Material} material - The 3D object's material.
  16127. * @param {Scene} scene - The scene the 3D object belongs to.
  16128. * @param {Camera} camera - The camera the object should be rendered with.
  16129. * @param {LightsNode} lightsNode - The lights node.
  16130. * @param {RenderContext} renderContext - The render context.
  16131. * @param {ClippingContext} clippingContext - The clipping context.
  16132. */
  16133. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  16134. this.id = _id$9 ++;
  16135. /**
  16136. * Renderer component for managing nodes related logic.
  16137. *
  16138. * @type {Nodes}
  16139. * @private
  16140. */
  16141. this._nodes = nodes;
  16142. /**
  16143. * Renderer component for managing geometries.
  16144. *
  16145. * @type {Geometries}
  16146. * @private
  16147. */
  16148. this._geometries = geometries;
  16149. /**
  16150. * The renderer.
  16151. *
  16152. * @type {Renderer}
  16153. */
  16154. this.renderer = renderer;
  16155. /**
  16156. * The 3D object.
  16157. *
  16158. * @type {Object3D}
  16159. */
  16160. this.object = object;
  16161. /**
  16162. * The 3D object's material.
  16163. *
  16164. * @type {Material}
  16165. */
  16166. this.material = material;
  16167. /**
  16168. * The scene the 3D object belongs to.
  16169. *
  16170. * @type {Scene}
  16171. */
  16172. this.scene = scene;
  16173. /**
  16174. * The camera the 3D object should be rendered with.
  16175. *
  16176. * @type {Camera}
  16177. */
  16178. this.camera = camera;
  16179. /**
  16180. * The lights node.
  16181. *
  16182. * @type {LightsNode}
  16183. */
  16184. this.lightsNode = lightsNode;
  16185. /**
  16186. * The render context.
  16187. *
  16188. * @type {RenderContext}
  16189. */
  16190. this.context = renderContext;
  16191. /**
  16192. * The 3D object's geometry.
  16193. *
  16194. * @type {BufferGeometry}
  16195. */
  16196. this.geometry = object.geometry;
  16197. /**
  16198. * The render object's version.
  16199. *
  16200. * @type {Number}
  16201. */
  16202. this.version = material.version;
  16203. /**
  16204. * The draw range of the geometry.
  16205. *
  16206. * @type {Object?}
  16207. * @default null
  16208. */
  16209. this.drawRange = null;
  16210. /**
  16211. * An array holding the buffer attributes
  16212. * of the render object. This entails attribute
  16213. * definitions on geometry and node level.
  16214. *
  16215. * @type {Array<BufferAttribute>?}
  16216. * @default null
  16217. */
  16218. this.attributes = null;
  16219. /**
  16220. * A reference to a render pipeline the render
  16221. * object is processed with.
  16222. *
  16223. * @type {RenderPipeline}
  16224. * @default null
  16225. */
  16226. this.pipeline = null;
  16227. /**
  16228. * Only relevant for objects using
  16229. * multiple materials. This represents a group entry
  16230. * from the respective `BufferGeometry`.
  16231. *
  16232. * @type {{start: Number, count: Number}?}
  16233. * @default null
  16234. */
  16235. this.group = null;
  16236. /**
  16237. * An array holding the vertex buffers which can
  16238. * be buffer attributes but also interleaved buffers.
  16239. *
  16240. * @type {Array<BufferAttribute|InterleavedBuffer>?}
  16241. * @default null
  16242. */
  16243. this.vertexBuffers = null;
  16244. /**
  16245. * The parameters for the draw command.
  16246. *
  16247. * @type {Object?}
  16248. * @default null
  16249. */
  16250. this.drawParams = null;
  16251. /**
  16252. * If this render object is used inside a render bundle,
  16253. * this property points to the respective bundle group.
  16254. *
  16255. * @type {BundleGroup?}
  16256. * @default null
  16257. */
  16258. this.bundle = null;
  16259. /**
  16260. * The clipping context.
  16261. *
  16262. * @type {ClippingContext}
  16263. */
  16264. this.clippingContext = clippingContext;
  16265. /**
  16266. * The clipping context's cache key.
  16267. *
  16268. * @type {String}
  16269. */
  16270. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  16271. /**
  16272. * The initial node cache key.
  16273. *
  16274. * @type {Number}
  16275. */
  16276. this.initialNodesCacheKey = this.getDynamicCacheKey();
  16277. /**
  16278. * The initial cache key.
  16279. *
  16280. * @type {Number}
  16281. */
  16282. this.initialCacheKey = this.getCacheKey();
  16283. /**
  16284. * The node builder state.
  16285. *
  16286. * @type {NodeBuilderState?}
  16287. * @private
  16288. * @default null
  16289. */
  16290. this._nodeBuilderState = null;
  16291. /**
  16292. * An array of bindings.
  16293. *
  16294. * @type {Array<BindGroup>?}
  16295. * @private
  16296. * @default null
  16297. */
  16298. this._bindings = null;
  16299. /**
  16300. * Reference to the node material observer.
  16301. *
  16302. * @type {NodeMaterialObserver?}
  16303. * @private
  16304. * @default null
  16305. */
  16306. this._monitor = null;
  16307. /**
  16308. * An event listener which is defined by `RenderObjects`. It performs
  16309. * clean up tasks when `dispose()` on this render object.
  16310. *
  16311. * @method
  16312. */
  16313. this.onDispose = null;
  16314. /**
  16315. * This flag can be used for type testing.
  16316. *
  16317. * @type {Boolean}
  16318. * @readonly
  16319. * @default true
  16320. */
  16321. this.isRenderObject = true;
  16322. /**
  16323. * An event listener which is executed when `dispose()` is called on
  16324. * the render object's material.
  16325. *
  16326. * @method
  16327. */
  16328. this.onMaterialDispose = () => {
  16329. this.dispose();
  16330. };
  16331. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  16332. }
  16333. /**
  16334. * Updates the clipping context.
  16335. *
  16336. * @param {ClippingContext} context - The clipping context to set.
  16337. */
  16338. updateClipping( context ) {
  16339. this.clippingContext = context;
  16340. }
  16341. /**
  16342. * Whether the clipping requires an update or not.
  16343. *
  16344. * @type {Boolean}
  16345. * @readonly
  16346. */
  16347. get clippingNeedsUpdate() {
  16348. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  16349. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  16350. return true;
  16351. }
  16352. /**
  16353. * The number of clipping planes defined in context of hardware clipping.
  16354. *
  16355. * @type {Number}
  16356. * @readonly
  16357. */
  16358. get hardwareClippingPlanes() {
  16359. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  16360. }
  16361. /**
  16362. * Returns the node builder state of this render object.
  16363. *
  16364. * @return {NodeBuilderState} The node builder state.
  16365. */
  16366. getNodeBuilderState() {
  16367. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  16368. }
  16369. /**
  16370. * Returns the node material observer of this render object.
  16371. *
  16372. * @return {NodeMaterialObserver} The node material observer.
  16373. */
  16374. getMonitor() {
  16375. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  16376. }
  16377. /**
  16378. * Returns an array of bind groups of this render object.
  16379. *
  16380. * @return {Array<BindGroup>} The bindings.
  16381. */
  16382. getBindings() {
  16383. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  16384. }
  16385. /**
  16386. * Returns the index of the render object's geometry.
  16387. *
  16388. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  16389. */
  16390. getIndex() {
  16391. return this._geometries.getIndex( this );
  16392. }
  16393. /**
  16394. * Returns the indirect buffer attribute.
  16395. *
  16396. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  16397. */
  16398. getIndirect() {
  16399. return this._geometries.getIndirect( this );
  16400. }
  16401. /**
  16402. * Returns an array that acts as a key for identifying the render object in a chain map.
  16403. *
  16404. * @return {Array<Object>} An array with object references.
  16405. */
  16406. getChainArray() {
  16407. return [ this.object, this.material, this.context, this.lightsNode ];
  16408. }
  16409. /**
  16410. * This method is used when the geometry of a 3D object has been exchanged and the
  16411. * respective render object now requires an update.
  16412. *
  16413. * @param {BufferGeometry} geometry - The geometry to set.
  16414. */
  16415. setGeometry( geometry ) {
  16416. this.geometry = geometry;
  16417. this.attributes = null;
  16418. }
  16419. /**
  16420. * Returns the buffer attributes of the render object. The returned array holds
  16421. * attribute definitions on geometry and node level.
  16422. *
  16423. * @return {Array<BufferAttribute>} An array with buffer attributes.
  16424. */
  16425. getAttributes() {
  16426. if ( this.attributes !== null ) return this.attributes;
  16427. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  16428. const geometry = this.geometry;
  16429. const attributes = [];
  16430. const vertexBuffers = new Set();
  16431. for ( const nodeAttribute of nodeAttributes ) {
  16432. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  16433. if ( attribute === undefined ) continue;
  16434. attributes.push( attribute );
  16435. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  16436. vertexBuffers.add( bufferAttribute );
  16437. }
  16438. this.attributes = attributes;
  16439. this.vertexBuffers = Array.from( vertexBuffers.values() );
  16440. return attributes;
  16441. }
  16442. /**
  16443. * Returns the vertex buffers of the render object.
  16444. *
  16445. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  16446. */
  16447. getVertexBuffers() {
  16448. if ( this.vertexBuffers === null ) this.getAttributes();
  16449. return this.vertexBuffers;
  16450. }
  16451. /**
  16452. * Returns the draw parameters for the render object.
  16453. *
  16454. * @return {{vertexCount: Number, firstVertex: Number, instanceCount: Number, firstInstance: Number}} The draw parameters.
  16455. */
  16456. getDrawParameters() {
  16457. const { object, material, geometry, group, drawRange } = this;
  16458. const drawParams = this.drawParams || ( this.drawParams = {
  16459. vertexCount: 0,
  16460. firstVertex: 0,
  16461. instanceCount: 0,
  16462. firstInstance: 0
  16463. } );
  16464. const index = this.getIndex();
  16465. const hasIndex = ( index !== null );
  16466. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  16467. if ( instanceCount === 0 ) return null;
  16468. drawParams.instanceCount = instanceCount;
  16469. if ( object.isBatchedMesh === true ) return drawParams;
  16470. let rangeFactor = 1;
  16471. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  16472. rangeFactor = 2;
  16473. }
  16474. let firstVertex = drawRange.start * rangeFactor;
  16475. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  16476. if ( group !== null ) {
  16477. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  16478. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  16479. }
  16480. const position = geometry.attributes.position;
  16481. let itemCount = Infinity;
  16482. if ( hasIndex ) {
  16483. itemCount = index.count;
  16484. } else if ( position !== undefined && position !== null ) {
  16485. itemCount = position.count;
  16486. }
  16487. firstVertex = Math.max( firstVertex, 0 );
  16488. lastVertex = Math.min( lastVertex, itemCount );
  16489. const count = lastVertex - firstVertex;
  16490. if ( count < 0 || count === Infinity ) return null;
  16491. drawParams.vertexCount = count;
  16492. drawParams.firstVertex = firstVertex;
  16493. return drawParams;
  16494. }
  16495. /**
  16496. * Returns the render object's geometry cache key.
  16497. *
  16498. * The geometry cache key is part of the material cache key.
  16499. *
  16500. * @return {String} The geometry cache key.
  16501. */
  16502. getGeometryCacheKey() {
  16503. const { geometry } = this;
  16504. let cacheKey = '';
  16505. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  16506. const attribute = geometry.attributes[ name ];
  16507. cacheKey += name + ',';
  16508. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  16509. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  16510. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  16511. if ( attribute.normalized ) cacheKey += 'n,';
  16512. }
  16513. // structural equality isn't sufficient for morph targets since the
  16514. // data are maintained in textures. only if the targets are all equal
  16515. // the texture and thus the instance of `MorphNode` can be shared.
  16516. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  16517. const targets = geometry.morphAttributes[ name ];
  16518. cacheKey += 'morph-' + name + ',';
  16519. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  16520. const attribute = targets[ i ];
  16521. cacheKey += attribute.id + ',';
  16522. }
  16523. }
  16524. if ( geometry.index ) {
  16525. cacheKey += 'index,';
  16526. }
  16527. return cacheKey;
  16528. }
  16529. /**
  16530. * Returns the render object's material cache key.
  16531. *
  16532. * The material cache key is part of the render object cache key.
  16533. *
  16534. * @return {Number} The material cache key.
  16535. */
  16536. getMaterialCacheKey() {
  16537. const { object, material } = this;
  16538. let cacheKey = material.customProgramCacheKey();
  16539. for ( const property of getKeys( material ) ) {
  16540. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  16541. const value = material[ property ];
  16542. let valueKey;
  16543. if ( value !== null ) {
  16544. // some material values require a formatting
  16545. const type = typeof value;
  16546. if ( type === 'number' ) {
  16547. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  16548. } else if ( type === 'object' ) {
  16549. valueKey = '{';
  16550. if ( value.isTexture ) {
  16551. valueKey += value.mapping;
  16552. }
  16553. valueKey += '}';
  16554. } else {
  16555. valueKey = String( value );
  16556. }
  16557. } else {
  16558. valueKey = String( value );
  16559. }
  16560. cacheKey += /*property + ':' +*/ valueKey + ',';
  16561. }
  16562. cacheKey += this.clippingContextCacheKey + ',';
  16563. if ( object.geometry ) {
  16564. cacheKey += this.getGeometryCacheKey();
  16565. }
  16566. if ( object.skeleton ) {
  16567. cacheKey += object.skeleton.bones.length + ',';
  16568. }
  16569. if ( object.isBatchedMesh ) {
  16570. cacheKey += object._matricesTexture.uuid + ',';
  16571. if ( object._colorsTexture !== null ) {
  16572. cacheKey += object._colorsTexture.uuid + ',';
  16573. }
  16574. }
  16575. if ( object.count > 1 ) {
  16576. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  16577. cacheKey += object.uuid + ',';
  16578. }
  16579. cacheKey += object.receiveShadow + ',';
  16580. return hashString( cacheKey );
  16581. }
  16582. /**
  16583. * Whether the geometry requires an update or not.
  16584. *
  16585. * @type {Boolean}
  16586. * @readonly
  16587. */
  16588. get needsGeometryUpdate() {
  16589. return this.geometry.id !== this.object.geometry.id;
  16590. }
  16591. /**
  16592. * Whether the render object requires an update or not.
  16593. *
  16594. * Note: There are two distinct places where render objects are checked for an update.
  16595. *
  16596. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  16597. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  16598. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  16599. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  16600. * a need for a refresh due to material, geometry or object related value changes.
  16601. *
  16602. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  16603. * that performs the 'needsUpdate' check.
  16604. *
  16605. * @type {Boolean}
  16606. * @readonly
  16607. */
  16608. get needsUpdate() {
  16609. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  16610. }
  16611. /**
  16612. * Returns the dynamic cache key which represents a key that is computed per draw command.
  16613. *
  16614. * @return {Number} The cache key.
  16615. */
  16616. getDynamicCacheKey() {
  16617. let cacheKey = 0;
  16618. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  16619. // the renderer is inside a shadow pass.
  16620. if ( this.material.isShadowPassMaterial !== true ) {
  16621. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  16622. }
  16623. if ( this.object.receiveShadow ) {
  16624. cacheKey += 1;
  16625. }
  16626. return cacheKey;
  16627. }
  16628. /**
  16629. * Returns the render object's cache key.
  16630. *
  16631. * @return {Number} The cache key.
  16632. */
  16633. getCacheKey() {
  16634. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  16635. }
  16636. /**
  16637. * Frees internal resources.
  16638. */
  16639. dispose() {
  16640. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  16641. this.onDispose();
  16642. }
  16643. }
  16644. const _chainKeys$5 = [];
  16645. /**
  16646. * This module manages the render objects of the renderer.
  16647. *
  16648. * @private
  16649. */
  16650. class RenderObjects {
  16651. /**
  16652. * Constructs a new render object management component.
  16653. *
  16654. * @param {Renderer} renderer - The renderer.
  16655. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16656. * @param {Geometries} geometries - Renderer component for managing geometries.
  16657. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  16658. * @param {Bindings} bindings - Renderer component for managing bindings.
  16659. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16660. */
  16661. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  16662. /**
  16663. * The renderer.
  16664. *
  16665. * @type {Renderer}
  16666. */
  16667. this.renderer = renderer;
  16668. /**
  16669. * Renderer component for managing nodes related logic.
  16670. *
  16671. * @type {Nodes}
  16672. */
  16673. this.nodes = nodes;
  16674. /**
  16675. * Renderer component for managing geometries.
  16676. *
  16677. * @type {Geometries}
  16678. */
  16679. this.geometries = geometries;
  16680. /**
  16681. * Renderer component for managing pipelines.
  16682. *
  16683. * @type {Pipelines}
  16684. */
  16685. this.pipelines = pipelines;
  16686. /**
  16687. * Renderer component for managing bindings.
  16688. *
  16689. * @type {Bindings}
  16690. */
  16691. this.bindings = bindings;
  16692. /**
  16693. * Renderer component for managing metrics and monitoring data.
  16694. *
  16695. * @type {Info}
  16696. */
  16697. this.info = info;
  16698. /**
  16699. * A dictionary that manages render contexts in chain maps
  16700. * for each pass ID.
  16701. *
  16702. * @type {Object<String,ChainMap>}
  16703. */
  16704. this.chainMaps = {};
  16705. }
  16706. /**
  16707. * Returns a render object for the given object and state data.
  16708. *
  16709. * @param {Object3D} object - The 3D object.
  16710. * @param {Material} material - The 3D object's material.
  16711. * @param {Scene} scene - The scene the 3D object belongs to.
  16712. * @param {Camera} camera - The camera the 3D object should be rendered with.
  16713. * @param {LightsNode} lightsNode - The lights node.
  16714. * @param {RenderContext} renderContext - The render context.
  16715. * @param {ClippingContext} clippingContext - The clipping context.
  16716. * @param {String?} passId - An optional ID for identifying the pass.
  16717. * @return {RenderObject} The render object.
  16718. */
  16719. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16720. const chainMap = this.getChainMap( passId );
  16721. // reuse chainArray
  16722. _chainKeys$5[ 0 ] = object;
  16723. _chainKeys$5[ 1 ] = material;
  16724. _chainKeys$5[ 2 ] = renderContext;
  16725. _chainKeys$5[ 3 ] = lightsNode;
  16726. let renderObject = chainMap.get( _chainKeys$5 );
  16727. if ( renderObject === undefined ) {
  16728. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16729. chainMap.set( _chainKeys$5, renderObject );
  16730. } else {
  16731. renderObject.updateClipping( clippingContext );
  16732. if ( renderObject.needsGeometryUpdate ) {
  16733. renderObject.setGeometry( object.geometry );
  16734. }
  16735. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  16736. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  16737. renderObject.dispose();
  16738. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16739. } else {
  16740. renderObject.version = material.version;
  16741. }
  16742. }
  16743. }
  16744. _chainKeys$5.length = 0;
  16745. return renderObject;
  16746. }
  16747. /**
  16748. * Returns a chain map for the given pass ID.
  16749. *
  16750. * @param {String} [passId='default'] - The pass ID.
  16751. * @return {ChainMap} The chain map.
  16752. */
  16753. getChainMap( passId = 'default' ) {
  16754. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  16755. }
  16756. /**
  16757. * Frees internal resources.
  16758. */
  16759. dispose() {
  16760. this.chainMaps = {};
  16761. }
  16762. /**
  16763. * Factory method for creating render objects with the given list of parameters.
  16764. *
  16765. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16766. * @param {Geometries} geometries - Renderer component for managing geometries.
  16767. * @param {Renderer} renderer - The renderer.
  16768. * @param {Object3D} object - The 3D object.
  16769. * @param {Material} material - The object's material.
  16770. * @param {Scene} scene - The scene the 3D object belongs to.
  16771. * @param {Camera} camera - The camera the object should be rendered with.
  16772. * @param {LightsNode} lightsNode - The lights node.
  16773. * @param {RenderContext} renderContext - The render context.
  16774. * @param {ClippingContext} clippingContext - The clipping context.
  16775. * @param {String?} passId - An optional ID for identifying the pass.
  16776. * @return {RenderObject} The render object.
  16777. */
  16778. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16779. const chainMap = this.getChainMap( passId );
  16780. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  16781. renderObject.onDispose = () => {
  16782. this.pipelines.delete( renderObject );
  16783. this.bindings.delete( renderObject );
  16784. this.nodes.delete( renderObject );
  16785. chainMap.delete( renderObject.getChainArray() );
  16786. };
  16787. return renderObject;
  16788. }
  16789. }
  16790. /**
  16791. * Data structure for the renderer. It is intended to manage
  16792. * data of objects in dictionaries.
  16793. *
  16794. * @private
  16795. */
  16796. class DataMap {
  16797. /**
  16798. * Constructs a new data map.
  16799. */
  16800. constructor() {
  16801. /**
  16802. * `DataMap` internally uses a weak map
  16803. * to manage its data.
  16804. *
  16805. * @type {WeakMap}
  16806. */
  16807. this.data = new WeakMap();
  16808. }
  16809. /**
  16810. * Returns the dictionary for the given object.
  16811. *
  16812. * @param {Object} object - The object.
  16813. * @return {Object} The dictionary.
  16814. */
  16815. get( object ) {
  16816. let map = this.data.get( object );
  16817. if ( map === undefined ) {
  16818. map = {};
  16819. this.data.set( object, map );
  16820. }
  16821. return map;
  16822. }
  16823. /**
  16824. * Deletes the dictionary for the given object.
  16825. *
  16826. * @param {Object} object - The object.
  16827. * @return {Object?} The deleted dictionary.
  16828. */
  16829. delete( object ) {
  16830. let map = null;
  16831. if ( this.data.has( object ) ) {
  16832. map = this.data.get( object );
  16833. this.data.delete( object );
  16834. }
  16835. return map;
  16836. }
  16837. /**
  16838. * Returns `true` if the given object has a dictionary defined.
  16839. *
  16840. * @param {Object} object - The object to test.
  16841. * @return {Boolean} Whether a dictionary is defined or not.
  16842. */
  16843. has( object ) {
  16844. return this.data.has( object );
  16845. }
  16846. /**
  16847. * Frees internal resources.
  16848. */
  16849. dispose() {
  16850. this.data = new WeakMap();
  16851. }
  16852. }
  16853. const AttributeType = {
  16854. VERTEX: 1,
  16855. INDEX: 2,
  16856. STORAGE: 3,
  16857. INDIRECT: 4
  16858. };
  16859. // size of a chunk in bytes (STD140 layout)
  16860. const GPU_CHUNK_BYTES = 16;
  16861. // @TODO: Move to src/constants.js
  16862. const BlendColorFactor = 211;
  16863. const OneMinusBlendColorFactor = 212;
  16864. /**
  16865. * This renderer module manages geometry attributes.
  16866. *
  16867. * @private
  16868. * @augments DataMap
  16869. */
  16870. class Attributes extends DataMap {
  16871. /**
  16872. * Constructs a new attribute management component.
  16873. *
  16874. * @param {Backend} backend - The renderer's backend.
  16875. */
  16876. constructor( backend ) {
  16877. super();
  16878. /**
  16879. * The renderer's backend.
  16880. *
  16881. * @type {Backend}
  16882. */
  16883. this.backend = backend;
  16884. }
  16885. /**
  16886. * Deletes the data for the given attribute.
  16887. *
  16888. * @param {BufferAttribute} attribute - The attribute.
  16889. * @return {Object} The deleted attribute data.
  16890. */
  16891. delete( attribute ) {
  16892. const attributeData = super.delete( attribute );
  16893. if ( attributeData !== undefined ) {
  16894. this.backend.destroyAttribute( attribute );
  16895. }
  16896. return attributeData;
  16897. }
  16898. /**
  16899. * Updates the given attribute. This method creates attribute buffers
  16900. * for new attributes and updates data for existing ones.
  16901. *
  16902. * @param {BufferAttribute} attribute - The attribute to update.
  16903. * @param {Number} type - The attribute type.
  16904. */
  16905. update( attribute, type ) {
  16906. const data = this.get( attribute );
  16907. if ( data.version === undefined ) {
  16908. if ( type === AttributeType.VERTEX ) {
  16909. this.backend.createAttribute( attribute );
  16910. } else if ( type === AttributeType.INDEX ) {
  16911. this.backend.createIndexAttribute( attribute );
  16912. } else if ( type === AttributeType.STORAGE ) {
  16913. this.backend.createStorageAttribute( attribute );
  16914. } else if ( type === AttributeType.INDIRECT ) {
  16915. this.backend.createIndirectStorageAttribute( attribute );
  16916. }
  16917. data.version = this._getBufferAttribute( attribute ).version;
  16918. } else {
  16919. const bufferAttribute = this._getBufferAttribute( attribute );
  16920. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  16921. this.backend.updateAttribute( attribute );
  16922. data.version = bufferAttribute.version;
  16923. }
  16924. }
  16925. }
  16926. /**
  16927. * Utility method for handling interleaved buffer attributes correctly.
  16928. * To process them, their `InterleavedBuffer` is returned.
  16929. *
  16930. * @param {BufferAttribute} attribute - The attribute.
  16931. * @return {BufferAttribute|InterleavedBuffer}
  16932. */
  16933. _getBufferAttribute( attribute ) {
  16934. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  16935. return attribute;
  16936. }
  16937. }
  16938. /**
  16939. * Returns `true` if the given array has values that require an Uint32 array type.
  16940. *
  16941. * @private
  16942. * @function
  16943. * @param {Array<Number>} array - The array to test.
  16944. * @return {Boolean} Whether the given array has values that require an Uint32 array type or not.
  16945. */
  16946. function arrayNeedsUint32( array ) {
  16947. // assumes larger values usually on last
  16948. for ( let i = array.length - 1; i >= 0; -- i ) {
  16949. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  16950. }
  16951. return false;
  16952. }
  16953. /**
  16954. * Returns the wireframe version for the given geometry.
  16955. *
  16956. * @private
  16957. * @function
  16958. * @param {BufferGeometry} geometry - The geometry.
  16959. * @return {Number} The version.
  16960. */
  16961. function getWireframeVersion( geometry ) {
  16962. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  16963. }
  16964. /**
  16965. * Returns a wireframe index attribute for the given geometry.
  16966. *
  16967. * @private
  16968. * @function
  16969. * @param {BufferGeometry} geometry - The geometry.
  16970. * @return {BufferAttribute} The wireframe index attribute.
  16971. */
  16972. function getWireframeIndex( geometry ) {
  16973. const indices = [];
  16974. const geometryIndex = geometry.index;
  16975. const geometryPosition = geometry.attributes.position;
  16976. if ( geometryIndex !== null ) {
  16977. const array = geometryIndex.array;
  16978. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  16979. const a = array[ i + 0 ];
  16980. const b = array[ i + 1 ];
  16981. const c = array[ i + 2 ];
  16982. indices.push( a, b, b, c, c, a );
  16983. }
  16984. } else {
  16985. const array = geometryPosition.array;
  16986. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  16987. const a = i + 0;
  16988. const b = i + 1;
  16989. const c = i + 2;
  16990. indices.push( a, b, b, c, c, a );
  16991. }
  16992. }
  16993. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  16994. attribute.version = getWireframeVersion( geometry );
  16995. return attribute;
  16996. }
  16997. /**
  16998. * This renderer module manages geometries.
  16999. *
  17000. * @private
  17001. * @augments DataMap
  17002. */
  17003. class Geometries extends DataMap {
  17004. /**
  17005. * Constructs a new geometry management component.
  17006. *
  17007. * @param {Attributes} attributes - Renderer component for managing attributes.
  17008. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17009. */
  17010. constructor( attributes, info ) {
  17011. super();
  17012. /**
  17013. * Renderer component for managing attributes.
  17014. *
  17015. * @type {Attributes}
  17016. */
  17017. this.attributes = attributes;
  17018. /**
  17019. * Renderer component for managing metrics and monitoring data.
  17020. *
  17021. * @type {Info}
  17022. */
  17023. this.info = info;
  17024. /**
  17025. * Weak Map for managing attributes for wireframe rendering.
  17026. *
  17027. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  17028. */
  17029. this.wireframes = new WeakMap();
  17030. /**
  17031. * This Weak Map is used to make sure buffer attributes are
  17032. * updated only once per render call.
  17033. *
  17034. * @type {WeakMap<BufferAttribute,Number>}
  17035. */
  17036. this.attributeCall = new WeakMap();
  17037. }
  17038. /**
  17039. * Returns `true` if the given render object has an initialized geometry.
  17040. *
  17041. * @param {RenderObject} renderObject - The render object.
  17042. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  17043. */
  17044. has( renderObject ) {
  17045. const geometry = renderObject.geometry;
  17046. return super.has( geometry ) && this.get( geometry ).initialized === true;
  17047. }
  17048. /**
  17049. * Prepares the geometry of the given render object for rendering.
  17050. *
  17051. * @param {RenderObject} renderObject - The render object.
  17052. */
  17053. updateForRender( renderObject ) {
  17054. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  17055. this.updateAttributes( renderObject );
  17056. }
  17057. /**
  17058. * Initializes the geometry of the given render object.
  17059. *
  17060. * @param {RenderObject} renderObject - The render object.
  17061. */
  17062. initGeometry( renderObject ) {
  17063. const geometry = renderObject.geometry;
  17064. const geometryData = this.get( geometry );
  17065. geometryData.initialized = true;
  17066. this.info.memory.geometries ++;
  17067. const onDispose = () => {
  17068. this.info.memory.geometries --;
  17069. const index = geometry.index;
  17070. const geometryAttributes = renderObject.getAttributes();
  17071. if ( index !== null ) {
  17072. this.attributes.delete( index );
  17073. }
  17074. for ( const geometryAttribute of geometryAttributes ) {
  17075. this.attributes.delete( geometryAttribute );
  17076. }
  17077. const wireframeAttribute = this.wireframes.get( geometry );
  17078. if ( wireframeAttribute !== undefined ) {
  17079. this.attributes.delete( wireframeAttribute );
  17080. }
  17081. geometry.removeEventListener( 'dispose', onDispose );
  17082. };
  17083. geometry.addEventListener( 'dispose', onDispose );
  17084. }
  17085. /**
  17086. * Updates the geometry attributes of the given render object.
  17087. *
  17088. * @param {RenderObject} renderObject - The render object.
  17089. */
  17090. updateAttributes( renderObject ) {
  17091. // attributes
  17092. const attributes = renderObject.getAttributes();
  17093. for ( const attribute of attributes ) {
  17094. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  17095. this.updateAttribute( attribute, AttributeType.STORAGE );
  17096. } else {
  17097. this.updateAttribute( attribute, AttributeType.VERTEX );
  17098. }
  17099. }
  17100. // indexes
  17101. const index = this.getIndex( renderObject );
  17102. if ( index !== null ) {
  17103. this.updateAttribute( index, AttributeType.INDEX );
  17104. }
  17105. // indirect
  17106. const indirect = renderObject.geometry.indirect;
  17107. if ( indirect !== null ) {
  17108. this.updateAttribute( indirect, AttributeType.INDIRECT );
  17109. }
  17110. }
  17111. /**
  17112. * Updates the given attribute.
  17113. *
  17114. * @param {BufferAttribute} attribute - The attribute to update.
  17115. * @param {Number} type - The attribute type.
  17116. */
  17117. updateAttribute( attribute, type ) {
  17118. const callId = this.info.render.calls;
  17119. if ( ! attribute.isInterleavedBufferAttribute ) {
  17120. if ( this.attributeCall.get( attribute ) !== callId ) {
  17121. this.attributes.update( attribute, type );
  17122. this.attributeCall.set( attribute, callId );
  17123. }
  17124. } else {
  17125. if ( this.attributeCall.get( attribute ) === undefined ) {
  17126. this.attributes.update( attribute, type );
  17127. this.attributeCall.set( attribute, callId );
  17128. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  17129. this.attributes.update( attribute, type );
  17130. this.attributeCall.set( attribute.data, callId );
  17131. this.attributeCall.set( attribute, callId );
  17132. }
  17133. }
  17134. }
  17135. /**
  17136. * Returns the indirect buffer attribute of the given render object.
  17137. *
  17138. * @param {RenderObject} renderObject - The render object.
  17139. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  17140. */
  17141. getIndirect( renderObject ) {
  17142. return renderObject.geometry.indirect;
  17143. }
  17144. /**
  17145. * Returns the index of the given render object's geometry. This is implemented
  17146. * in a method to return a wireframe index if necessary.
  17147. *
  17148. * @param {RenderObject} renderObject - The render object.
  17149. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  17150. */
  17151. getIndex( renderObject ) {
  17152. const { geometry, material } = renderObject;
  17153. let index = geometry.index;
  17154. if ( material.wireframe === true ) {
  17155. const wireframes = this.wireframes;
  17156. let wireframeAttribute = wireframes.get( geometry );
  17157. if ( wireframeAttribute === undefined ) {
  17158. wireframeAttribute = getWireframeIndex( geometry );
  17159. wireframes.set( geometry, wireframeAttribute );
  17160. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  17161. this.attributes.delete( wireframeAttribute );
  17162. wireframeAttribute = getWireframeIndex( geometry );
  17163. wireframes.set( geometry, wireframeAttribute );
  17164. }
  17165. index = wireframeAttribute;
  17166. }
  17167. return index;
  17168. }
  17169. }
  17170. /**
  17171. * This renderer module provides a series of statistical information
  17172. * about the GPU memory and the rendering process. Useful for debugging
  17173. * and monitoring.
  17174. */
  17175. class Info {
  17176. /**
  17177. * Constructs a new info component.
  17178. */
  17179. constructor() {
  17180. /**
  17181. * Whether frame related metrics should automatically
  17182. * be resetted or not. This property should be set to `false`
  17183. * by apps which manage their own animation loop. They must
  17184. * then call `renderer.info.reset()` once per frame manually.
  17185. *
  17186. * @type {Boolean}
  17187. * @default true
  17188. */
  17189. this.autoReset = true;
  17190. /**
  17191. * The current frame ID. This ID is managed
  17192. * by `NodeFrame`.
  17193. *
  17194. * @type {Number}
  17195. * @readonly
  17196. * @default 0
  17197. */
  17198. this.frame = 0;
  17199. /**
  17200. * The number of render calls since the
  17201. * app has been started.
  17202. *
  17203. * @type {Number}
  17204. * @readonly
  17205. * @default 0
  17206. */
  17207. this.calls = 0;
  17208. /**
  17209. * Render related metrics.
  17210. *
  17211. * @type {Object}
  17212. * @readonly
  17213. * @property {Number} calls - The number of render calls since the app has been started.
  17214. * @property {Number} frameCalls - The number of render calls of the current frame.
  17215. * @property {Number} drawCalls - The number of draw calls of the current frame.
  17216. * @property {Number} triangles - The number of rendered triangle primitives of the current frame.
  17217. * @property {Number} points - The number of rendered point primitives of the current frame.
  17218. * @property {Number} lines - The number of rendered line primitives of the current frame.
  17219. * @property {Number} previousFrameCalls - The number of render calls of the previous frame.
  17220. * @property {Number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  17221. * @property {Number} timestampCalls - The number of render calls using `renderer.renderAsync()`.
  17222. */
  17223. this.render = {
  17224. calls: 0,
  17225. frameCalls: 0,
  17226. drawCalls: 0,
  17227. triangles: 0,
  17228. points: 0,
  17229. lines: 0,
  17230. timestamp: 0,
  17231. previousFrameCalls: 0,
  17232. timestampCalls: 0
  17233. };
  17234. /**
  17235. * Compute related metrics.
  17236. *
  17237. * @type {Object}
  17238. * @readonly
  17239. * @property {Number} calls - The number of compute calls since the app has been started.
  17240. * @property {Number} frameCalls - The number of compute calls of the current frame.
  17241. * @property {Number} previousFrameCalls - The number of compute calls of the previous frame.
  17242. * @property {Number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  17243. * @property {Number} timestampCalls - The number of render calls using `renderer.computeAsync()`.
  17244. */
  17245. this.compute = {
  17246. calls: 0,
  17247. frameCalls: 0,
  17248. timestamp: 0,
  17249. previousFrameCalls: 0,
  17250. timestampCalls: 0
  17251. };
  17252. /**
  17253. * Memory related metrics.
  17254. *
  17255. * @type {Object}
  17256. * @readonly
  17257. * @property {Number} geometries - The number of active geometries.
  17258. * @property {Number} frameCalls - The number of active textures.
  17259. */
  17260. this.memory = {
  17261. geometries: 0,
  17262. textures: 0
  17263. };
  17264. }
  17265. /**
  17266. * This method should be executed per draw call and updates the corresponding metrics.
  17267. *
  17268. * @param {Object3D} object - The 3D object that is going to be rendered.
  17269. * @param {Number} count - The vertex or index count.
  17270. * @param {Number} instanceCount - The instance count.
  17271. */
  17272. update( object, count, instanceCount ) {
  17273. this.render.drawCalls ++;
  17274. if ( object.isMesh || object.isSprite ) {
  17275. this.render.triangles += instanceCount * ( count / 3 );
  17276. } else if ( object.isPoints ) {
  17277. this.render.points += instanceCount * count;
  17278. } else if ( object.isLineSegments ) {
  17279. this.render.lines += instanceCount * ( count / 2 );
  17280. } else if ( object.isLine ) {
  17281. this.render.lines += instanceCount * ( count - 1 );
  17282. } else {
  17283. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  17284. }
  17285. }
  17286. /**
  17287. * Used by async render methods to updated timestamp metrics.
  17288. *
  17289. * @param {('render'|'compute')} type - The type of render call.
  17290. * @param {Number} time - The duration of the compute/render call in milliseconds.
  17291. */
  17292. updateTimestamp( type, time ) {
  17293. if ( this[ type ].timestampCalls === 0 ) {
  17294. this[ type ].timestamp = 0;
  17295. }
  17296. this[ type ].timestamp += time;
  17297. this[ type ].timestampCalls ++;
  17298. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  17299. this[ type ].timestampCalls = 0;
  17300. }
  17301. }
  17302. /**
  17303. * Resets frame related metrics.
  17304. */
  17305. reset() {
  17306. const previousRenderFrameCalls = this.render.frameCalls;
  17307. this.render.previousFrameCalls = previousRenderFrameCalls;
  17308. const previousComputeFrameCalls = this.compute.frameCalls;
  17309. this.compute.previousFrameCalls = previousComputeFrameCalls;
  17310. this.render.drawCalls = 0;
  17311. this.render.frameCalls = 0;
  17312. this.compute.frameCalls = 0;
  17313. this.render.triangles = 0;
  17314. this.render.points = 0;
  17315. this.render.lines = 0;
  17316. }
  17317. /**
  17318. * Performs a complete reset of the object.
  17319. */
  17320. dispose() {
  17321. this.reset();
  17322. this.calls = 0;
  17323. this.render.calls = 0;
  17324. this.compute.calls = 0;
  17325. this.render.timestamp = 0;
  17326. this.compute.timestamp = 0;
  17327. this.memory.geometries = 0;
  17328. this.memory.textures = 0;
  17329. }
  17330. }
  17331. /**
  17332. * Abstract class for representing pipelines.
  17333. *
  17334. * @private
  17335. * @abstract
  17336. */
  17337. class Pipeline {
  17338. /**
  17339. * Constructs a new pipeline.
  17340. *
  17341. * @param {String} cacheKey - The pipeline's cache key.
  17342. */
  17343. constructor( cacheKey ) {
  17344. /**
  17345. * The pipeline's cache key.
  17346. *
  17347. * @type {String}
  17348. */
  17349. this.cacheKey = cacheKey;
  17350. /**
  17351. * How often the pipeline is currently in use.
  17352. *
  17353. * @type {Number}
  17354. * @default 0
  17355. */
  17356. this.usedTimes = 0;
  17357. }
  17358. }
  17359. /**
  17360. * Class for representing render pipelines.
  17361. *
  17362. * @private
  17363. * @augments Pipeline
  17364. */
  17365. class RenderPipeline extends Pipeline {
  17366. /**
  17367. * Constructs a new render pipeline.
  17368. *
  17369. * @param {String} cacheKey - The pipeline's cache key.
  17370. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  17371. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  17372. */
  17373. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  17374. super( cacheKey );
  17375. /**
  17376. * The pipeline's vertex shader.
  17377. *
  17378. * @type {ProgrammableStage}
  17379. */
  17380. this.vertexProgram = vertexProgram;
  17381. /**
  17382. * The pipeline's fragment shader.
  17383. *
  17384. * @type {ProgrammableStage}
  17385. */
  17386. this.fragmentProgram = fragmentProgram;
  17387. }
  17388. }
  17389. /**
  17390. * Class for representing compute pipelines.
  17391. *
  17392. * @private
  17393. * @augments Pipeline
  17394. */
  17395. class ComputePipeline extends Pipeline {
  17396. /**
  17397. * Constructs a new render pipeline.
  17398. *
  17399. * @param {String} cacheKey - The pipeline's cache key.
  17400. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  17401. */
  17402. constructor( cacheKey, computeProgram ) {
  17403. super( cacheKey );
  17404. /**
  17405. * The pipeline's compute shader.
  17406. *
  17407. * @type {ProgrammableStage}
  17408. */
  17409. this.computeProgram = computeProgram;
  17410. /**
  17411. * This flag can be used for type testing.
  17412. *
  17413. * @type {Boolean}
  17414. * @readonly
  17415. * @default true
  17416. */
  17417. this.isComputePipeline = true;
  17418. }
  17419. }
  17420. let _id$8 = 0;
  17421. /**
  17422. * Class for representing programmable stages which are vertex,
  17423. * fragment or compute shaders. Unlike fixed-function states (like blending),
  17424. * they represent the programmable part of a pipeline.
  17425. *
  17426. * @private
  17427. */
  17428. class ProgrammableStage {
  17429. /**
  17430. * Constructs a new programmable stage.
  17431. *
  17432. * @param {String} code - The shader code.
  17433. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  17434. * @param {String} name - The name of the shader.
  17435. * @param {Array<Object>?} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17436. * @param {Array<Object>?} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17437. */
  17438. constructor( code, stage, name, transforms = null, attributes = null ) {
  17439. /**
  17440. * The id of the programmable stage.
  17441. *
  17442. * @type {Number}
  17443. */
  17444. this.id = _id$8 ++;
  17445. /**
  17446. * The shader code.
  17447. *
  17448. * @type {String}
  17449. */
  17450. this.code = code;
  17451. /**
  17452. * The type of stage.
  17453. *
  17454. * @type {String}
  17455. */
  17456. this.stage = stage;
  17457. /**
  17458. * The name of the stage.
  17459. * This is used for debugging purposes.
  17460. *
  17461. * @type {String}
  17462. */
  17463. this.name = name;
  17464. /**
  17465. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17466. *
  17467. * @type {Array<Object>?}
  17468. */
  17469. this.transforms = transforms;
  17470. /**
  17471. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17472. *
  17473. * @type {Array<Object>?}
  17474. */
  17475. this.attributes = attributes;
  17476. /**
  17477. * How often the programmable stage is currently in use.
  17478. *
  17479. * @type {Number}
  17480. * @default 0
  17481. */
  17482. this.usedTimes = 0;
  17483. }
  17484. }
  17485. /**
  17486. * This renderer module manages the pipelines of the renderer.
  17487. *
  17488. * @private
  17489. * @augments DataMap
  17490. */
  17491. class Pipelines extends DataMap {
  17492. /**
  17493. * Constructs a new pipeline management component.
  17494. *
  17495. * @param {Backend} backend - The renderer's backend.
  17496. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17497. */
  17498. constructor( backend, nodes ) {
  17499. super();
  17500. /**
  17501. * The renderer's backend.
  17502. *
  17503. * @type {Backend}
  17504. */
  17505. this.backend = backend;
  17506. /**
  17507. * Renderer component for managing nodes related logic.
  17508. *
  17509. * @type {Nodes}
  17510. */
  17511. this.nodes = nodes;
  17512. /**
  17513. * A references to the bindings management component.
  17514. * This reference will be set inside the `Bindings`
  17515. * constructor.
  17516. *
  17517. * @type {Bindings?}
  17518. * @default null
  17519. */
  17520. this.bindings = null;
  17521. /**
  17522. * Internal cache for maintaining pipelines.
  17523. * The key of the map is a cache key, the value the pipeline.
  17524. *
  17525. * @type {Map<String,Pipeline>}
  17526. */
  17527. this.caches = new Map();
  17528. /**
  17529. * This dictionary maintains for each shader stage type (vertex,
  17530. * fragment and compute) the programmable stage objects which
  17531. * represent the actual shader code.
  17532. *
  17533. * @type {Object<String,Map>}
  17534. */
  17535. this.programs = {
  17536. vertex: new Map(),
  17537. fragment: new Map(),
  17538. compute: new Map()
  17539. };
  17540. }
  17541. /**
  17542. * Returns a compute pipeline for the given compute node.
  17543. *
  17544. * @param {Node} computeNode - The compute node.
  17545. * @param {Array<BindGroup>} bindings - The bindings.
  17546. * @return {ComputePipeline} The compute pipeline.
  17547. */
  17548. getForCompute( computeNode, bindings ) {
  17549. const { backend } = this;
  17550. const data = this.get( computeNode );
  17551. if ( this._needsComputeUpdate( computeNode ) ) {
  17552. const previousPipeline = data.pipeline;
  17553. if ( previousPipeline ) {
  17554. previousPipeline.usedTimes --;
  17555. previousPipeline.computeProgram.usedTimes --;
  17556. }
  17557. // get shader
  17558. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  17559. // programmable stage
  17560. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  17561. if ( stageCompute === undefined ) {
  17562. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  17563. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  17564. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  17565. backend.createProgram( stageCompute );
  17566. }
  17567. // determine compute pipeline
  17568. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  17569. let pipeline = this.caches.get( cacheKey );
  17570. if ( pipeline === undefined ) {
  17571. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17572. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  17573. }
  17574. // keep track of all used times
  17575. pipeline.usedTimes ++;
  17576. stageCompute.usedTimes ++;
  17577. //
  17578. data.version = computeNode.version;
  17579. data.pipeline = pipeline;
  17580. }
  17581. return data.pipeline;
  17582. }
  17583. /**
  17584. * Returns a render pipeline for the given render object.
  17585. *
  17586. * @param {RenderObject} renderObject - The render object.
  17587. * @param {Array<Promise>?} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17588. * @return {RenderPipeline} The render pipeline.
  17589. */
  17590. getForRender( renderObject, promises = null ) {
  17591. const { backend } = this;
  17592. const data = this.get( renderObject );
  17593. if ( this._needsRenderUpdate( renderObject ) ) {
  17594. const previousPipeline = data.pipeline;
  17595. if ( previousPipeline ) {
  17596. previousPipeline.usedTimes --;
  17597. previousPipeline.vertexProgram.usedTimes --;
  17598. previousPipeline.fragmentProgram.usedTimes --;
  17599. }
  17600. // get shader
  17601. const nodeBuilderState = renderObject.getNodeBuilderState();
  17602. const name = renderObject.material ? renderObject.material.name : '';
  17603. // programmable stages
  17604. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  17605. if ( stageVertex === undefined ) {
  17606. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  17607. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  17608. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  17609. backend.createProgram( stageVertex );
  17610. }
  17611. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  17612. if ( stageFragment === undefined ) {
  17613. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  17614. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  17615. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  17616. backend.createProgram( stageFragment );
  17617. }
  17618. // determine render pipeline
  17619. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17620. let pipeline = this.caches.get( cacheKey );
  17621. if ( pipeline === undefined ) {
  17622. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17623. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  17624. } else {
  17625. renderObject.pipeline = pipeline;
  17626. }
  17627. // keep track of all used times
  17628. pipeline.usedTimes ++;
  17629. stageVertex.usedTimes ++;
  17630. stageFragment.usedTimes ++;
  17631. //
  17632. data.pipeline = pipeline;
  17633. }
  17634. return data.pipeline;
  17635. }
  17636. /**
  17637. * Deletes the pipeline for the given render object.
  17638. *
  17639. * @param {RenderObject} object - The render object.
  17640. * @return {Object?} The deleted dictionary.
  17641. */
  17642. delete( object ) {
  17643. const pipeline = this.get( object ).pipeline;
  17644. if ( pipeline ) {
  17645. // pipeline
  17646. pipeline.usedTimes --;
  17647. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  17648. // programs
  17649. if ( pipeline.isComputePipeline ) {
  17650. pipeline.computeProgram.usedTimes --;
  17651. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  17652. } else {
  17653. pipeline.fragmentProgram.usedTimes --;
  17654. pipeline.vertexProgram.usedTimes --;
  17655. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  17656. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  17657. }
  17658. }
  17659. return super.delete( object );
  17660. }
  17661. /**
  17662. * Frees internal resources.
  17663. */
  17664. dispose() {
  17665. super.dispose();
  17666. this.caches = new Map();
  17667. this.programs = {
  17668. vertex: new Map(),
  17669. fragment: new Map(),
  17670. compute: new Map()
  17671. };
  17672. }
  17673. /**
  17674. * Updates the pipeline for the given render object.
  17675. *
  17676. * @param {RenderObject} renderObject - The render object.
  17677. */
  17678. updateForRender( renderObject ) {
  17679. this.getForRender( renderObject );
  17680. }
  17681. /**
  17682. * Returns a compute pipeline for the given parameters.
  17683. *
  17684. * @private
  17685. * @param {Node} computeNode - The compute node.
  17686. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17687. * @param {String} cacheKey - The cache key.
  17688. * @param {Array<BindGroup>} bindings - The bindings.
  17689. * @return {ComputePipeline} The compute pipeline.
  17690. */
  17691. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  17692. // check for existing pipeline
  17693. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  17694. let pipeline = this.caches.get( cacheKey );
  17695. if ( pipeline === undefined ) {
  17696. pipeline = new ComputePipeline( cacheKey, stageCompute );
  17697. this.caches.set( cacheKey, pipeline );
  17698. this.backend.createComputePipeline( pipeline, bindings );
  17699. }
  17700. return pipeline;
  17701. }
  17702. /**
  17703. * Returns a render pipeline for the given parameters.
  17704. *
  17705. * @private
  17706. * @param {RenderObject} renderObject - The render object.
  17707. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17708. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17709. * @param {String} cacheKey - The cache key.
  17710. * @param {Array<Promise>?} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17711. * @return {ComputePipeline} The compute pipeline.
  17712. */
  17713. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  17714. // check for existing pipeline
  17715. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17716. let pipeline = this.caches.get( cacheKey );
  17717. if ( pipeline === undefined ) {
  17718. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  17719. this.caches.set( cacheKey, pipeline );
  17720. renderObject.pipeline = pipeline;
  17721. // The `promises` array is `null` by default and only set to an empty array when
  17722. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  17723. // pending promises that resolve when the render pipelines are ready for rendering.
  17724. this.backend.createRenderPipeline( renderObject, promises );
  17725. }
  17726. return pipeline;
  17727. }
  17728. /**
  17729. * Computes a cache key representing a compute pipeline.
  17730. *
  17731. * @private
  17732. * @param {Node} computeNode - The compute node.
  17733. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17734. * @return {String} The cache key.
  17735. */
  17736. _getComputeCacheKey( computeNode, stageCompute ) {
  17737. return computeNode.id + ',' + stageCompute.id;
  17738. }
  17739. /**
  17740. * Computes a cache key representing a render pipeline.
  17741. *
  17742. * @private
  17743. * @param {RenderObject} renderObject - The render object.
  17744. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17745. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17746. * @return {String} The cache key.
  17747. */
  17748. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  17749. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  17750. }
  17751. /**
  17752. * Releases the given pipeline.
  17753. *
  17754. * @private
  17755. * @param {Pipeline} pipeline - The pipeline to release.
  17756. */
  17757. _releasePipeline( pipeline ) {
  17758. this.caches.delete( pipeline.cacheKey );
  17759. }
  17760. /**
  17761. * Releases the shader program.
  17762. *
  17763. * @private
  17764. * @param {Object} program - The shader program to release.
  17765. */
  17766. _releaseProgram( program ) {
  17767. const code = program.code;
  17768. const stage = program.stage;
  17769. this.programs[ stage ].delete( code );
  17770. }
  17771. /**
  17772. * Returns `true` if the compute pipeline for the given compute node requires an update.
  17773. *
  17774. * @private
  17775. * @param {Node} computeNode - The compute node.
  17776. * @return {Boolean} Whether the compute pipeline for the given compute node requires an update or not.
  17777. */
  17778. _needsComputeUpdate( computeNode ) {
  17779. const data = this.get( computeNode );
  17780. return data.pipeline === undefined || data.version !== computeNode.version;
  17781. }
  17782. /**
  17783. * Returns `true` if the render pipeline for the given render object requires an update.
  17784. *
  17785. * @private
  17786. * @param {RenderObject} renderObject - The render object.
  17787. * @return {Boolean} Whether the render object for the given render object requires an update or not.
  17788. */
  17789. _needsRenderUpdate( renderObject ) {
  17790. const data = this.get( renderObject );
  17791. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  17792. }
  17793. }
  17794. /**
  17795. * This renderer module manages the bindings of the renderer.
  17796. *
  17797. * @private
  17798. * @augments DataMap
  17799. */
  17800. class Bindings extends DataMap {
  17801. /**
  17802. * Constructs a new bindings management component.
  17803. *
  17804. * @param {Backend} backend - The renderer's backend.
  17805. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17806. * @param {Textures} textures - Renderer component for managing textures.
  17807. * @param {Attributes} attributes - Renderer component for managing attributes.
  17808. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17809. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17810. */
  17811. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  17812. super();
  17813. /**
  17814. * The renderer's backend.
  17815. *
  17816. * @type {Backend}
  17817. */
  17818. this.backend = backend;
  17819. /**
  17820. * Renderer component for managing textures.
  17821. *
  17822. * @type {Textures}
  17823. */
  17824. this.textures = textures;
  17825. /**
  17826. * Renderer component for managing pipelines.
  17827. *
  17828. * @type {Pipelines}
  17829. */
  17830. this.pipelines = pipelines;
  17831. /**
  17832. * Renderer component for managing attributes.
  17833. *
  17834. * @type {Attributes}
  17835. */
  17836. this.attributes = attributes;
  17837. /**
  17838. * Renderer component for managing nodes related logic.
  17839. *
  17840. * @type {Nodes}
  17841. */
  17842. this.nodes = nodes;
  17843. /**
  17844. * Renderer component for managing metrics and monitoring data.
  17845. *
  17846. * @type {Info}
  17847. */
  17848. this.info = info;
  17849. this.pipelines.bindings = this; // assign bindings to pipelines
  17850. }
  17851. /**
  17852. * Returns the bind groups for the given render object.
  17853. *
  17854. * @param {RenderObject} renderObject - The render object.
  17855. * @return {Array<BindGroup>} The bind groups.
  17856. */
  17857. getForRender( renderObject ) {
  17858. const bindings = renderObject.getBindings();
  17859. for ( const bindGroup of bindings ) {
  17860. const groupData = this.get( bindGroup );
  17861. if ( groupData.bindGroup === undefined ) {
  17862. // each object defines an array of bindings (ubos, textures, samplers etc.)
  17863. this._init( bindGroup );
  17864. this.backend.createBindings( bindGroup, bindings, 0 );
  17865. groupData.bindGroup = bindGroup;
  17866. }
  17867. }
  17868. return bindings;
  17869. }
  17870. /**
  17871. * Returns the bind groups for the given compute node.
  17872. *
  17873. * @param {Node} computeNode - The compute node.
  17874. * @return {Array<BindGroup>} The bind groups.
  17875. */
  17876. getForCompute( computeNode ) {
  17877. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  17878. for ( const bindGroup of bindings ) {
  17879. const groupData = this.get( bindGroup );
  17880. if ( groupData.bindGroup === undefined ) {
  17881. this._init( bindGroup );
  17882. this.backend.createBindings( bindGroup, bindings, 0 );
  17883. groupData.bindGroup = bindGroup;
  17884. }
  17885. }
  17886. return bindings;
  17887. }
  17888. /**
  17889. * Updates the bindings for the given compute node.
  17890. *
  17891. * @param {Node} computeNode - The compute node.
  17892. */
  17893. updateForCompute( computeNode ) {
  17894. this._updateBindings( this.getForCompute( computeNode ) );
  17895. }
  17896. /**
  17897. * Updates the bindings for the given render object.
  17898. *
  17899. * @param {RenderObject} renderObject - The render object.
  17900. */
  17901. updateForRender( renderObject ) {
  17902. this._updateBindings( this.getForRender( renderObject ) );
  17903. }
  17904. /**
  17905. * Updates the given array of bindings.
  17906. *
  17907. * @param {Array<BindGroup>} bindings - The bind groups.
  17908. */
  17909. _updateBindings( bindings ) {
  17910. for ( const bindGroup of bindings ) {
  17911. this._update( bindGroup, bindings );
  17912. }
  17913. }
  17914. /**
  17915. * Initializes the given bind group.
  17916. *
  17917. * @param {BindGroup} bindGroup - The bind group to initialize.
  17918. */
  17919. _init( bindGroup ) {
  17920. for ( const binding of bindGroup.bindings ) {
  17921. if ( binding.isSampledTexture ) {
  17922. this.textures.updateTexture( binding.texture );
  17923. } else if ( binding.isStorageBuffer ) {
  17924. const attribute = binding.attribute;
  17925. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  17926. this.attributes.update( attribute, attributeType );
  17927. }
  17928. }
  17929. }
  17930. /**
  17931. * Updates the given bind group.
  17932. *
  17933. * @param {BindGroup} bindGroup - The bind group to update.
  17934. * @param {Array<BindGroup>} bindings - The bind groups.
  17935. */
  17936. _update( bindGroup, bindings ) {
  17937. const { backend } = this;
  17938. let needsBindingsUpdate = false;
  17939. let cacheBindings = true;
  17940. let cacheIndex = 0;
  17941. let version = 0;
  17942. // iterate over all bindings and check if buffer updates or a new binding group is required
  17943. for ( const binding of bindGroup.bindings ) {
  17944. if ( binding.isNodeUniformsGroup ) {
  17945. const updated = this.nodes.updateGroup( binding );
  17946. // every uniforms group is a uniform buffer. So if no update is required,
  17947. // we move one with the next binding. Otherwise the next if block will update the group.
  17948. if ( updated === false ) continue;
  17949. }
  17950. if ( binding.isUniformBuffer ) {
  17951. const updated = binding.update();
  17952. if ( updated ) {
  17953. backend.updateBinding( binding );
  17954. }
  17955. } else if ( binding.isSampler ) {
  17956. binding.update();
  17957. } else if ( binding.isSampledTexture ) {
  17958. const texturesTextureData = this.textures.get( binding.texture );
  17959. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  17960. const updated = binding.update();
  17961. const texture = binding.texture;
  17962. if ( updated ) {
  17963. this.textures.updateTexture( texture );
  17964. }
  17965. const textureData = backend.get( texture );
  17966. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  17967. cacheBindings = false;
  17968. } else {
  17969. cacheIndex = cacheIndex * 10 + texture.id;
  17970. version += texture.version;
  17971. }
  17972. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  17973. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  17974. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  17975. this.textures.updateTexture( texture );
  17976. needsBindingsUpdate = true;
  17977. }
  17978. if ( texture.isStorageTexture === true ) {
  17979. const textureData = this.get( texture );
  17980. if ( binding.store === true ) {
  17981. textureData.needsMipmap = true;
  17982. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  17983. this.backend.generateMipmaps( texture );
  17984. textureData.needsMipmap = false;
  17985. }
  17986. }
  17987. }
  17988. }
  17989. if ( needsBindingsUpdate === true ) {
  17990. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  17991. }
  17992. }
  17993. }
  17994. /**
  17995. * Default sorting function for opaque render items.
  17996. *
  17997. * @private
  17998. * @function
  17999. * @param {Object} a - The first render item.
  18000. * @param {Object} b - The second render item.
  18001. * @return {Number} A numeric value which defines the sort order.
  18002. */
  18003. function painterSortStable( a, b ) {
  18004. if ( a.groupOrder !== b.groupOrder ) {
  18005. return a.groupOrder - b.groupOrder;
  18006. } else if ( a.renderOrder !== b.renderOrder ) {
  18007. return a.renderOrder - b.renderOrder;
  18008. } else if ( a.material.id !== b.material.id ) {
  18009. return a.material.id - b.material.id;
  18010. } else if ( a.z !== b.z ) {
  18011. return a.z - b.z;
  18012. } else {
  18013. return a.id - b.id;
  18014. }
  18015. }
  18016. /**
  18017. * Default sorting function for transparent render items.
  18018. *
  18019. * @private
  18020. * @function
  18021. * @param {Object} a - The first render item.
  18022. * @param {Object} b - The second render item.
  18023. * @return {Number} A numeric value which defines the sort order.
  18024. */
  18025. function reversePainterSortStable( a, b ) {
  18026. if ( a.groupOrder !== b.groupOrder ) {
  18027. return a.groupOrder - b.groupOrder;
  18028. } else if ( a.renderOrder !== b.renderOrder ) {
  18029. return a.renderOrder - b.renderOrder;
  18030. } else if ( a.z !== b.z ) {
  18031. return b.z - a.z;
  18032. } else {
  18033. return a.id - b.id;
  18034. }
  18035. }
  18036. /**
  18037. * Returns `true` if the given transparent material requires a double pass.
  18038. *
  18039. * @private
  18040. * @function
  18041. * @param {Material} material - The transparent material.
  18042. * @return {Boolean} Whether the given material requires a double pass or not.
  18043. */
  18044. function needsDoublePass( material ) {
  18045. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  18046. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  18047. }
  18048. /**
  18049. * When the renderer analyzes the scene at the beginning of a render call,
  18050. * it stores 3D object for further processing in render lists. Depending on the
  18051. * properties of a 3D objects (like their transformation or material state), the
  18052. * objects are maintained in ordered lists for the actual rendering.
  18053. *
  18054. * Render lists are unique per scene and camera combination.
  18055. *
  18056. * @private
  18057. * @augments Pipeline
  18058. */
  18059. class RenderList {
  18060. /**
  18061. * Constructs a render list.
  18062. *
  18063. * @param {Lighting} lighting - The lighting management component.
  18064. * @param {Scene} scene - The scene.
  18065. * @param {Camera} camera - The camera the scene is rendered with.
  18066. */
  18067. constructor( lighting, scene, camera ) {
  18068. /**
  18069. * 3D objects are transformed into render items and stored in this array.
  18070. *
  18071. * @type {Array<Object>}
  18072. */
  18073. this.renderItems = [];
  18074. /**
  18075. * The current render items index.
  18076. *
  18077. * @type {Number}
  18078. * @default 0
  18079. */
  18080. this.renderItemsIndex = 0;
  18081. /**
  18082. * A list with opaque render items.
  18083. *
  18084. * @type {Array<Object>}
  18085. */
  18086. this.opaque = [];
  18087. /**
  18088. * A list with transparent render items which require
  18089. * double pass rendering (e.g. transmissive objects).
  18090. *
  18091. * @type {Array<Object>}
  18092. */
  18093. this.transparentDoublePass = [];
  18094. /**
  18095. * A list with transparent render items.
  18096. *
  18097. * @type {Array<Object>}
  18098. */
  18099. this.transparent = [];
  18100. /**
  18101. * A list with transparent render bundle data.
  18102. *
  18103. * @type {Array<Object>}
  18104. */
  18105. this.bundles = [];
  18106. /**
  18107. * The render list's lights node. This node is later
  18108. * relevant for the actual analytical light nodes which
  18109. * compute the scene's lighting in the shader.
  18110. *
  18111. * @type {LightsNode}
  18112. */
  18113. this.lightsNode = lighting.getNode( scene, camera );
  18114. /**
  18115. * The scene's lights stored in an array. This array
  18116. * is used to setup the lights node.
  18117. *
  18118. * @type {Array<Light>}
  18119. */
  18120. this.lightsArray = [];
  18121. /**
  18122. * The scene.
  18123. *
  18124. * @type {Scene}
  18125. */
  18126. this.scene = scene;
  18127. /**
  18128. * The camera the scene is rendered with.
  18129. *
  18130. * @type {Camera}
  18131. */
  18132. this.camera = camera;
  18133. /**
  18134. * How many objects perform occlusion query tests.
  18135. *
  18136. * @type {Number}
  18137. * @default 0
  18138. */
  18139. this.occlusionQueryCount = 0;
  18140. }
  18141. /**
  18142. * This method is called right at the beginning of a render call
  18143. * before the scene is analyzed. It prepares the internal data
  18144. * structures for the upcoming render lists generation.
  18145. *
  18146. * @return {RenderList} A reference to this render list.
  18147. */
  18148. begin() {
  18149. this.renderItemsIndex = 0;
  18150. this.opaque.length = 0;
  18151. this.transparentDoublePass.length = 0;
  18152. this.transparent.length = 0;
  18153. this.bundles.length = 0;
  18154. this.lightsArray.length = 0;
  18155. this.occlusionQueryCount = 0;
  18156. return this;
  18157. }
  18158. /**
  18159. * Returns a render item for the giving render item state. The state is defined
  18160. * by a series of object-related parameters.
  18161. *
  18162. * The method avoids object creation by holding render items and reusing them in
  18163. * subsequent render calls (just with different property values).
  18164. *
  18165. * @param {Object3D} object - The 3D object.
  18166. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18167. * @param {Material} material - The 3D object's material.
  18168. * @param {Number} groupOrder - The current group order.
  18169. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18170. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18171. * @param {ClippingContext} clippingContext - The current clipping context.
  18172. * @return {Object} The render item.
  18173. */
  18174. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18175. let renderItem = this.renderItems[ this.renderItemsIndex ];
  18176. if ( renderItem === undefined ) {
  18177. renderItem = {
  18178. id: object.id,
  18179. object: object,
  18180. geometry: geometry,
  18181. material: material,
  18182. groupOrder: groupOrder,
  18183. renderOrder: object.renderOrder,
  18184. z: z,
  18185. group: group,
  18186. clippingContext: clippingContext
  18187. };
  18188. this.renderItems[ this.renderItemsIndex ] = renderItem;
  18189. } else {
  18190. renderItem.id = object.id;
  18191. renderItem.object = object;
  18192. renderItem.geometry = geometry;
  18193. renderItem.material = material;
  18194. renderItem.groupOrder = groupOrder;
  18195. renderItem.renderOrder = object.renderOrder;
  18196. renderItem.z = z;
  18197. renderItem.group = group;
  18198. renderItem.clippingContext = clippingContext;
  18199. }
  18200. this.renderItemsIndex ++;
  18201. return renderItem;
  18202. }
  18203. /**
  18204. * Pushes the given object as a render item to the internal render lists.
  18205. * The selected lists depend on the object properties.
  18206. *
  18207. * @param {Object3D} object - The 3D object.
  18208. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18209. * @param {Material} material - The 3D object's material.
  18210. * @param {Number} groupOrder - The current group order.
  18211. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18212. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18213. * @param {ClippingContext} clippingContext - The current clipping context.
  18214. */
  18215. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18216. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18217. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  18218. if ( material.transparent === true || material.transmission > 0 ) {
  18219. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  18220. this.transparent.push( renderItem );
  18221. } else {
  18222. this.opaque.push( renderItem );
  18223. }
  18224. }
  18225. /**
  18226. * Inserts the given object as a render item at the start of the internal render lists.
  18227. * The selected lists depend on the object properties.
  18228. *
  18229. * @param {Object3D} object - The 3D object.
  18230. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18231. * @param {Material} material - The 3D object's material.
  18232. * @param {Number} groupOrder - The current group order.
  18233. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18234. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18235. * @param {ClippingContext} clippingContext - The current clipping context.
  18236. */
  18237. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18238. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18239. if ( material.transparent === true || material.transmission > 0 ) {
  18240. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  18241. this.transparent.unshift( renderItem );
  18242. } else {
  18243. this.opaque.unshift( renderItem );
  18244. }
  18245. }
  18246. /**
  18247. * Pushes render bundle group data into the render list.
  18248. *
  18249. * @param {Object} group - Bundle group data.
  18250. */
  18251. pushBundle( group ) {
  18252. this.bundles.push( group );
  18253. }
  18254. /**
  18255. * Pushes a light into the render list.
  18256. *
  18257. * @param {Light} light - The light.
  18258. */
  18259. pushLight( light ) {
  18260. this.lightsArray.push( light );
  18261. }
  18262. /**
  18263. * Sorts the internal render lists.
  18264. *
  18265. * @param {Function} customOpaqueSort - A custom sort function for opaque objects.
  18266. * @param {Function} customTransparentSort - A custom sort function for transparent objects.
  18267. */
  18268. sort( customOpaqueSort, customTransparentSort ) {
  18269. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  18270. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  18271. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  18272. }
  18273. /**
  18274. * This method performs finalizing tasks right after the render lists
  18275. * have been generated.
  18276. */
  18277. finish() {
  18278. // update lights
  18279. this.lightsNode.setLights( this.lightsArray );
  18280. // Clear references from inactive renderItems in the list
  18281. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  18282. const renderItem = this.renderItems[ i ];
  18283. if ( renderItem.id === null ) break;
  18284. renderItem.id = null;
  18285. renderItem.object = null;
  18286. renderItem.geometry = null;
  18287. renderItem.material = null;
  18288. renderItem.groupOrder = null;
  18289. renderItem.renderOrder = null;
  18290. renderItem.z = null;
  18291. renderItem.group = null;
  18292. renderItem.clippingContext = null;
  18293. }
  18294. }
  18295. }
  18296. const _chainKeys$4 = [];
  18297. /**
  18298. * This renderer module manages the render lists which are unique
  18299. * per scene and camera combination.
  18300. *
  18301. * @private
  18302. */
  18303. class RenderLists {
  18304. /**
  18305. * Constructs a render lists management component.
  18306. *
  18307. * @param {Lighting} lighting - The lighting management component.
  18308. */
  18309. constructor( lighting ) {
  18310. /**
  18311. * The lighting management component.
  18312. *
  18313. * @type {Lighting}
  18314. */
  18315. this.lighting = lighting;
  18316. /**
  18317. * The internal chain map which holds the render lists.
  18318. *
  18319. * @type {ChainMap}
  18320. */
  18321. this.lists = new ChainMap();
  18322. }
  18323. /**
  18324. * Returns a render list for the given scene and camera.
  18325. *
  18326. * @param {Scene} scene - The scene.
  18327. * @param {Camera} camera - The camera.
  18328. * @return {RenderList} The render list.
  18329. */
  18330. get( scene, camera ) {
  18331. const lists = this.lists;
  18332. _chainKeys$4[ 0 ] = scene;
  18333. _chainKeys$4[ 1 ] = camera;
  18334. let list = lists.get( _chainKeys$4 );
  18335. if ( list === undefined ) {
  18336. list = new RenderList( this.lighting, scene, camera );
  18337. lists.set( _chainKeys$4, list );
  18338. }
  18339. _chainKeys$4.length = 0;
  18340. return list;
  18341. }
  18342. /**
  18343. * Frees all internal resources.
  18344. */
  18345. dispose() {
  18346. this.lists = new ChainMap();
  18347. }
  18348. }
  18349. let _id$7 = 0;
  18350. /**
  18351. * Any render or compute command is executed in a specific context that defines
  18352. * the state of the renderer and its backend. Typical examples for such context
  18353. * data are the current clear values or data from the active framebuffer. This
  18354. * module is used to represent these contexts as objects.
  18355. *
  18356. * @private
  18357. */
  18358. class RenderContext {
  18359. /**
  18360. * Constructs a new render context.
  18361. */
  18362. constructor() {
  18363. /**
  18364. * The context's ID.
  18365. *
  18366. * @type {Number}
  18367. */
  18368. this.id = _id$7 ++;
  18369. /**
  18370. * Whether the current active framebuffer has a color attachment.
  18371. *
  18372. * @type {Boolean}
  18373. * @default true
  18374. */
  18375. this.color = true;
  18376. /**
  18377. * Whether the color attachment should be cleared or not.
  18378. *
  18379. * @type {Boolean}
  18380. * @default true
  18381. */
  18382. this.clearColor = true;
  18383. /**
  18384. * The clear color value.
  18385. *
  18386. * @type {Object}
  18387. * @default true
  18388. */
  18389. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  18390. /**
  18391. * Whether the current active framebuffer has a depth attachment.
  18392. *
  18393. * @type {Boolean}
  18394. * @default true
  18395. */
  18396. this.depth = true;
  18397. /**
  18398. * Whether the depth attachment should be cleared or not.
  18399. *
  18400. * @type {Boolean}
  18401. * @default true
  18402. */
  18403. this.clearDepth = true;
  18404. /**
  18405. * The clear depth value.
  18406. *
  18407. * @type {Number}
  18408. * @default 1
  18409. */
  18410. this.clearDepthValue = 1;
  18411. /**
  18412. * Whether the current active framebuffer has a stencil attachment.
  18413. *
  18414. * @type {Boolean}
  18415. * @default false
  18416. */
  18417. this.stencil = false;
  18418. /**
  18419. * Whether the stencil attachment should be cleared or not.
  18420. *
  18421. * @type {Boolean}
  18422. * @default true
  18423. */
  18424. this.clearStencil = true;
  18425. /**
  18426. * The clear stencil value.
  18427. *
  18428. * @type {Number}
  18429. * @default 1
  18430. */
  18431. this.clearStencilValue = 1;
  18432. /**
  18433. * By default the viewport encloses the entire framebuffer If a smaller
  18434. * viewport is manually defined, this property is to `true` by the renderer.
  18435. *
  18436. * @type {Boolean}
  18437. * @default false
  18438. */
  18439. this.viewport = false;
  18440. /**
  18441. * The viewport value. This value is in physical pixels meaning it incorporates
  18442. * the renderer's pixel ratio. The viewport property of render targets or
  18443. * the renderer is in logical pixels.
  18444. *
  18445. * @type {Vector4}
  18446. */
  18447. this.viewportValue = new Vector4();
  18448. /**
  18449. * When the scissor test is active and scissor rectangle smaller than the
  18450. * framebuffers dimensions, this property is to `true` by the renderer.
  18451. *
  18452. * @type {Boolean}
  18453. * @default false
  18454. */
  18455. this.scissor = false;
  18456. /**
  18457. * The scissor rectangle.
  18458. *
  18459. * @type {Vector4}
  18460. */
  18461. this.scissorValue = new Vector4();
  18462. /**
  18463. * The active render target.
  18464. *
  18465. * @type {RenderTarget?}
  18466. * @default null
  18467. */
  18468. this.renderTarget = null;
  18469. /**
  18470. * The textures of the active render target.
  18471. * `null` when no render target is set.
  18472. *
  18473. * @type {Array<Texture>?}
  18474. * @default null
  18475. */
  18476. this.textures = null;
  18477. /**
  18478. * The depth texture of the active render target.
  18479. * `null` when no render target is set.
  18480. *
  18481. * @type {DepthTexture?}
  18482. * @default null
  18483. */
  18484. this.depthTexture = null;
  18485. /**
  18486. * The active cube face.
  18487. *
  18488. * @type {Number}
  18489. * @default 0
  18490. */
  18491. this.activeCubeFace = 0;
  18492. /**
  18493. * The active mipmap level.
  18494. *
  18495. * @type {Number}
  18496. * @default 0
  18497. */
  18498. this.activeMipmapLevel = 0;
  18499. /**
  18500. * The number of MSAA samples. This value is always `1` when
  18501. * MSAA isn't used.
  18502. *
  18503. * @type {Number}
  18504. * @default 1
  18505. */
  18506. this.sampleCount = 1;
  18507. /**
  18508. * The active render target's width in physical pixels.
  18509. *
  18510. * @type {Number}
  18511. * @default 0
  18512. */
  18513. this.width = 0;
  18514. /**
  18515. * The active render target's height in physical pixels.
  18516. *
  18517. * @type {Number}
  18518. * @default 0
  18519. */
  18520. this.height = 0;
  18521. /**
  18522. * The occlusion query count.
  18523. *
  18524. * @type {Number}
  18525. * @default 0
  18526. */
  18527. this.occlusionQueryCount = 0;
  18528. /**
  18529. * The current clipping context.
  18530. *
  18531. * @type {ClippingContext?}
  18532. * @default null
  18533. */
  18534. this.clippingContext = null;
  18535. /**
  18536. * This flag can be used for type testing.
  18537. *
  18538. * @type {Boolean}
  18539. * @readonly
  18540. * @default true
  18541. */
  18542. this.isRenderContext = true;
  18543. }
  18544. /**
  18545. * Returns the cache key of this render context.
  18546. *
  18547. * @return {Number} The cache key.
  18548. */
  18549. getCacheKey() {
  18550. return getCacheKey( this );
  18551. }
  18552. }
  18553. /**
  18554. * Computes a cache key for the given render context. This key
  18555. * should identify the render target state so it is possible to
  18556. * configure the correct attachments in the respective backend.
  18557. *
  18558. * @param {RenderContext} renderContext - The render context.
  18559. * @return {Number} The cache key.
  18560. */
  18561. function getCacheKey( renderContext ) {
  18562. const { textures, activeCubeFace } = renderContext;
  18563. const values = [ activeCubeFace ];
  18564. for ( const texture of textures ) {
  18565. values.push( texture.id );
  18566. }
  18567. return hashArray( values );
  18568. }
  18569. const _chainKeys$3 = [];
  18570. const _defaultScene = /*@__PURE__*/ new Scene();
  18571. const _defaultCamera = /*@__PURE__*/ new Camera();
  18572. /**
  18573. * This module manages the render contexts of the renderer.
  18574. *
  18575. * @private
  18576. */
  18577. class RenderContexts {
  18578. /**
  18579. * Constructs a new render context management component.
  18580. */
  18581. constructor() {
  18582. /**
  18583. * A dictionary that manages render contexts in chain maps
  18584. * for each attachment state.
  18585. *
  18586. * @type {Object<String,ChainMap>}
  18587. */
  18588. this.chainMaps = {};
  18589. }
  18590. /**
  18591. * Returns a render context for the given scene, camera and render target.
  18592. *
  18593. * @param {Scene} scene - The scene.
  18594. * @param {Camera} camera - The camera that is used to render the scene.
  18595. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18596. * @return {RenderContext} The render context.
  18597. */
  18598. get( scene, camera, renderTarget = null ) {
  18599. _chainKeys$3[ 0 ] = scene;
  18600. _chainKeys$3[ 1 ] = camera;
  18601. let attachmentState;
  18602. if ( renderTarget === null ) {
  18603. attachmentState = 'default';
  18604. } else {
  18605. const format = renderTarget.texture.format;
  18606. const count = renderTarget.textures.length;
  18607. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  18608. }
  18609. const chainMap = this._getChainMap( attachmentState );
  18610. let renderState = chainMap.get( _chainKeys$3 );
  18611. if ( renderState === undefined ) {
  18612. renderState = new RenderContext();
  18613. chainMap.set( _chainKeys$3, renderState );
  18614. }
  18615. _chainKeys$3.length = 0;
  18616. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18617. return renderState;
  18618. }
  18619. /**
  18620. * Returns a render context intended for clear operations.
  18621. *
  18622. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18623. * @return {RenderContext} The render context.
  18624. */
  18625. getForClear( renderTarget = null ) {
  18626. return this.get( _defaultScene, _defaultCamera, renderTarget );
  18627. }
  18628. /**
  18629. * Returns a chain map for the given attachment state.
  18630. *
  18631. * @private
  18632. * @param {String} attachmentState - The attachment state.
  18633. * @return {ChainMap} The chain map.
  18634. */
  18635. _getChainMap( attachmentState ) {
  18636. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  18637. }
  18638. /**
  18639. * Frees internal resources.
  18640. */
  18641. dispose() {
  18642. this.chainMaps = {};
  18643. }
  18644. }
  18645. const _size$3 = /*@__PURE__*/ new Vector3();
  18646. /**
  18647. * This module manages the textures of the renderer.
  18648. *
  18649. * @private
  18650. * @augments DataMap
  18651. */
  18652. class Textures extends DataMap {
  18653. /**
  18654. * Constructs a new texture management component.
  18655. *
  18656. * @param {Renderer} renderer - The renderer.
  18657. * @param {Backend} backend - The renderer's backend.
  18658. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18659. */
  18660. constructor( renderer, backend, info ) {
  18661. super();
  18662. /**
  18663. * The renderer.
  18664. *
  18665. * @type {Renderer}
  18666. */
  18667. this.renderer = renderer;
  18668. /**
  18669. * The backend.
  18670. *
  18671. * @type {Backend}
  18672. */
  18673. this.backend = backend;
  18674. /**
  18675. * Renderer component for managing metrics and monitoring data.
  18676. *
  18677. * @type {Info}
  18678. */
  18679. this.info = info;
  18680. }
  18681. /**
  18682. * Updates the given render target. Based on the given render target configuration,
  18683. * it updates the texture states representing the attachments of the framebuffer.
  18684. *
  18685. * @param {RenderTarget} renderTarget - The render target to update.
  18686. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  18687. */
  18688. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  18689. const renderTargetData = this.get( renderTarget );
  18690. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18691. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  18692. const textures = renderTarget.textures;
  18693. const size = this.getSize( textures[ 0 ] );
  18694. const mipWidth = size.width >> activeMipmapLevel;
  18695. const mipHeight = size.height >> activeMipmapLevel;
  18696. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  18697. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  18698. let textureNeedsUpdate = false;
  18699. if ( depthTexture === undefined && useDepthTexture ) {
  18700. depthTexture = new DepthTexture();
  18701. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  18702. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  18703. depthTexture.image.width = mipWidth;
  18704. depthTexture.image.height = mipHeight;
  18705. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  18706. }
  18707. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  18708. textureNeedsUpdate = true;
  18709. if ( depthTexture ) {
  18710. depthTexture.needsUpdate = true;
  18711. depthTexture.image.width = mipWidth;
  18712. depthTexture.image.height = mipHeight;
  18713. }
  18714. }
  18715. renderTargetData.width = size.width;
  18716. renderTargetData.height = size.height;
  18717. renderTargetData.textures = textures;
  18718. renderTargetData.depthTexture = depthTexture || null;
  18719. renderTargetData.depth = renderTarget.depthBuffer;
  18720. renderTargetData.stencil = renderTarget.stencilBuffer;
  18721. renderTargetData.renderTarget = renderTarget;
  18722. if ( renderTargetData.sampleCount !== sampleCount ) {
  18723. textureNeedsUpdate = true;
  18724. if ( depthTexture ) {
  18725. depthTexture.needsUpdate = true;
  18726. }
  18727. renderTargetData.sampleCount = sampleCount;
  18728. }
  18729. //
  18730. const options = { sampleCount };
  18731. for ( let i = 0; i < textures.length; i ++ ) {
  18732. const texture = textures[ i ];
  18733. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  18734. this.updateTexture( texture, options );
  18735. }
  18736. if ( depthTexture ) {
  18737. this.updateTexture( depthTexture, options );
  18738. }
  18739. // dispose handler
  18740. if ( renderTargetData.initialized !== true ) {
  18741. renderTargetData.initialized = true;
  18742. // dispose
  18743. const onDispose = () => {
  18744. renderTarget.removeEventListener( 'dispose', onDispose );
  18745. for ( let i = 0; i < textures.length; i ++ ) {
  18746. this._destroyTexture( textures[ i ] );
  18747. }
  18748. if ( depthTexture ) {
  18749. this._destroyTexture( depthTexture );
  18750. }
  18751. this.delete( renderTarget );
  18752. };
  18753. renderTarget.addEventListener( 'dispose', onDispose );
  18754. }
  18755. }
  18756. /**
  18757. * Updates the given texture. Depending on the texture state, this method
  18758. * triggers the upload of texture data to the GPU memory. If the texture data are
  18759. * not yet ready for the upload, it uses default texture data for as a placeholder.
  18760. *
  18761. * @param {Texture} texture - The texture to update.
  18762. * @param {Object} [options={}] - The options.
  18763. */
  18764. updateTexture( texture, options = {} ) {
  18765. const textureData = this.get( texture );
  18766. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  18767. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  18768. const backend = this.backend;
  18769. if ( isRenderTarget && textureData.initialized === true ) {
  18770. // it's an update
  18771. backend.destroySampler( texture );
  18772. backend.destroyTexture( texture );
  18773. }
  18774. //
  18775. if ( texture.isFramebufferTexture ) {
  18776. const renderTarget = this.renderer.getRenderTarget();
  18777. if ( renderTarget ) {
  18778. texture.type = renderTarget.texture.type;
  18779. } else {
  18780. texture.type = UnsignedByteType;
  18781. }
  18782. }
  18783. //
  18784. const { width, height, depth } = this.getSize( texture );
  18785. options.width = width;
  18786. options.height = height;
  18787. options.depth = depth;
  18788. options.needsMipmaps = this.needsMipmaps( texture );
  18789. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  18790. //
  18791. if ( isRenderTarget || texture.isStorageTexture === true ) {
  18792. backend.createSampler( texture );
  18793. backend.createTexture( texture, options );
  18794. textureData.generation = texture.version;
  18795. } else {
  18796. const needsCreate = textureData.initialized !== true;
  18797. if ( needsCreate ) backend.createSampler( texture );
  18798. if ( texture.version > 0 ) {
  18799. const image = texture.image;
  18800. if ( image === undefined ) {
  18801. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  18802. } else if ( image.complete === false ) {
  18803. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  18804. } else {
  18805. if ( texture.images ) {
  18806. const images = [];
  18807. for ( const image of texture.images ) {
  18808. images.push( image );
  18809. }
  18810. options.images = images;
  18811. } else {
  18812. options.image = image;
  18813. }
  18814. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  18815. backend.createTexture( texture, options );
  18816. textureData.isDefaultTexture = false;
  18817. textureData.generation = texture.version;
  18818. }
  18819. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  18820. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  18821. }
  18822. } else {
  18823. // async update
  18824. backend.createDefaultTexture( texture );
  18825. textureData.isDefaultTexture = true;
  18826. textureData.generation = texture.version;
  18827. }
  18828. }
  18829. // dispose handler
  18830. if ( textureData.initialized !== true ) {
  18831. textureData.initialized = true;
  18832. textureData.generation = texture.version;
  18833. //
  18834. this.info.memory.textures ++;
  18835. // dispose
  18836. const onDispose = () => {
  18837. texture.removeEventListener( 'dispose', onDispose );
  18838. this._destroyTexture( texture );
  18839. this.info.memory.textures --;
  18840. };
  18841. texture.addEventListener( 'dispose', onDispose );
  18842. }
  18843. //
  18844. textureData.version = texture.version;
  18845. }
  18846. /**
  18847. * Computes the size of the given texture and writes the result
  18848. * into the target vector. This vector is also returned by the
  18849. * method.
  18850. *
  18851. * If no texture data are available for the compute yet, the method
  18852. * returns default size values.
  18853. *
  18854. * @param {Texture} texture - The texture to compute the size for.
  18855. * @param {Vector3} target - The target vector.
  18856. * @return {Vector3} The target vector.
  18857. */
  18858. getSize( texture, target = _size$3 ) {
  18859. let image = texture.images ? texture.images[ 0 ] : texture.image;
  18860. if ( image ) {
  18861. if ( image.image !== undefined ) image = image.image;
  18862. target.width = image.width || 1;
  18863. target.height = image.height || 1;
  18864. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  18865. } else {
  18866. target.width = target.height = target.depth = 1;
  18867. }
  18868. return target;
  18869. }
  18870. /**
  18871. * Computes the number of mipmap levels for the given texture.
  18872. *
  18873. * @param {Texture} texture - The texture.
  18874. * @param {Number} width - The texture's width.
  18875. * @param {Number} height - The texture's height.
  18876. * @return {Number} The number of mipmap levels.
  18877. */
  18878. getMipLevels( texture, width, height ) {
  18879. let mipLevelCount;
  18880. if ( texture.isCompressedTexture ) {
  18881. if ( texture.mipmaps ) {
  18882. mipLevelCount = texture.mipmaps.length;
  18883. } else {
  18884. mipLevelCount = 1;
  18885. }
  18886. } else {
  18887. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  18888. }
  18889. return mipLevelCount;
  18890. }
  18891. /**
  18892. * Returns `true` if the given texture requires mipmaps.
  18893. *
  18894. * @param {Texture} texture - The texture.
  18895. * @return {Boolean} Whether mipmaps are required or not.
  18896. */
  18897. needsMipmaps( texture ) {
  18898. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  18899. }
  18900. /**
  18901. * Returns `true` if the given texture is an environment map.
  18902. *
  18903. * @param {Texture} texture - The texture.
  18904. * @return {Boolean} Whether the given texture is an environment map or not.
  18905. */
  18906. isEnvironmentTexture( texture ) {
  18907. const mapping = texture.mapping;
  18908. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  18909. }
  18910. /**
  18911. * Frees internal resource when the given texture isn't
  18912. * required anymore.
  18913. *
  18914. * @param {Texture} texture - The texture to destroy.
  18915. */
  18916. _destroyTexture( texture ) {
  18917. this.backend.destroySampler( texture );
  18918. this.backend.destroyTexture( texture );
  18919. this.delete( texture );
  18920. }
  18921. }
  18922. /**
  18923. * A four-component version of {@link Color} which is internally
  18924. * used by the renderer to represents clear color with alpha as
  18925. * one object.
  18926. *
  18927. * @private
  18928. * @augments Color
  18929. */
  18930. class Color4 extends Color {
  18931. /**
  18932. * Constructs a new four-component color.
  18933. *
  18934. * @param {Number|String} r - The red value.
  18935. * @param {Number} g - The green value.
  18936. * @param {Number} b - The blue value.
  18937. * @param {Number} [a=1] - The alpha value.
  18938. */
  18939. constructor( r, g, b, a = 1 ) {
  18940. super( r, g, b );
  18941. this.a = a;
  18942. }
  18943. /**
  18944. * Overwrites the default to honor alpha.
  18945. * You can also passed a single THREE.Color, hex or
  18946. * string argument to this method.
  18947. *
  18948. * @param {Number|String} r - The red value.
  18949. * @param {Number} g - The green value.
  18950. * @param {Number} b - The blue value.
  18951. * @param {Number} [a=1] - The alpha value.
  18952. * @return {Color4} A reference to this object.
  18953. */
  18954. set( r, g, b, a = 1 ) {
  18955. this.a = a;
  18956. return super.set( r, g, b );
  18957. }
  18958. /**
  18959. * Overwrites the default to honor alpha.
  18960. *
  18961. * @param {Color4} color - The color to copy.
  18962. * @return {Color4} A reference to this object.
  18963. */
  18964. copy( color ) {
  18965. if ( color.a !== undefined ) this.a = color.a;
  18966. return super.copy( color );
  18967. }
  18968. /**
  18969. * Overwrites the default to honor alpha.
  18970. *
  18971. * @return {Color4} The cloned color.
  18972. */
  18973. clone() {
  18974. return new this.constructor( this.r, this.g, this.b, this.a );
  18975. }
  18976. }
  18977. /** @module ParameterNode **/
  18978. /**
  18979. * Special version of {@link PropertyNode} which is used for parameters.
  18980. *
  18981. * @augments PropertyNode
  18982. */
  18983. class ParameterNode extends PropertyNode {
  18984. static get type() {
  18985. return 'ParameterNode';
  18986. }
  18987. /**
  18988. * Constructs a new parameter node.
  18989. *
  18990. * @param {String} nodeType - The type of the node.
  18991. * @param {String?} [name=null] - The name of the parameter in the shader.
  18992. */
  18993. constructor( nodeType, name = null ) {
  18994. super( nodeType, name );
  18995. /**
  18996. * This flag can be used for type testing.
  18997. *
  18998. * @type {Boolean}
  18999. * @readonly
  19000. * @default true
  19001. */
  19002. this.isParameterNode = true;
  19003. }
  19004. getHash() {
  19005. return this.uuid;
  19006. }
  19007. generate() {
  19008. return this.name;
  19009. }
  19010. }
  19011. /**
  19012. * TSL function for creating a parameter node.
  19013. *
  19014. * @function
  19015. * @param {String} type - The type of the node.
  19016. * @param {String?} name - The name of the parameter in the shader.
  19017. * @returns {ParameterNode}
  19018. */
  19019. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  19020. /** @module StackNode **/
  19021. /**
  19022. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  19023. * They are usually needed in cases like `If`, `Else`.
  19024. *
  19025. * @augments Node
  19026. */
  19027. class StackNode extends Node {
  19028. static get type() {
  19029. return 'StackNode';
  19030. }
  19031. /**
  19032. * Constructs a new stack node.
  19033. *
  19034. * @param {StackNode?} [parent=null] - The parent stack node.
  19035. */
  19036. constructor( parent = null ) {
  19037. super();
  19038. /**
  19039. * List of nodes.
  19040. *
  19041. * @type {Array<Node>}
  19042. */
  19043. this.nodes = [];
  19044. /**
  19045. * The output node.
  19046. *
  19047. * @type {Node?}
  19048. * @default null
  19049. */
  19050. this.outputNode = null;
  19051. /**
  19052. * The parent stack node.
  19053. *
  19054. * @type {StackNode}
  19055. * @default null
  19056. */
  19057. this.parent = parent;
  19058. /**
  19059. * The current conditional node.
  19060. *
  19061. * @private
  19062. * @type {ConditionalNode}
  19063. * @default null
  19064. */
  19065. this._currentCond = null;
  19066. /**
  19067. * This flag can be used for type testing.
  19068. *
  19069. * @type {Boolean}
  19070. * @readonly
  19071. * @default true
  19072. */
  19073. this.isStackNode = true;
  19074. }
  19075. getNodeType( builder ) {
  19076. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  19077. }
  19078. /**
  19079. * Adds a node to this stack.
  19080. *
  19081. * @param {Node} node - The node to add.
  19082. * @return {StackNode} A reference to this stack node.
  19083. */
  19084. add( node ) {
  19085. this.nodes.push( node );
  19086. return this;
  19087. }
  19088. /**
  19089. * Represent an `if` statement in TSL.
  19090. *
  19091. * @param {Node} boolNode - Represents the condition.
  19092. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19093. * @return {StackNode} A reference to this stack node.
  19094. */
  19095. If( boolNode, method ) {
  19096. const methodNode = new ShaderNode( method );
  19097. this._currentCond = select( boolNode, methodNode );
  19098. return this.add( this._currentCond );
  19099. }
  19100. /**
  19101. * Represent an `elseif` statement in TSL.
  19102. *
  19103. * @param {Node} boolNode - Represents the condition.
  19104. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19105. * @return {StackNode} A reference to this stack node.
  19106. */
  19107. ElseIf( boolNode, method ) {
  19108. const methodNode = new ShaderNode( method );
  19109. const ifNode = select( boolNode, methodNode );
  19110. this._currentCond.elseNode = ifNode;
  19111. this._currentCond = ifNode;
  19112. return this;
  19113. }
  19114. /**
  19115. * Represent an `else` statement in TSL.
  19116. *
  19117. * @param {Function} method - TSL code which is executed in the `else` case.
  19118. * @return {StackNode} A reference to this stack node.
  19119. */
  19120. Else( method ) {
  19121. this._currentCond.elseNode = new ShaderNode( method );
  19122. return this;
  19123. }
  19124. build( builder, ...params ) {
  19125. const previousStack = getCurrentStack();
  19126. setCurrentStack( this );
  19127. for ( const node of this.nodes ) {
  19128. node.build( builder, 'void' );
  19129. }
  19130. setCurrentStack( previousStack );
  19131. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  19132. }
  19133. // deprecated
  19134. /**
  19135. * @function
  19136. * @deprecated since r168. Use {@link StackNode#Else} instead.
  19137. *
  19138. * @param {...any} params
  19139. * @returns {StackNode}
  19140. */
  19141. else( ...params ) { // @deprecated, r168
  19142. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  19143. return this.Else( ...params );
  19144. }
  19145. /**
  19146. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  19147. *
  19148. * @param {...any} params
  19149. * @returns {StackNode}
  19150. */
  19151. elseif( ...params ) { // @deprecated, r168
  19152. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  19153. return this.ElseIf( ...params );
  19154. }
  19155. }
  19156. /**
  19157. * TSL function for creating a stack node.
  19158. *
  19159. * @function
  19160. * @param {StackNode?} [parent=null] - The parent stack node.
  19161. * @returns {StackNode}
  19162. */
  19163. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  19164. /** @module OutputStructNode **/
  19165. /**
  19166. * This node can be used to define multiple outputs in a shader programs.
  19167. *
  19168. * @augments Node
  19169. */
  19170. class OutputStructNode extends Node {
  19171. static get type() {
  19172. return 'OutputStructNode';
  19173. }
  19174. /**
  19175. * Constructs a new output struct node. The constructor can be invoked with an
  19176. * arbitrary number of nodes representing the members.
  19177. *
  19178. * @param {...Node} members - A parameter list of nodes.
  19179. */
  19180. constructor( ...members ) {
  19181. super();
  19182. /**
  19183. * An array of nodes which defines the output.
  19184. *
  19185. * @type {Array<Node>}
  19186. */
  19187. this.members = members;
  19188. /**
  19189. * This flag can be used for type testing.
  19190. *
  19191. * @type {Boolean}
  19192. * @readonly
  19193. * @default true
  19194. */
  19195. this.isOutputStructNode = true;
  19196. }
  19197. setup( builder ) {
  19198. super.setup( builder );
  19199. const members = this.members;
  19200. const types = [];
  19201. for ( let i = 0; i < members.length; i ++ ) {
  19202. types.push( members[ i ].getNodeType( builder ) );
  19203. }
  19204. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  19205. }
  19206. generate( builder, output ) {
  19207. const propertyName = builder.getOutputStructName();
  19208. const members = this.members;
  19209. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  19210. for ( let i = 0; i < members.length; i ++ ) {
  19211. const snippet = members[ i ].build( builder, output );
  19212. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  19213. }
  19214. return propertyName;
  19215. }
  19216. }
  19217. /**
  19218. * TSL function for creating an output struct node.
  19219. *
  19220. * @function
  19221. * @param {...Node} members - A parameter list of nodes.
  19222. * @returns {OutputStructNode}
  19223. */
  19224. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  19225. /** @module MRTNode **/
  19226. /**
  19227. * Returns the MRT texture index for the given name.
  19228. *
  19229. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  19230. * @param {String} name - The name of the MRT texture which index is requested.
  19231. * @return {Number} The texture index.
  19232. */
  19233. function getTextureIndex( textures, name ) {
  19234. for ( let i = 0; i < textures.length; i ++ ) {
  19235. if ( textures[ i ].name === name ) {
  19236. return i;
  19237. }
  19238. }
  19239. return - 1;
  19240. }
  19241. /**
  19242. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  19243. * post-processing is shown below:
  19244. * ```js
  19245. * const mrtNode = mrt( {
  19246. * output: output,
  19247. * normal: normalView
  19248. * } ) );
  19249. * ```
  19250. * The MRT output is defined as a dictionary.
  19251. *
  19252. * @augments OutputStructNode
  19253. */
  19254. class MRTNode extends OutputStructNode {
  19255. static get type() {
  19256. return 'MRTNode';
  19257. }
  19258. /**
  19259. * Constructs a new output struct node.
  19260. *
  19261. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19262. */
  19263. constructor( outputNodes ) {
  19264. super();
  19265. /**
  19266. * A dictionary representing the MRT outputs. The key
  19267. * is the name of the output, the value the node which produces
  19268. * the output result.
  19269. *
  19270. * @type {Object<String, Node>}
  19271. */
  19272. this.outputNodes = outputNodes;
  19273. /**
  19274. * This flag can be used for type testing.
  19275. *
  19276. * @type {Boolean}
  19277. * @readonly
  19278. * @default true
  19279. */
  19280. this.isMRTNode = true;
  19281. }
  19282. /**
  19283. * Returns `true` if the MRT node has an output with the given name.
  19284. *
  19285. * @param {String} name - The name of the output.
  19286. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  19287. */
  19288. has( name ) {
  19289. return this.outputNodes[ name ] !== undefined;
  19290. }
  19291. /**
  19292. * Returns the output node for the given name.
  19293. *
  19294. * @param {String} name - The name of the output.
  19295. * @return {Node} The output node.
  19296. */
  19297. get( name ) {
  19298. return this.outputNodes[ name ];
  19299. }
  19300. /**
  19301. * Merges the outputs of the given MRT node with the outputs of this node.
  19302. *
  19303. * @param {MRTNode} mrtNode - The MRT to merge.
  19304. * @return {MRTNode} A new MRT node with merged outputs..
  19305. */
  19306. merge( mrtNode ) {
  19307. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  19308. return mrt( outputs );
  19309. }
  19310. setup( builder ) {
  19311. const outputNodes = this.outputNodes;
  19312. const mrt = builder.renderer.getRenderTarget();
  19313. const members = [];
  19314. const textures = mrt.textures;
  19315. for ( const name in outputNodes ) {
  19316. const index = getTextureIndex( textures, name );
  19317. members[ index ] = vec4( outputNodes[ name ] );
  19318. }
  19319. this.members = members;
  19320. return super.setup( builder );
  19321. }
  19322. }
  19323. /**
  19324. * TSL function for creating a MRT node.
  19325. *
  19326. * @function
  19327. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19328. * @returns {MRTNode}
  19329. */
  19330. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  19331. /** @module Hash **/
  19332. /**
  19333. * Generates a hash value in the range `[0, 1]` from the given seed.
  19334. *
  19335. * @method
  19336. * @param {Node<float>} seed - The seed.
  19337. * @return {Node<float>} The hash value.
  19338. */
  19339. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  19340. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  19341. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  19342. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  19343. const result = word.shiftRight( 22 ).bitXor( word );
  19344. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  19345. } );
  19346. /** @module MathUtils **/
  19347. /**
  19348. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19349. * The corners are mapped to `0` and the center to `1`.
  19350. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19351. *
  19352. * @method
  19353. * @param {Node<float>} x - The value to remap.
  19354. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  19355. * @return {Node<float>} The remapped value.
  19356. */
  19357. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  19358. /**
  19359. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19360. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  19361. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19362. *
  19363. * @method
  19364. * @param {Node<float>} x - The value to remap.
  19365. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  19366. * @return {Node<float>} The remapped value.
  19367. */
  19368. 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 ) );
  19369. /**
  19370. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19371. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  19372. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19373. *
  19374. * @method
  19375. * @param {Node<float>} x - The value to remap.
  19376. * @param {Node<float>} a - First control parameter.
  19377. * @param {Node<float>} b - Second control parameter.
  19378. * @return {Node<float>} The remapped value.
  19379. */
  19380. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  19381. /**
  19382. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  19383. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19384. *
  19385. * @method
  19386. * @param {Node<float>} x - The value to compute the sin for.
  19387. * @param {Node<float>} k - Controls the amount of bounces.
  19388. * @return {Node<float>} The result value.
  19389. */
  19390. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  19391. // https://github.com/cabbibo/glsl-tri-noise-3d
  19392. /** @module TriNoise3D **/
  19393. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  19394. return x.fract().sub( .5 ).abs();
  19395. } ).setLayout( {
  19396. name: 'tri',
  19397. type: 'float',
  19398. inputs: [
  19399. { name: 'x', type: 'float' }
  19400. ]
  19401. } );
  19402. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  19403. 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. ) ) ) ) );
  19404. } ).setLayout( {
  19405. name: 'tri3',
  19406. type: 'vec3',
  19407. inputs: [
  19408. { name: 'p', type: 'vec3' }
  19409. ]
  19410. } );
  19411. /**
  19412. * Generates a noise value from the given position, speed and time parameters.
  19413. *
  19414. * @method
  19415. * @param {Node<vec3>} position - The position.
  19416. * @param {Node<float>} speed - The speed.
  19417. * @param {Node<float>} time - The time.
  19418. * @return {Node<float>} The generated noise.
  19419. */
  19420. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  19421. const p = vec3( position ).toVar();
  19422. const z = float( 1.4 ).toVar();
  19423. const rz = float( 0.0 ).toVar();
  19424. const bp = vec3( p ).toVar();
  19425. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  19426. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  19427. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  19428. bp.mulAssign( 1.8 );
  19429. z.mulAssign( 1.5 );
  19430. p.mulAssign( 1.2 );
  19431. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  19432. rz.addAssign( t.div( z ) );
  19433. bp.addAssign( 0.14 );
  19434. } );
  19435. return rz;
  19436. } ).setLayout( {
  19437. name: 'triNoise3D',
  19438. type: 'float',
  19439. inputs: [
  19440. { name: 'position', type: 'vec3' },
  19441. { name: 'speed', type: 'float' },
  19442. { name: 'time', type: 'float' }
  19443. ]
  19444. } );
  19445. /** @module FunctionOverloadingNode **/
  19446. /**
  19447. * This class allows to define multiple overloaded versions
  19448. * of the same function. Depending on the parameters of the function
  19449. * call, the node picks the best-fit overloaded version.
  19450. *
  19451. * @augments Node
  19452. */
  19453. class FunctionOverloadingNode extends Node {
  19454. static get type() {
  19455. return 'FunctionOverloadingNode';
  19456. }
  19457. /**
  19458. * Constructs a new function overloading node.
  19459. *
  19460. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19461. * @param {...Node} parametersNodes - A list of parameter nodes.
  19462. */
  19463. constructor( functionNodes = [], ...parametersNodes ) {
  19464. super();
  19465. /**
  19466. * Array of `Fn` function definitions.
  19467. *
  19468. * @type {Array<Function>}
  19469. */
  19470. this.functionNodes = functionNodes;
  19471. /**
  19472. * A list of parameter nodes.
  19473. *
  19474. * @type {Array<Node>}
  19475. */
  19476. this.parametersNodes = parametersNodes;
  19477. /**
  19478. * The selected overloaded function call.
  19479. *
  19480. * @private
  19481. * @type {ShaderCallNodeInternal}
  19482. */
  19483. this._candidateFnCall = null;
  19484. /**
  19485. * This node is marked as global.
  19486. *
  19487. * @type {Boolean}
  19488. * @default true
  19489. */
  19490. this.global = true;
  19491. }
  19492. /**
  19493. * This method is overwritten since the node type is inferred from
  19494. * the function's return type.
  19495. *
  19496. * @param {NodeBuilder} builder - The current node builder.
  19497. * @return {String} The node type.
  19498. */
  19499. getNodeType() {
  19500. return this.functionNodes[ 0 ].shaderNode.layout.type;
  19501. }
  19502. setup( builder ) {
  19503. const params = this.parametersNodes;
  19504. let candidateFnCall = this._candidateFnCall;
  19505. if ( candidateFnCall === null ) {
  19506. let candidateFn = null;
  19507. let candidateScore = - 1;
  19508. for ( const functionNode of this.functionNodes ) {
  19509. const shaderNode = functionNode.shaderNode;
  19510. const layout = shaderNode.layout;
  19511. if ( layout === null ) {
  19512. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  19513. }
  19514. const inputs = layout.inputs;
  19515. if ( params.length === inputs.length ) {
  19516. let score = 0;
  19517. for ( let i = 0; i < params.length; i ++ ) {
  19518. const param = params[ i ];
  19519. const input = inputs[ i ];
  19520. if ( param.getNodeType( builder ) === input.type ) {
  19521. score ++;
  19522. } else {
  19523. score = 0;
  19524. }
  19525. }
  19526. if ( score > candidateScore ) {
  19527. candidateFn = functionNode;
  19528. candidateScore = score;
  19529. }
  19530. }
  19531. }
  19532. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  19533. }
  19534. return candidateFnCall;
  19535. }
  19536. }
  19537. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  19538. /**
  19539. * TSL function for creating a function overloading node.
  19540. *
  19541. * @function
  19542. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19543. * @returns {FunctionOverloadingNode}
  19544. */
  19545. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  19546. /** @module Timer **/
  19547. /**
  19548. * Represents the elapsed time in seconds.
  19549. *
  19550. * @type {UniformNode<float>}
  19551. */
  19552. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  19553. /**
  19554. * Represents the delta time in seconds.
  19555. *
  19556. * @type {UniformNode<float>}
  19557. */
  19558. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  19559. /**
  19560. * Represents the current frame ID.
  19561. *
  19562. * @type {UniformNode<uint>}
  19563. */
  19564. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  19565. // Deprecated
  19566. /**
  19567. * @function
  19568. * @deprecated since r170. Use {@link time} instead.
  19569. *
  19570. * @param {Number} [timeScale=1] - The time scale.
  19571. * @returns {UniformNode<float>}
  19572. */
  19573. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  19574. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  19575. return time.mul( timeScale );
  19576. };
  19577. /**
  19578. * @function
  19579. * @deprecated since r170. Use {@link time} instead.
  19580. *
  19581. * @param {Number} [timeScale=1] - The time scale.
  19582. * @returns {UniformNode<float>}
  19583. */
  19584. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  19585. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  19586. return time.mul( timeScale );
  19587. };
  19588. /**
  19589. * @function
  19590. * @deprecated since r170. Use {@link deltaTime} instead.
  19591. *
  19592. * @param {Number} [timeScale=1] - The time scale.
  19593. * @returns {UniformNode<float>}
  19594. */
  19595. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  19596. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  19597. return deltaTime.mul( timeScale );
  19598. };
  19599. /** @module Oscillators **/
  19600. /**
  19601. * Generates a sine wave oscillation based on a timer.
  19602. *
  19603. * @method
  19604. * @param {Node<float>} t - The timer to generate the oscillation with.
  19605. * @return {Node<float>} The oscillation node.
  19606. */
  19607. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  19608. /**
  19609. * Generates a square wave oscillation based on a timer.
  19610. *
  19611. * @method
  19612. * @param {Node<float>} t - The timer to generate the oscillation with.
  19613. * @return {Node<float>} The oscillation node.
  19614. */
  19615. const oscSquare = ( t = time ) => t.fract().round();
  19616. /**
  19617. * Generates a triangle wave oscillation based on a timer.
  19618. *
  19619. * @method
  19620. * @param {Node<float>} t - The timer to generate the oscillation with.
  19621. * @return {Node<float>} The oscillation node.
  19622. */
  19623. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  19624. /**
  19625. * Generates a sawtooth wave oscillation based on a timer.
  19626. *
  19627. * @method
  19628. * @param {Node<float>} t - The timer to generate the oscillation with.
  19629. * @return {Node<float>} The oscillation node.
  19630. */
  19631. const oscSawtooth = ( t = time ) => t.fract();
  19632. /** @module UVUtils **/
  19633. /**
  19634. * Rotates the given uv coordinates around a center point
  19635. *
  19636. * @method
  19637. * @param {Node<vec2>} uv - The uv coordinates.
  19638. * @param {Node<float>} rotation - The rotation defined in radians.
  19639. * @param {Node<vec2>} center - The center of rotation
  19640. * @return {Node<vec2>} The rotated uv coordinates.
  19641. */
  19642. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  19643. return rotate( uv.sub( center ), rotation ).add( center );
  19644. } );
  19645. /**
  19646. * Applies a spherical warping effect to the given uv coordinates.
  19647. *
  19648. * @method
  19649. * @param {Node<vec2>} uv - The uv coordinates.
  19650. * @param {Node<float>} strength - The strength of the effect.
  19651. * @param {Node<vec2>} center - The center point
  19652. * @return {Node<vec2>} The updated uv coordinates.
  19653. */
  19654. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  19655. const delta = uv.sub( center );
  19656. const delta2 = delta.dot( delta );
  19657. const delta4 = delta2.mul( delta2 );
  19658. const deltaOffset = delta4.mul( strength );
  19659. return uv.add( delta.mul( deltaOffset ) );
  19660. } );
  19661. /** @module SpriteUtils **/
  19662. /**
  19663. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  19664. * oriented always towards the camera.
  19665. *
  19666. * ```js
  19667. * material.vertexNode = billboarding();
  19668. * ```
  19669. *
  19670. * @method
  19671. * @param {Object} config - The configuration object.
  19672. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  19673. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  19674. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  19675. * @return {Node<vec3>} The updated vertex position in clip space.
  19676. */
  19677. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  19678. let worldMatrix;
  19679. if ( position !== null ) {
  19680. worldMatrix = modelWorldMatrix.toVar();
  19681. worldMatrix[ 3 ][ 0 ] = position.x;
  19682. worldMatrix[ 3 ][ 1 ] = position.y;
  19683. worldMatrix[ 3 ][ 2 ] = position.z;
  19684. } else {
  19685. worldMatrix = modelWorldMatrix;
  19686. }
  19687. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  19688. if ( defined( horizontal ) ) {
  19689. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  19690. modelViewMatrix[ 0 ][ 1 ] = 0;
  19691. modelViewMatrix[ 0 ][ 2 ] = 0;
  19692. }
  19693. if ( defined( vertical ) ) {
  19694. modelViewMatrix[ 1 ][ 0 ] = 0;
  19695. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  19696. modelViewMatrix[ 1 ][ 2 ] = 0;
  19697. }
  19698. modelViewMatrix[ 2 ][ 0 ] = 0;
  19699. modelViewMatrix[ 2 ][ 1 ] = 0;
  19700. modelViewMatrix[ 2 ][ 2 ] = 1;
  19701. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  19702. } );
  19703. /** @module ViewportUtils **/
  19704. /**
  19705. * A special version of a screen uv function that involves a depth comparison
  19706. * when computing the final uvs. The function mitigates visual errors when
  19707. * using viewport texture nodes for refraction purposes. Without this function
  19708. * objects in front of a refractive surface might appear on the refractive surface
  19709. * which is incorrect.
  19710. *
  19711. * @method
  19712. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  19713. * @return {Node<vec2>} The update uv coordinates.
  19714. */
  19715. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  19716. const depth = linearDepth();
  19717. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  19718. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  19719. return finalUV;
  19720. } );
  19721. /** @module SpriteSheetUVNode **/
  19722. /**
  19723. * Can be used to compute texture coordinates for animated sprite sheets.
  19724. *
  19725. * ```js
  19726. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  19727. *
  19728. * material.colorNode = texture( spriteSheet, uvNode );
  19729. * ```
  19730. *
  19731. * @augments Node
  19732. */
  19733. class SpriteSheetUVNode extends Node {
  19734. static get type() {
  19735. return 'SpriteSheetUVNode';
  19736. }
  19737. /**
  19738. * Constructs a new sprite sheet uv node.
  19739. *
  19740. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19741. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19742. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19743. */
  19744. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  19745. super( 'vec2' );
  19746. /**
  19747. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19748. *
  19749. * @type {Node<vec2>}
  19750. */
  19751. this.countNode = countNode;
  19752. /**
  19753. * The uv node.
  19754. *
  19755. * @type {Node<vec2>}
  19756. */
  19757. this.uvNode = uvNode;
  19758. /**
  19759. * The node that defines the current frame/sprite.
  19760. *
  19761. * @type {Node<float>}
  19762. */
  19763. this.frameNode = frameNode;
  19764. }
  19765. setup() {
  19766. const { frameNode, uvNode, countNode } = this;
  19767. const { width, height } = countNode;
  19768. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  19769. const column = frameNum.mod( width );
  19770. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  19771. const scale = countNode.reciprocal();
  19772. const uvFrameOffset = vec2( column, row );
  19773. return uvNode.add( uvFrameOffset ).mul( scale );
  19774. }
  19775. }
  19776. /**
  19777. * TSL function for creating a sprite sheet uv node.
  19778. *
  19779. * @function
  19780. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19781. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19782. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19783. * @returns {SpriteSheetUVNode}
  19784. */
  19785. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  19786. /** @module TriplanarTexturesNode **/
  19787. /**
  19788. * Can be used for triplanar texture mapping.
  19789. *
  19790. * ```js
  19791. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  19792. * ```
  19793. *
  19794. * @augments Node
  19795. */
  19796. class TriplanarTexturesNode extends Node {
  19797. static get type() {
  19798. return 'TriplanarTexturesNode';
  19799. }
  19800. /**
  19801. * Constructs a new triplanar textures node.
  19802. *
  19803. * @param {Node} textureXNode - First texture node.
  19804. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19805. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19806. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19807. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19808. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19809. */
  19810. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  19811. super( 'vec4' );
  19812. /**
  19813. * First texture node.
  19814. *
  19815. * @type {Node}
  19816. */
  19817. this.textureXNode = textureXNode;
  19818. /**
  19819. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19820. *
  19821. * @type {Node}
  19822. * @default null
  19823. */
  19824. this.textureYNode = textureYNode;
  19825. /**
  19826. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19827. *
  19828. * @type {Node}
  19829. * @default null
  19830. */
  19831. this.textureZNode = textureZNode;
  19832. /**
  19833. * The scale node.
  19834. *
  19835. * @type {Node<float>}
  19836. * @default float(1)
  19837. */
  19838. this.scaleNode = scaleNode;
  19839. /**
  19840. * Vertex positions in local space.
  19841. *
  19842. * @type {Node<vec3>}
  19843. * @default positionLocal
  19844. */
  19845. this.positionNode = positionNode;
  19846. /**
  19847. * Normals in local space.
  19848. *
  19849. * @type {Node<vec3>}
  19850. * @default normalLocal
  19851. */
  19852. this.normalNode = normalNode;
  19853. }
  19854. setup() {
  19855. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  19856. // Ref: https://github.com/keijiro/StandardTriplanar
  19857. // Blending factor of triplanar mapping
  19858. let bf = normalNode.abs().normalize();
  19859. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  19860. // Triplanar mapping
  19861. const tx = positionNode.yz.mul( scaleNode );
  19862. const ty = positionNode.zx.mul( scaleNode );
  19863. const tz = positionNode.xy.mul( scaleNode );
  19864. // Base color
  19865. const textureX = textureXNode.value;
  19866. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  19867. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  19868. const cx = texture( textureX, tx ).mul( bf.x );
  19869. const cy = texture( textureY, ty ).mul( bf.y );
  19870. const cz = texture( textureZ, tz ).mul( bf.z );
  19871. return add( cx, cy, cz );
  19872. }
  19873. }
  19874. /**
  19875. * TSL function for creating a triplanar textures node.
  19876. *
  19877. * @function
  19878. * @param {Node} textureXNode - First texture node.
  19879. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19880. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19881. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19882. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19883. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19884. * @returns {TriplanarTexturesNode}
  19885. */
  19886. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  19887. /**
  19888. * TSL function for creating a triplanar textures node.
  19889. *
  19890. * @function
  19891. * @param {Node} textureXNode - First texture node.
  19892. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19893. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19894. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19895. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19896. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19897. * @returns {TriplanarTexturesNode}
  19898. */
  19899. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  19900. /** @module ReflectorNode **/
  19901. const _reflectorPlane = new Plane();
  19902. const _normal = new Vector3();
  19903. const _reflectorWorldPosition = new Vector3();
  19904. const _cameraWorldPosition = new Vector3();
  19905. const _rotationMatrix = new Matrix4();
  19906. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  19907. const clipPlane = new Vector4();
  19908. const _view = new Vector3();
  19909. const _target = new Vector3();
  19910. const _q = new Vector4();
  19911. const _size$2 = new Vector2();
  19912. const _defaultRT = new RenderTarget();
  19913. const _defaultUV = screenUV.flipX();
  19914. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  19915. let _inReflector = false;
  19916. /**
  19917. * This node can be used to implement mirror-like flat reflective surfaces.
  19918. *
  19919. * ```js
  19920. * const groundReflector = reflector();
  19921. * material.colorNode = groundReflector;
  19922. *
  19923. * const plane = new Mesh( geometry, material );
  19924. * plane.add( groundReflector.target );
  19925. * ```
  19926. *
  19927. * @augments module:TextureNode~TextureNode
  19928. */
  19929. class ReflectorNode extends TextureNode {
  19930. static get type() {
  19931. return 'ReflectorNode';
  19932. }
  19933. /**
  19934. * Constructs a new reflector node.
  19935. *
  19936. * @param {Object} [parameters={}] - An object holding configuration parameters.
  19937. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  19938. * @param {Number} [parameters.resolution=1] - The resolution scale.
  19939. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  19940. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  19941. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  19942. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  19943. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  19944. */
  19945. constructor( parameters = {} ) {
  19946. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  19947. /**
  19948. * A reference to the internal reflector base node which holds the actual implementation.
  19949. *
  19950. * @private
  19951. * @type {ReflectorBaseNode?}
  19952. * @default null
  19953. */
  19954. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  19955. /**
  19956. * A reference to the internal depth node.
  19957. *
  19958. * @private
  19959. * @type {Node?}
  19960. * @default null
  19961. */
  19962. this._depthNode = null;
  19963. this.setUpdateMatrix( false );
  19964. }
  19965. /**
  19966. * A reference to the internal reflector node.
  19967. *
  19968. * @type {ReflectorBaseNode}
  19969. */
  19970. get reflector() {
  19971. return this._reflectorBaseNode;
  19972. }
  19973. /**
  19974. * A reference to 3D object the reflector is linked to.
  19975. *
  19976. * @type {Object3D}
  19977. */
  19978. get target() {
  19979. return this._reflectorBaseNode.target;
  19980. }
  19981. /**
  19982. * Returns a node representing the mirror's depth. That can be used
  19983. * to implement more advanced reflection effects like distance attenuation.
  19984. *
  19985. * @return {Node} The depth node.
  19986. */
  19987. getDepthNode() {
  19988. if ( this._depthNode === null ) {
  19989. if ( this._reflectorBaseNode.depth !== true ) {
  19990. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  19991. }
  19992. this._depthNode = nodeObject( new ReflectorNode( {
  19993. defaultTexture: _defaultRT.depthTexture,
  19994. reflector: this._reflectorBaseNode
  19995. } ) );
  19996. }
  19997. return this._depthNode;
  19998. }
  19999. setup( builder ) {
  20000. // ignore if used in post-processing
  20001. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  20002. return super.setup( builder );
  20003. }
  20004. clone() {
  20005. const texture = new this.constructor( this.reflectorNode );
  20006. texture._reflectorBaseNode = this._reflectorBaseNode;
  20007. return texture;
  20008. }
  20009. }
  20010. /**
  20011. * Holds the actual implementation of the reflector.
  20012. *
  20013. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  20014. * in `ReflectorNode`, see #29619.
  20015. *
  20016. * @private
  20017. * @augments Node
  20018. */
  20019. class ReflectorBaseNode extends Node {
  20020. static get type() {
  20021. return 'ReflectorBaseNode';
  20022. }
  20023. /**
  20024. * Constructs a new reflector base node.
  20025. *
  20026. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  20027. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20028. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20029. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20030. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20031. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20032. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20033. */
  20034. constructor( textureNode, parameters = {} ) {
  20035. super();
  20036. const {
  20037. target = new Object3D(),
  20038. resolution = 1,
  20039. generateMipmaps = false,
  20040. bounces = true,
  20041. depth = false
  20042. } = parameters;
  20043. /**
  20044. * Represents the rendered reflections as a texture node.
  20045. *
  20046. * @type {TextureNode}
  20047. */
  20048. this.textureNode = textureNode;
  20049. /**
  20050. * The 3D object the reflector is linked to.
  20051. *
  20052. * @type {Object3D}
  20053. * @default {new Object3D()}
  20054. */
  20055. this.target = target;
  20056. /**
  20057. * The resolution scale.
  20058. *
  20059. * @type {Number}
  20060. * @default {1}
  20061. */
  20062. this.resolution = resolution;
  20063. /**
  20064. * Whether mipmaps should be generated or not.
  20065. *
  20066. * @type {Boolean}
  20067. * @default {false}
  20068. */
  20069. this.generateMipmaps = generateMipmaps;
  20070. /**
  20071. * Whether reflectors can render other reflector nodes or not.
  20072. *
  20073. * @type {Boolean}
  20074. * @default {true}
  20075. */
  20076. this.bounces = bounces;
  20077. /**
  20078. * Whether depth data should be generated or not.
  20079. *
  20080. * @type {Boolean}
  20081. * @default {false}
  20082. */
  20083. this.depth = depth;
  20084. /**
  20085. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  20086. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  20087. *
  20088. * @type {String}
  20089. * @default 'render'
  20090. */
  20091. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  20092. /**
  20093. * Weak map for managing virtual cameras.
  20094. *
  20095. * @type {WeakMap<Camera, Camera>}
  20096. */
  20097. this.virtualCameras = new WeakMap();
  20098. /**
  20099. * Weak map for managing render targets.
  20100. *
  20101. * @type {WeakMap<Camera, RenderTarget>}
  20102. */
  20103. this.renderTargets = new WeakMap();
  20104. }
  20105. /**
  20106. * Updates the resolution of the internal render target.
  20107. *
  20108. * @private
  20109. * @param {RenderTarget} renderTarget - The render target to resize.
  20110. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  20111. */
  20112. _updateResolution( renderTarget, renderer ) {
  20113. const resolution = this.resolution;
  20114. renderer.getDrawingBufferSize( _size$2 );
  20115. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  20116. }
  20117. setup( builder ) {
  20118. this._updateResolution( _defaultRT, builder.renderer );
  20119. return super.setup( builder );
  20120. }
  20121. /**
  20122. * Returns a virtual camera for the given camera. The virtual camera is used to
  20123. * render the scene from the reflector's view so correct reflections can be produced.
  20124. *
  20125. * @param {Camera} camera - The scene's camera.
  20126. * @return {Camera} The corresponding virtual camera.
  20127. */
  20128. getVirtualCamera( camera ) {
  20129. let virtualCamera = this.virtualCameras.get( camera );
  20130. if ( virtualCamera === undefined ) {
  20131. virtualCamera = camera.clone();
  20132. this.virtualCameras.set( camera, virtualCamera );
  20133. }
  20134. return virtualCamera;
  20135. }
  20136. /**
  20137. * Returns a render target for the given camera. The reflections are rendered
  20138. * into this render target.
  20139. *
  20140. * @param {Camera} camera - The scene's camera.
  20141. * @return {RenderTarget} The render target.
  20142. */
  20143. getRenderTarget( camera ) {
  20144. let renderTarget = this.renderTargets.get( camera );
  20145. if ( renderTarget === undefined ) {
  20146. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  20147. if ( this.generateMipmaps === true ) {
  20148. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  20149. renderTarget.texture.generateMipmaps = true;
  20150. }
  20151. if ( this.depth === true ) {
  20152. renderTarget.depthTexture = new DepthTexture();
  20153. }
  20154. this.renderTargets.set( camera, renderTarget );
  20155. }
  20156. return renderTarget;
  20157. }
  20158. updateBefore( frame ) {
  20159. if ( this.bounces === false && _inReflector ) return false;
  20160. _inReflector = true;
  20161. const { scene, camera, renderer, material } = frame;
  20162. const { target } = this;
  20163. const virtualCamera = this.getVirtualCamera( camera );
  20164. const renderTarget = this.getRenderTarget( virtualCamera );
  20165. renderer.getDrawingBufferSize( _size$2 );
  20166. this._updateResolution( renderTarget, renderer );
  20167. //
  20168. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  20169. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  20170. _rotationMatrix.extractRotation( target.matrixWorld );
  20171. _normal.set( 0, 0, 1 );
  20172. _normal.applyMatrix4( _rotationMatrix );
  20173. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  20174. // Avoid rendering when reflector is facing away
  20175. if ( _view.dot( _normal ) > 0 ) return;
  20176. _view.reflect( _normal ).negate();
  20177. _view.add( _reflectorWorldPosition );
  20178. _rotationMatrix.extractRotation( camera.matrixWorld );
  20179. _lookAtPosition.set( 0, 0, - 1 );
  20180. _lookAtPosition.applyMatrix4( _rotationMatrix );
  20181. _lookAtPosition.add( _cameraWorldPosition );
  20182. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  20183. _target.reflect( _normal ).negate();
  20184. _target.add( _reflectorWorldPosition );
  20185. //
  20186. virtualCamera.coordinateSystem = camera.coordinateSystem;
  20187. virtualCamera.position.copy( _view );
  20188. virtualCamera.up.set( 0, 1, 0 );
  20189. virtualCamera.up.applyMatrix4( _rotationMatrix );
  20190. virtualCamera.up.reflect( _normal );
  20191. virtualCamera.lookAt( _target );
  20192. virtualCamera.near = camera.near;
  20193. virtualCamera.far = camera.far;
  20194. virtualCamera.updateMatrixWorld();
  20195. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  20196. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  20197. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  20198. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  20199. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  20200. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  20201. const projectionMatrix = virtualCamera.projectionMatrix;
  20202. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  20203. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  20204. _q.z = - 1.0;
  20205. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  20206. // Calculate the scaled plane vector
  20207. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  20208. const clipBias = 0;
  20209. // Replacing the third row of the projection matrix
  20210. projectionMatrix.elements[ 2 ] = clipPlane.x;
  20211. projectionMatrix.elements[ 6 ] = clipPlane.y;
  20212. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  20213. projectionMatrix.elements[ 14 ] = clipPlane.w;
  20214. //
  20215. this.textureNode.value = renderTarget.texture;
  20216. if ( this.depth === true ) {
  20217. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  20218. }
  20219. material.visible = false;
  20220. const currentRenderTarget = renderer.getRenderTarget();
  20221. const currentMRT = renderer.getMRT();
  20222. const currentAutoClear = renderer.autoClear;
  20223. renderer.setMRT( null );
  20224. renderer.setRenderTarget( renderTarget );
  20225. renderer.autoClear = true;
  20226. renderer.render( scene, virtualCamera );
  20227. renderer.setMRT( currentMRT );
  20228. renderer.setRenderTarget( currentRenderTarget );
  20229. renderer.autoClear = currentAutoClear;
  20230. material.visible = true;
  20231. _inReflector = false;
  20232. }
  20233. }
  20234. /**
  20235. * TSL function for creating a reflector node.
  20236. *
  20237. * @function
  20238. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20239. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20240. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20241. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20242. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20243. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20244. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20245. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20246. * @returns {ReflectorNode}
  20247. */
  20248. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  20249. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  20250. /**
  20251. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  20252. *
  20253. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  20254. *
  20255. * @private
  20256. * @augments BufferGeometry
  20257. */
  20258. class QuadGeometry extends BufferGeometry {
  20259. /**
  20260. * Constructs a new quad geometry.
  20261. *
  20262. * @param {Boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  20263. */
  20264. constructor( flipY = false ) {
  20265. super();
  20266. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  20267. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  20268. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  20269. }
  20270. }
  20271. const _geometry = /*@__PURE__*/ new QuadGeometry();
  20272. /**
  20273. * This module is a helper for passes which need to render a full
  20274. * screen effect which is quite common in context of post processing.
  20275. *
  20276. * The intended usage is to reuse a single quad mesh for rendering
  20277. * subsequent passes by just reassigning the `material` reference.
  20278. *
  20279. * @augments BufferGeometry
  20280. */
  20281. class QuadMesh extends Mesh {
  20282. /**
  20283. * Constructs a new quad mesh.
  20284. *
  20285. * @param {Material?} [material=null] - The material to render the quad mesh with.
  20286. */
  20287. constructor( material = null ) {
  20288. super( _geometry, material );
  20289. /**
  20290. * The camera to render the quad mesh with.
  20291. *
  20292. * @type {OrthographicCamera}
  20293. * @readonly
  20294. */
  20295. this.camera = _camera;
  20296. /**
  20297. * This flag can be used for type testing.
  20298. *
  20299. * @type {Boolean}
  20300. * @readonly
  20301. * @default true
  20302. */
  20303. this.isQuadMesh = true;
  20304. }
  20305. /**
  20306. * Async version of `render()`.
  20307. *
  20308. * @async
  20309. * @param {Renderer} renderer - The renderer.
  20310. * @return {Promise} A Promise that resolves when the render has been finished.
  20311. */
  20312. async renderAsync( renderer ) {
  20313. return renderer.renderAsync( this, _camera );
  20314. }
  20315. /**
  20316. * Renders the quad mesh
  20317. *
  20318. * @param {Renderer} renderer - The renderer.
  20319. */
  20320. render( renderer ) {
  20321. renderer.render( this, _camera );
  20322. }
  20323. }
  20324. /** @module RTTNode **/
  20325. const _size$1 = /*@__PURE__*/ new Vector2();
  20326. /**
  20327. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  20328. * This module is especially relevant in context of post processing where certain nodes require
  20329. * texture input for their effects. With the helper function `convertToTexture()` which is based
  20330. * on this module, the node system can automatically ensure texture input if required.
  20331. *
  20332. * @augments module:TextureNode~TextureNode
  20333. */
  20334. class RTTNode extends TextureNode {
  20335. static get type() {
  20336. return 'RTTNode';
  20337. }
  20338. /**
  20339. * Constructs a new RTT node.
  20340. *
  20341. * @param {Node} node - The node to render a texture with.
  20342. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20343. * @param {Number?} [height=null] - The height of the internal render target.
  20344. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20345. */
  20346. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  20347. const renderTarget = new RenderTarget( width, height, options );
  20348. super( renderTarget.texture, uv() );
  20349. /**
  20350. * The node to render a texture with.
  20351. *
  20352. * @type {Node}
  20353. */
  20354. this.node = node;
  20355. /**
  20356. * The width of the internal render target.
  20357. * If not width is applied, the render target is automatically resized.
  20358. *
  20359. * @type {Number?}
  20360. * @default null
  20361. */
  20362. this.width = width;
  20363. /**
  20364. * The height of the internal render target.
  20365. *
  20366. * @type {Number?}
  20367. * @default null
  20368. */
  20369. this.height = height;
  20370. /**
  20371. * The pixel ratio
  20372. *
  20373. * @type {Number}
  20374. * @default 1
  20375. */
  20376. this.pixelRatio = 1;
  20377. /**
  20378. * The render target
  20379. *
  20380. * @type {RenderTarget}
  20381. */
  20382. this.renderTarget = renderTarget;
  20383. /**
  20384. * Whether the texture requires an update or not.
  20385. *
  20386. * @type {Boolean}
  20387. * @default true
  20388. */
  20389. this.textureNeedsUpdate = true;
  20390. /**
  20391. * Whether the texture should automatically be updated or not.
  20392. *
  20393. * @type {Boolean}
  20394. * @default true
  20395. */
  20396. this.autoUpdate = true;
  20397. /**
  20398. * The node which is used with the quad mesh for RTT.
  20399. *
  20400. * @private
  20401. * @type {Node}
  20402. * @default null
  20403. */
  20404. this._rttNode = null;
  20405. /**
  20406. * The internal quad mesh for RTT.
  20407. *
  20408. * @private
  20409. * @type {QuadMesh}
  20410. */
  20411. this._quadMesh = new QuadMesh( new NodeMaterial() );
  20412. /**
  20413. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  20414. * the texture once per render in its {@link RTTNode#updateBefore} method.
  20415. *
  20416. * @type {String}
  20417. * @default 'render'
  20418. */
  20419. this.updateBeforeType = NodeUpdateType.RENDER;
  20420. }
  20421. /**
  20422. * Whether the internal render target should automatically be resized or not.
  20423. *
  20424. * @type {Boolean}
  20425. * @readonly
  20426. * @default true
  20427. */
  20428. get autoSize() {
  20429. return this.width === null;
  20430. }
  20431. setup( builder ) {
  20432. this._rttNode = this.node.context( builder.getSharedContext() );
  20433. this._quadMesh.material.name = 'RTT';
  20434. this._quadMesh.material.needsUpdate = true;
  20435. return super.setup( builder );
  20436. }
  20437. /**
  20438. * Sets the size of the internal render target
  20439. *
  20440. * @param {Number} width - The width to set.
  20441. * @param {Number} height - The width to set.
  20442. */
  20443. setSize( width, height ) {
  20444. this.width = width;
  20445. this.height = height;
  20446. const effectiveWidth = width * this.pixelRatio;
  20447. const effectiveHeight = height * this.pixelRatio;
  20448. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  20449. this.textureNeedsUpdate = true;
  20450. }
  20451. /**
  20452. * Sets the pixel ratio. This will also resize the render target.
  20453. *
  20454. * @param {Number} pixelRatio - The pixel ratio to set.
  20455. */
  20456. setPixelRatio( pixelRatio ) {
  20457. this.pixelRatio = pixelRatio;
  20458. this.setSize( this.width, this.height );
  20459. }
  20460. updateBefore( { renderer } ) {
  20461. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  20462. this.textureNeedsUpdate = false;
  20463. //
  20464. if ( this.autoSize === true ) {
  20465. this.pixelRatio = renderer.getPixelRatio();
  20466. const size = renderer.getSize( _size$1 );
  20467. this.setSize( size.width, size.height );
  20468. }
  20469. //
  20470. this._quadMesh.material.fragmentNode = this._rttNode;
  20471. //
  20472. const currentRenderTarget = renderer.getRenderTarget();
  20473. renderer.setRenderTarget( this.renderTarget );
  20474. this._quadMesh.render( renderer );
  20475. renderer.setRenderTarget( currentRenderTarget );
  20476. }
  20477. clone() {
  20478. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  20479. newNode.sampler = this.sampler;
  20480. newNode.referenceNode = this;
  20481. return newNode;
  20482. }
  20483. }
  20484. /**
  20485. * TSL function for creating a RTT node.
  20486. *
  20487. * @function
  20488. * @param {Node} node - The node to render a texture with.
  20489. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20490. * @param {Number?} [height=null] - The height of the internal render target.
  20491. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20492. * @returns {RTTNode}
  20493. */
  20494. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  20495. /**
  20496. * TSL function for converting nodes to textures nodes.
  20497. *
  20498. * @function
  20499. * @param {Node} node - The node to render a texture with.
  20500. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20501. * @param {Number?} [height=null] - The height of the internal render target.
  20502. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20503. * @returns {RTTNode}
  20504. */
  20505. const convertToTexture = ( node, ...params ) => {
  20506. if ( node.isTextureNode ) return node;
  20507. if ( node.isPassNode ) return node.getTextureNode();
  20508. return rtt( node, ...params );
  20509. };
  20510. /** @module PostProcessingUtils **/
  20511. /**
  20512. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  20513. * depth value and the camera's inverse projection matrix.
  20514. *
  20515. * @method
  20516. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  20517. * @param {Node<float>} depth - The fragment's depth value.
  20518. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20519. * @return {Node<vec3>} The fragments position in view space.
  20520. */
  20521. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  20522. let clipSpacePosition;
  20523. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  20524. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  20525. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  20526. } else {
  20527. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  20528. }
  20529. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  20530. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  20531. } );
  20532. /**
  20533. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  20534. * and the camera's projection matrix
  20535. *
  20536. * @method
  20537. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  20538. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  20539. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  20540. */
  20541. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  20542. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  20543. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  20544. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  20545. } );
  20546. /**
  20547. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  20548. * target is available or if flat surface normals are required.
  20549. *
  20550. * @method
  20551. * @param {Node<vec2>} uv - The texture coordinate.
  20552. * @param {DepthTexture} depthTexture - The depth texture.
  20553. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20554. * @return {Node<vec3>} The computed normal vector.
  20555. */
  20556. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  20557. const size = textureSize( textureLoad( depthTexture ) );
  20558. const p = ivec2( uv.mul( size ) ).toVar();
  20559. const c0 = textureLoad( depthTexture, p ).toVar();
  20560. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  20561. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  20562. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  20563. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  20564. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  20565. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  20566. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  20567. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  20568. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  20569. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  20570. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  20571. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  20572. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  20573. 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 ) ) );
  20574. 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 ) ) );
  20575. return normalize( cross( dpdx, dpdy ) );
  20576. } );
  20577. /**
  20578. * This special type of instanced buffer attribute is intended for compute shaders.
  20579. * In earlier three.js versions it was only possible to update attribute data
  20580. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20581. * new material system and renderer it is now possible to use compute shaders
  20582. * to compute the data for an attribute more efficiently on the GPU.
  20583. *
  20584. * The idea is to create an instance of this class and provide it as an input
  20585. * to {@link module:StorageBufferNode}.
  20586. *
  20587. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20588. *
  20589. * @augments InstancedBufferAttribute
  20590. */
  20591. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  20592. /**
  20593. * Constructs a new storage instanced buffer attribute.
  20594. *
  20595. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20596. * The subsequent parameters are then obsolete.
  20597. * @param {Number} itemSize - The item size.
  20598. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20599. */
  20600. constructor( count, itemSize, typeClass = Float32Array ) {
  20601. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20602. super( array, itemSize );
  20603. /**
  20604. * This flag can be used for type testing.
  20605. *
  20606. * @type {Boolean}
  20607. * @readonly
  20608. * @default true
  20609. */
  20610. this.isStorageInstancedBufferAttribute = true;
  20611. }
  20612. }
  20613. /**
  20614. * This special type of buffer attribute is intended for compute shaders.
  20615. * In earlier three.js versions it was only possible to update attribute data
  20616. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20617. * new material system and renderer it is now possible to use compute shaders
  20618. * to compute the data for an attribute more efficiently on the GPU.
  20619. *
  20620. * The idea is to create an instance of this class and provide it as an input
  20621. * to {@link module:StorageBufferNode}.
  20622. *
  20623. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20624. *
  20625. * @augments BufferAttribute
  20626. */
  20627. class StorageBufferAttribute extends BufferAttribute {
  20628. /**
  20629. * Constructs a new storage buffer attribute.
  20630. *
  20631. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20632. * The subsequent parameters are then obsolete.
  20633. * @param {Number} itemSize - The item size.
  20634. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20635. */
  20636. constructor( count, itemSize, typeClass = Float32Array ) {
  20637. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20638. super( array, itemSize );
  20639. /**
  20640. * This flag can be used for type testing.
  20641. *
  20642. * @type {Boolean}
  20643. * @readonly
  20644. * @default true
  20645. */
  20646. this.isStorageBufferAttribute = true;
  20647. }
  20648. }
  20649. /** @module StorageArrayElementNode **/
  20650. /**
  20651. * This class enables element access on instances of {@link StorageBufferNode}.
  20652. * In most cases, it is indirectly used when accessing elements with the
  20653. * {@link StorageBufferNode#element} method.
  20654. *
  20655. * ```js
  20656. * const position = positionStorage.element( instanceIndex );
  20657. * ```
  20658. *
  20659. * @augments ArrayElementNode
  20660. */
  20661. class StorageArrayElementNode extends ArrayElementNode {
  20662. static get type() {
  20663. return 'StorageArrayElementNode';
  20664. }
  20665. /**
  20666. * Constructs storage buffer element node.
  20667. *
  20668. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20669. * @param {Node} indexNode - The index node that defines the element access.
  20670. */
  20671. constructor( storageBufferNode, indexNode ) {
  20672. super( storageBufferNode, indexNode );
  20673. /**
  20674. * This flag can be used for type testing.
  20675. *
  20676. * @type {Boolean}
  20677. * @readonly
  20678. * @default true
  20679. */
  20680. this.isStorageArrayElementNode = true;
  20681. }
  20682. /**
  20683. * The storage buffer node.
  20684. *
  20685. * @param {Node} value
  20686. * @type {StorageBufferNode}
  20687. */
  20688. set storageBufferNode( value ) {
  20689. this.node = value;
  20690. }
  20691. get storageBufferNode() {
  20692. return this.node;
  20693. }
  20694. setup( builder ) {
  20695. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20696. if ( this.node.isPBO === true ) {
  20697. builder.setupPBO( this.node );
  20698. }
  20699. }
  20700. return super.setup( builder );
  20701. }
  20702. generate( builder, output ) {
  20703. let snippet;
  20704. const isAssignContext = builder.context.assign;
  20705. //
  20706. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20707. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  20708. snippet = builder.generatePBO( this );
  20709. } else {
  20710. snippet = this.node.build( builder );
  20711. }
  20712. } else {
  20713. snippet = super.generate( builder );
  20714. }
  20715. if ( isAssignContext !== true ) {
  20716. const type = this.getNodeType( builder );
  20717. snippet = builder.format( snippet, type, output );
  20718. }
  20719. return snippet;
  20720. }
  20721. }
  20722. /**
  20723. * TSL function for creating a storage element node.
  20724. *
  20725. * @function
  20726. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20727. * @param {Node} indexNode - The index node that defines the element access.
  20728. * @returns {StorageArrayElementNode}
  20729. */
  20730. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  20731. /** @module StorageBufferNode **/
  20732. /**
  20733. * This node is used in context of compute shaders and allows to define a
  20734. * storage buffer for data. A typical workflow is to create instances of
  20735. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  20736. * setup up a compute shader that writes into the buffers and then convert
  20737. * the storage buffers to attribute nodes for rendering.
  20738. *
  20739. * ```js
  20740. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  20741. *
  20742. * const computeInit = Fn( () => { // the compute shader
  20743. *
  20744. * const position = positionBuffer.element( instanceIndex );
  20745. *
  20746. * // compute position data
  20747. *
  20748. * position.x = 1;
  20749. * position.y = 1;
  20750. * position.z = 1;
  20751. *
  20752. * } )().compute( particleCount );
  20753. *
  20754. * const particleMaterial = new THREE.SpriteNodeMaterial();
  20755. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20756. *
  20757. * renderer.computeAsync( computeInit );
  20758. *
  20759. * ```
  20760. *
  20761. * @augments BufferNode
  20762. */
  20763. class StorageBufferNode extends BufferNode {
  20764. static get type() {
  20765. return 'StorageBufferNode';
  20766. }
  20767. /**
  20768. * Constructs a new storage buffer node.
  20769. *
  20770. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20771. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  20772. * @param {Number} [bufferCount=0] - The buffer count.
  20773. */
  20774. constructor( value, bufferType = null, bufferCount = 0 ) {
  20775. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  20776. bufferType = getTypeFromLength( value.itemSize );
  20777. bufferCount = value.count;
  20778. }
  20779. super( value, bufferType, bufferCount );
  20780. /**
  20781. * This flag can be used for type testing.
  20782. *
  20783. * @type {Boolean}
  20784. * @readonly
  20785. * @default true
  20786. */
  20787. this.isStorageBufferNode = true;
  20788. /**
  20789. * The access type of the texture node.
  20790. *
  20791. * @type {String}
  20792. * @default 'readWrite'
  20793. */
  20794. this.access = NodeAccess.READ_WRITE;
  20795. /**
  20796. * Whether the node is atomic or not.
  20797. *
  20798. * @type {Boolean}
  20799. * @default false
  20800. */
  20801. this.isAtomic = false;
  20802. /**
  20803. * Whether the node represents a PBO or not.
  20804. * Only relevant for WebGL.
  20805. *
  20806. * @type {Boolean}
  20807. * @default false
  20808. */
  20809. this.isPBO = false;
  20810. /**
  20811. * A reference to the internal buffer attribute node.
  20812. *
  20813. * @type {BufferAttributeNode?}
  20814. * @default null
  20815. */
  20816. this._attribute = null;
  20817. /**
  20818. * A reference to the internal varying node.
  20819. *
  20820. * @type {VaryingNode?}
  20821. * @default null
  20822. */
  20823. this._varying = null;
  20824. /**
  20825. * `StorageBufferNode` sets this property to `true` by default.
  20826. *
  20827. * @type {Boolean}
  20828. * @default true
  20829. */
  20830. this.global = true;
  20831. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  20832. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  20833. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  20834. else value.isStorageBufferAttribute = true;
  20835. }
  20836. }
  20837. /**
  20838. * This method is overwritten since the buffer data might be shared
  20839. * and thus the hash should be shared as well.
  20840. *
  20841. * @param {NodeBuilder} builder - The current node builder.
  20842. * @return {String} The hash.
  20843. */
  20844. getHash( builder ) {
  20845. if ( this.bufferCount === 0 ) {
  20846. let bufferData = builder.globalCache.getData( this.value );
  20847. if ( bufferData === undefined ) {
  20848. bufferData = {
  20849. node: this
  20850. };
  20851. builder.globalCache.setData( this.value, bufferData );
  20852. }
  20853. return bufferData.node.uuid;
  20854. }
  20855. return this.uuid;
  20856. }
  20857. /**
  20858. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  20859. *
  20860. * @param {NodeBuilder} builder - The current node builder.
  20861. * @return {String} The input type.
  20862. */
  20863. getInputType( /*builder*/ ) {
  20864. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  20865. }
  20866. /**
  20867. * Enables element access with the given index node.
  20868. *
  20869. * @param {IndexNode} indexNode - The index node.
  20870. * @return {StorageArrayElementNode} A node representing the element access.
  20871. */
  20872. element( indexNode ) {
  20873. return storageElement( this, indexNode );
  20874. }
  20875. /**
  20876. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  20877. *
  20878. * @param {Boolean} value - The value so set.
  20879. * @return {StorageBufferNode} A reference to this node.
  20880. */
  20881. setPBO( value ) {
  20882. this.isPBO = value;
  20883. return this;
  20884. }
  20885. /**
  20886. * Returns the `isPBO` value.
  20887. *
  20888. * @return {Boolean} Whether the node represents a PBO or not.
  20889. */
  20890. getPBO() {
  20891. return this.isPBO;
  20892. }
  20893. /**
  20894. * Defines the node access.
  20895. *
  20896. * @param {String} value - The node access.
  20897. * @return {StorageBufferNode} A reference to this node.
  20898. */
  20899. setAccess( value ) {
  20900. this.access = value;
  20901. return this;
  20902. }
  20903. /**
  20904. * Convenience method for configuring a read-only node access.
  20905. *
  20906. * @return {StorageBufferNode} A reference to this node.
  20907. */
  20908. toReadOnly() {
  20909. return this.setAccess( NodeAccess.READ_ONLY );
  20910. }
  20911. /**
  20912. * Defines whether the node is atomic or not.
  20913. *
  20914. * @param {Boolean} value - The atomic flag.
  20915. * @return {StorageBufferNode} A reference to this node.
  20916. */
  20917. setAtomic( value ) {
  20918. this.isAtomic = value;
  20919. return this;
  20920. }
  20921. /**
  20922. * Convenience method for making this node atomic.
  20923. *
  20924. * @return {StorageBufferNode} A reference to this node.
  20925. */
  20926. toAtomic() {
  20927. return this.setAtomic( true );
  20928. }
  20929. /**
  20930. * Returns attribute data for this storage buffer node.
  20931. *
  20932. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  20933. */
  20934. getAttributeData() {
  20935. if ( this._attribute === null ) {
  20936. this._attribute = bufferAttribute( this.value );
  20937. this._varying = varying( this._attribute );
  20938. }
  20939. return {
  20940. attribute: this._attribute,
  20941. varying: this._varying
  20942. };
  20943. }
  20944. /**
  20945. * This method is overwritten since the node type from the availability of storage buffers
  20946. * and the attribute data.
  20947. *
  20948. * @param {NodeBuilder} builder - The current node builder.
  20949. * @return {String} The node type.
  20950. */
  20951. getNodeType( builder ) {
  20952. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  20953. return super.getNodeType( builder );
  20954. }
  20955. const { attribute } = this.getAttributeData();
  20956. return attribute.getNodeType( builder );
  20957. }
  20958. /**
  20959. * Generates the code snippet of the storage buffer node.
  20960. *
  20961. * @param {NodeBuilder} builder - The current node builder.
  20962. * @return {String} The generated code snippet.
  20963. */
  20964. generate( builder ) {
  20965. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  20966. return super.generate( builder );
  20967. }
  20968. const { attribute, varying } = this.getAttributeData();
  20969. const output = varying.build( builder );
  20970. builder.registerTransform( output, attribute );
  20971. return output;
  20972. }
  20973. }
  20974. /**
  20975. * TSL function for creating a storage buffer node.
  20976. *
  20977. * @function
  20978. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20979. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  20980. * @param {Number} [count=0] - The buffer count.
  20981. * @returns {StorageBufferNode}
  20982. */
  20983. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  20984. /**
  20985. * @function
  20986. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  20987. *
  20988. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20989. * @param {String?} type - The buffer type (e.g. `'vec3'`).
  20990. * @param {Number} count - The buffer count.
  20991. * @returns {StorageBufferNode}
  20992. */
  20993. const storageObject = ( value, type, count ) => { // @deprecated, r171
  20994. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  20995. return storage( value, type, count ).setPBO( true );
  20996. };
  20997. /** @module Arrays **/
  20998. /**
  20999. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  21000. *
  21001. * @function
  21002. * @param {Number} count - The data count.
  21003. * @param {String} [type='float'] - The data type.
  21004. * @returns {StorageBufferNode}
  21005. */
  21006. const attributeArray = ( count, type = 'float' ) => {
  21007. const itemSize = getLengthFromType( type );
  21008. const typedArray = getTypedArrayFromType( type );
  21009. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  21010. const node = storage( buffer, type, count );
  21011. return node;
  21012. };
  21013. /**
  21014. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  21015. *
  21016. * @function
  21017. * @param {Number} count - The data count.
  21018. * @param {String} [type='float'] - The data type.
  21019. * @returns {StorageBufferNode}
  21020. */
  21021. const instancedArray = ( count, type = 'float' ) => {
  21022. const itemSize = getLengthFromType( type );
  21023. const typedArray = getTypedArrayFromType( type );
  21024. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  21025. const node = storage( buffer, type, count );
  21026. return node;
  21027. };
  21028. /** @module VertexColorNode **/
  21029. /**
  21030. * An attribute node for representing vertex colors.
  21031. *
  21032. * @augments module:AttributeNode~AttributeNode
  21033. */
  21034. class VertexColorNode extends AttributeNode {
  21035. static get type() {
  21036. return 'VertexColorNode';
  21037. }
  21038. /**
  21039. * Constructs a new vertex color node.
  21040. *
  21041. * @param {Number} [index=0] - The attribute index.
  21042. */
  21043. constructor( index = 0 ) {
  21044. super( null, 'vec4' );
  21045. /**
  21046. * This flag can be used for type testing.
  21047. *
  21048. * @type {Boolean}
  21049. * @readonly
  21050. * @default true
  21051. */
  21052. this.isVertexColorNode = true;
  21053. /**
  21054. * The attribute index to enable more than one sets of vertex colors.
  21055. *
  21056. * @type {Number}
  21057. * @default 0
  21058. */
  21059. this.index = index;
  21060. }
  21061. /**
  21062. * Overwrites the default implementation by honoring the attribute index.
  21063. *
  21064. * @param {NodeBuilder} builder - The current node builder.
  21065. * @return {String} The attribute name.
  21066. */
  21067. getAttributeName( /*builder*/ ) {
  21068. const index = this.index;
  21069. return 'color' + ( index > 0 ? index : '' );
  21070. }
  21071. generate( builder ) {
  21072. const attributeName = this.getAttributeName( builder );
  21073. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  21074. let result;
  21075. if ( geometryAttribute === true ) {
  21076. result = super.generate( builder );
  21077. } else {
  21078. // Vertex color fallback should be white
  21079. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  21080. }
  21081. return result;
  21082. }
  21083. serialize( data ) {
  21084. super.serialize( data );
  21085. data.index = this.index;
  21086. }
  21087. deserialize( data ) {
  21088. super.deserialize( data );
  21089. this.index = data.index;
  21090. }
  21091. }
  21092. /**
  21093. * TSL function for creating a reference node.
  21094. *
  21095. * @function
  21096. * @param {Number} index - The attribute index.
  21097. * @returns {VertexColorNode}
  21098. */
  21099. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  21100. /** @module PointUVNode **/
  21101. /**
  21102. * A node for representing the uv coordinates of points.
  21103. *
  21104. * Can only be used with a WebGL backend. In WebGPU, point
  21105. * primitives always have the size of one pixel and can thus
  21106. * can't be used as sprite-like objects that display textures.
  21107. *
  21108. * @augments Node
  21109. */
  21110. class PointUVNode extends Node {
  21111. static get type() {
  21112. return 'PointUVNode';
  21113. }
  21114. /**
  21115. * Constructs a new point uv node.
  21116. */
  21117. constructor() {
  21118. super( 'vec2' );
  21119. /**
  21120. * This flag can be used for type testing.
  21121. *
  21122. * @type {Boolean}
  21123. * @readonly
  21124. * @default true
  21125. */
  21126. this.isPointUVNode = true;
  21127. }
  21128. generate( /*builder*/ ) {
  21129. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  21130. }
  21131. }
  21132. /**
  21133. * TSL object that represents the uv coordinates of points.
  21134. *
  21135. * @type {PointUVNode}
  21136. */
  21137. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  21138. const _e1 = /*@__PURE__*/ new Euler();
  21139. const _m1 = /*@__PURE__*/ new Matrix4();
  21140. /** @module SceneNode **/
  21141. /**
  21142. * This module allows access to a collection of scene properties. The following predefined TSL objects
  21143. * are available for easier use:
  21144. *
  21145. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  21146. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  21147. * - `backgroundRotation`: A node that represents the scene's background rotation.
  21148. *
  21149. * @augments Node
  21150. */
  21151. class SceneNode extends Node {
  21152. static get type() {
  21153. return 'SceneNode';
  21154. }
  21155. /**
  21156. * Constructs a new scene node.
  21157. *
  21158. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  21159. * @param {Scene?} [scene=null] - A reference to the scene.
  21160. */
  21161. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  21162. super();
  21163. /**
  21164. * The scope defines the type of scene property that is accessed.
  21165. *
  21166. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  21167. */
  21168. this.scope = scope;
  21169. /**
  21170. * A reference to the scene that is going to be accessed.
  21171. *
  21172. * @type {Scene?}
  21173. * @default null
  21174. */
  21175. this.scene = scene;
  21176. }
  21177. /**
  21178. * Depending on the scope, the method returns a different type of node that represents
  21179. * the respective scene property.
  21180. *
  21181. * @param {NodeBuilder} builder - The current node builder.
  21182. * @return {Node} The output node.
  21183. */
  21184. setup( builder ) {
  21185. const scope = this.scope;
  21186. const scene = this.scene !== null ? this.scene : builder.scene;
  21187. let output;
  21188. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  21189. output = reference( 'backgroundBlurriness', 'float', scene );
  21190. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  21191. output = reference( 'backgroundIntensity', 'float', scene );
  21192. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  21193. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  21194. const background = scene.background;
  21195. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  21196. _e1.copy( scene.backgroundRotation );
  21197. // accommodate left-handed frame
  21198. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  21199. _m1.makeRotationFromEuler( _e1 );
  21200. } else {
  21201. _m1.identity();
  21202. }
  21203. return _m1;
  21204. } );
  21205. } else {
  21206. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  21207. }
  21208. return output;
  21209. }
  21210. }
  21211. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  21212. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  21213. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  21214. /**
  21215. * TSL object that represents the scene's background blurriness.
  21216. *
  21217. * @type {SceneNode}
  21218. */
  21219. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  21220. /**
  21221. * TSL object that represents the scene's background intensity.
  21222. *
  21223. * @type {SceneNode}
  21224. */
  21225. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  21226. /**
  21227. * TSL object that represents the scene's background rotation.
  21228. *
  21229. * @type {SceneNode}
  21230. */
  21231. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  21232. /** @module StorageTextureNode **/
  21233. /**
  21234. * This special version of a texture node can be used to
  21235. * write data into a storage texture with a compute shader.
  21236. *
  21237. * ```js
  21238. * const storageTexture = new THREE.StorageTexture( width, height );
  21239. *
  21240. * const computeTexture = Fn( ( { storageTexture } ) => {
  21241. *
  21242. * const posX = instanceIndex.modInt( width );
  21243. * const posY = instanceIndex.div( width );
  21244. * const indexUV = uvec2( posX, posY );
  21245. *
  21246. * // generate RGB values
  21247. *
  21248. * const r = 1;
  21249. * const g = 1;
  21250. * const b = 1;
  21251. *
  21252. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  21253. *
  21254. * } );
  21255. *
  21256. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  21257. * renderer.computeAsync( computeNode );
  21258. * ```
  21259. *
  21260. * This node can only be used with a WebGPU backend.
  21261. *
  21262. * @augments module:TextureNode~TextureNode
  21263. */
  21264. class StorageTextureNode extends TextureNode {
  21265. static get type() {
  21266. return 'StorageTextureNode';
  21267. }
  21268. /**
  21269. * Constructs a new storage texture node.
  21270. *
  21271. * @param {StorageTexture} value - The storage texture.
  21272. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21273. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21274. */
  21275. constructor( value, uvNode, storeNode = null ) {
  21276. super( value, uvNode );
  21277. /**
  21278. * The value node that should be stored in the texture.
  21279. *
  21280. * @type {Node?}
  21281. * @default null
  21282. */
  21283. this.storeNode = storeNode;
  21284. /**
  21285. * This flag can be used for type testing.
  21286. *
  21287. * @type {Boolean}
  21288. * @readonly
  21289. * @default true
  21290. */
  21291. this.isStorageTextureNode = true;
  21292. /**
  21293. * The access type of the texture node.
  21294. *
  21295. * @type {String}
  21296. * @default 'writeOnly'
  21297. */
  21298. this.access = NodeAccess.WRITE_ONLY;
  21299. }
  21300. /**
  21301. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  21302. *
  21303. * @param {NodeBuilder} builder - The current node builder.
  21304. * @return {String} The input type.
  21305. */
  21306. getInputType( /*builder*/ ) {
  21307. return 'storageTexture';
  21308. }
  21309. setup( builder ) {
  21310. super.setup( builder );
  21311. const properties = builder.getNodeProperties( this );
  21312. properties.storeNode = this.storeNode;
  21313. }
  21314. /**
  21315. * Defines the node access.
  21316. *
  21317. * @param {String} value - The node access.
  21318. * @return {StorageTextureNode} A reference to this node.
  21319. */
  21320. setAccess( value ) {
  21321. this.access = value;
  21322. return this;
  21323. }
  21324. /**
  21325. * Generates the code snippet of the stroge node. If no `storeNode`
  21326. * is defined, the texture node is generated as normal texture.
  21327. *
  21328. * @param {NodeBuilder} builder - The current node builder.
  21329. * @param {String} output - The current output.
  21330. * @return {String} The generated code snippet.
  21331. */
  21332. generate( builder, output ) {
  21333. let snippet;
  21334. if ( this.storeNode !== null ) {
  21335. snippet = this.generateStore( builder );
  21336. } else {
  21337. snippet = super.generate( builder, output );
  21338. }
  21339. return snippet;
  21340. }
  21341. /**
  21342. * Convenience method for configuring a read/write node access.
  21343. *
  21344. * @return {StorageTextureNode} A reference to this node.
  21345. */
  21346. toReadWrite() {
  21347. return this.setAccess( NodeAccess.READ_WRITE );
  21348. }
  21349. /**
  21350. * Convenience method for configuring a read-only node access.
  21351. *
  21352. * @return {StorageTextureNode} A reference to this node.
  21353. */
  21354. toReadOnly() {
  21355. return this.setAccess( NodeAccess.READ_ONLY );
  21356. }
  21357. /**
  21358. * Convenience method for configuring a write-only node access.
  21359. *
  21360. * @return {StorageTextureNode} A reference to this node.
  21361. */
  21362. toWriteOnly() {
  21363. return this.setAccess( NodeAccess.WRITE_ONLY );
  21364. }
  21365. /**
  21366. * Generates the code snippet of the storage texture node.
  21367. *
  21368. * @param {NodeBuilder} builder - The current node builder.
  21369. */
  21370. generateStore( builder ) {
  21371. const properties = builder.getNodeProperties( this );
  21372. const { uvNode, storeNode } = properties;
  21373. const textureProperty = super.generate( builder, 'property' );
  21374. const uvSnippet = uvNode.build( builder, 'uvec2' );
  21375. const storeSnippet = storeNode.build( builder, 'vec4' );
  21376. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  21377. builder.addLineFlowCode( snippet, this );
  21378. }
  21379. }
  21380. /**
  21381. * TSL function for creating a storage texture node.
  21382. *
  21383. * @function
  21384. * @param {StorageTexture} value - The storage texture.
  21385. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21386. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21387. * @returns {StorageTextureNode}
  21388. */
  21389. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  21390. /**
  21391. * TODO: Explain difference to `storageTexture()`.
  21392. *
  21393. * @function
  21394. * @param {StorageTexture} value - The storage texture.
  21395. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21396. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21397. * @returns {StorageTextureNode}
  21398. */
  21399. const textureStore = ( value, uvNode, storeNode ) => {
  21400. const node = storageTexture( value, uvNode, storeNode );
  21401. if ( storeNode !== null ) node.append();
  21402. return node;
  21403. };
  21404. /** @module UserDataNode **/
  21405. /**
  21406. * A special type of reference node that allows to link values in
  21407. * `userData` fields to node objects.
  21408. * ```js
  21409. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  21410. *
  21411. * const material = new THREE.SpriteNodeMaterial();
  21412. * material.rotationNode = userData( 'rotation', 'float' );
  21413. * ```
  21414. * Since `UserDataNode` is extended from {@link module:ReferenceNode~ReferenceNode}, the node value
  21415. * will automatically be updated when the `rotation` user data field changes.
  21416. *
  21417. * @augments module:ReferenceNode~ReferenceNode
  21418. */
  21419. class UserDataNode extends ReferenceNode {
  21420. static get type() {
  21421. return 'UserDataNode';
  21422. }
  21423. /**
  21424. * Constructs a new user data node.
  21425. *
  21426. * @param {String} property - The property name that should be referenced by the node.
  21427. * @param {String} inputType - The node data type of the reference.
  21428. * @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.
  21429. */
  21430. constructor( property, inputType, userData = null ) {
  21431. super( property, inputType, userData );
  21432. /**
  21433. * A reference to the `userData` object. If not provided, the `userData`
  21434. * property of the 3D object that uses the node material is evaluated.
  21435. *
  21436. * @type {Object?}
  21437. * @default null
  21438. */
  21439. this.userData = userData;
  21440. }
  21441. /**
  21442. * Overwritten to make sure {@link module:ReferenceNode~ReferenceNode#reference} points to the correct
  21443. * `userData` field.
  21444. *
  21445. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  21446. * @return {Object} A reference to the `userData` field.
  21447. */
  21448. updateReference( state ) {
  21449. this.reference = this.userData !== null ? this.userData : state.object.userData;
  21450. return this.reference;
  21451. }
  21452. }
  21453. /**
  21454. * TSL function for creating a user data node.
  21455. *
  21456. * @function
  21457. * @param {String} name - The property name that should be referenced by the node.
  21458. * @param {String} inputType - The node data type of the reference.
  21459. * @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.
  21460. * @returns {UserDataNode}
  21461. */
  21462. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  21463. const _objectData = new WeakMap();
  21464. /** @module VelocityNode **/
  21465. /**
  21466. * A node for representing motion or velocity vectors. Foundation
  21467. * for advanced post processing effects like motion blur or TRAA.
  21468. *
  21469. * The node keeps track of the model, view and projection matrices
  21470. * of the previous frame and uses them to compute offsets in NDC space.
  21471. * These offsets represent the final velocity.
  21472. *
  21473. * @augments TempNode
  21474. */
  21475. class VelocityNode extends TempNode {
  21476. static get type() {
  21477. return 'VelocityNode';
  21478. }
  21479. /**
  21480. * Constructs a new vertex color node.
  21481. *
  21482. * @param {Number} [index=0] - The attribute index.
  21483. */
  21484. constructor() {
  21485. super( 'vec2' );
  21486. /**
  21487. * The current projection matrix.
  21488. *
  21489. * @type {Matrix4?}
  21490. * @default null
  21491. */
  21492. this.projectionMatrix = null;
  21493. /**
  21494. * Overwritten since velocity nodes are updated per object.
  21495. *
  21496. * @type {String}
  21497. * @default 'object'
  21498. */
  21499. this.updateType = NodeUpdateType.OBJECT;
  21500. /**
  21501. * Overwritten since velocity nodes save data after the update.
  21502. *
  21503. * @type {String}
  21504. * @default 'object'
  21505. */
  21506. this.updateAfterType = NodeUpdateType.OBJECT;
  21507. /**
  21508. * Uniform node representing the previous model matrix in world space.
  21509. *
  21510. * @type {UniformNode<mat4>}
  21511. * @default null
  21512. */
  21513. this.previousModelWorldMatrix = uniform( new Matrix4() );
  21514. /**
  21515. * Uniform node representing the previous projection matrix.
  21516. *
  21517. * @type {UniformNode<mat4>}
  21518. * @default null
  21519. */
  21520. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  21521. /**
  21522. * Uniform node representing the previous view matrix.
  21523. *
  21524. * @type {UniformNode<mat4>}
  21525. * @default null
  21526. */
  21527. this.previousCameraViewMatrix = uniform( new Matrix4() );
  21528. }
  21529. /**
  21530. * Sets the given projection matrix.
  21531. *
  21532. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  21533. */
  21534. setProjectionMatrix( projectionMatrix ) {
  21535. this.projectionMatrix = projectionMatrix;
  21536. }
  21537. /**
  21538. * Updates velocity specific uniforms.
  21539. *
  21540. * @param {NodeFrame} frame - A reference to the current node frame.
  21541. */
  21542. update( { frameId, camera, object } ) {
  21543. const previousModelMatrix = getPreviousMatrix( object );
  21544. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  21545. //
  21546. const cameraData = getData( camera );
  21547. if ( cameraData.frameId !== frameId ) {
  21548. cameraData.frameId = frameId;
  21549. if ( cameraData.previousProjectionMatrix === undefined ) {
  21550. cameraData.previousProjectionMatrix = new Matrix4();
  21551. cameraData.previousCameraViewMatrix = new Matrix4();
  21552. cameraData.currentProjectionMatrix = new Matrix4();
  21553. cameraData.currentCameraViewMatrix = new Matrix4();
  21554. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21555. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  21556. } else {
  21557. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  21558. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  21559. }
  21560. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21561. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  21562. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  21563. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  21564. }
  21565. }
  21566. /**
  21567. * Overwritten to updated velocity specific uniforms.
  21568. *
  21569. * @param {NodeFrame} frame - A reference to the current node frame.
  21570. */
  21571. updateAfter( { object } ) {
  21572. getPreviousMatrix( object ).copy( object.matrixWorld );
  21573. }
  21574. /**
  21575. * Implements the velocity computation based on the previous and current vertex data.
  21576. *
  21577. * @param {NodeBuilder} builder - A reference to the current node builder.
  21578. * @return {Node<vec2>} The motion vector.
  21579. */
  21580. setup( /*builder*/ ) {
  21581. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  21582. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  21583. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  21584. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  21585. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  21586. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  21587. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  21588. return velocity;
  21589. }
  21590. }
  21591. function getData( object ) {
  21592. let objectData = _objectData.get( object );
  21593. if ( objectData === undefined ) {
  21594. objectData = {};
  21595. _objectData.set( object, objectData );
  21596. }
  21597. return objectData;
  21598. }
  21599. function getPreviousMatrix( object, index = 0 ) {
  21600. const objectData = getData( object );
  21601. let matrix = objectData[ index ];
  21602. if ( matrix === undefined ) {
  21603. objectData[ index ] = matrix = new Matrix4();
  21604. }
  21605. return matrix;
  21606. }
  21607. /**
  21608. * TSL object that represents the velocity of a render pass.
  21609. *
  21610. * @type {VelocityNode}
  21611. */
  21612. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  21613. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21614. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  21615. } ).setLayout( {
  21616. name: 'blendBurn',
  21617. type: 'vec3',
  21618. inputs: [
  21619. { name: 'base', type: 'vec3' },
  21620. { name: 'blend', type: 'vec3' }
  21621. ]
  21622. } );
  21623. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21624. return min$1( base.div( blend.oneMinus() ), 1.0 );
  21625. } ).setLayout( {
  21626. name: 'blendDodge',
  21627. type: 'vec3',
  21628. inputs: [
  21629. { name: 'base', type: 'vec3' },
  21630. { name: 'blend', type: 'vec3' }
  21631. ]
  21632. } );
  21633. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21634. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  21635. } ).setLayout( {
  21636. name: 'blendScreen',
  21637. type: 'vec3',
  21638. inputs: [
  21639. { name: 'base', type: 'vec3' },
  21640. { name: 'blend', type: 'vec3' }
  21641. ]
  21642. } );
  21643. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21644. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  21645. } ).setLayout( {
  21646. name: 'blendOverlay',
  21647. type: 'vec3',
  21648. inputs: [
  21649. { name: 'base', type: 'vec3' },
  21650. { name: 'blend', type: 'vec3' }
  21651. ]
  21652. } );
  21653. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21654. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  21655. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  21656. } ).setLayout( {
  21657. name: 'blendColor',
  21658. type: 'vec4',
  21659. inputs: [
  21660. { name: 'base', type: 'vec4' },
  21661. { name: 'blend', type: 'vec4' }
  21662. ]
  21663. } );
  21664. // deprecated
  21665. /**
  21666. * @function
  21667. * @deprecated since r171. Use {@link blendBurn} instead.
  21668. *
  21669. * @param {...any} params
  21670. * @returns {Function}
  21671. */
  21672. const burn = ( ...params ) => { // @deprecated, r171
  21673. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  21674. return blendBurn( params );
  21675. };
  21676. /**
  21677. * @function
  21678. * @deprecated since r171. Use {@link blendDodge} instead.
  21679. *
  21680. * @param {...any} params
  21681. * @returns {Function}
  21682. */
  21683. const dodge = ( ...params ) => { // @deprecated, r171
  21684. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  21685. return blendDodge( params );
  21686. };
  21687. /**
  21688. * @function
  21689. * @deprecated since r171. Use {@link blendScreen} instead.
  21690. *
  21691. * @param {...any} params
  21692. * @returns {Function}
  21693. */
  21694. const screen = ( ...params ) => { // @deprecated, r171
  21695. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  21696. return blendScreen( params );
  21697. };
  21698. /**
  21699. * @function
  21700. * @deprecated since r171. Use {@link blendOverlay} instead.
  21701. *
  21702. * @param {...any} params
  21703. * @returns {Function}
  21704. */
  21705. const overlay = ( ...params ) => { // @deprecated, r171
  21706. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  21707. return blendOverlay( params );
  21708. };
  21709. /** @module ColorAdjustment **/
  21710. /**
  21711. * Computes a grayscale value for the given RGB color value.
  21712. *
  21713. * @method
  21714. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  21715. * @return {Node<vec3>} The grayscale color.
  21716. */
  21717. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  21718. return luminance( color.rgb );
  21719. } );
  21720. /**
  21721. * Super-saturates or desaturates the given RGB color.
  21722. *
  21723. * @method
  21724. * @param {Node<vec3>} color - The input color.
  21725. * @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.
  21726. * @return {Node<vec3>} The saturated color.
  21727. */
  21728. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21729. return adjustment.mix( luminance( color.rgb ), color.rgb );
  21730. } );
  21731. /**
  21732. * Selectively enhance the intensity of less saturated RGB colors. Can result
  21733. * in a more natural and visually appealing image with enhanced color depth
  21734. * compared to {@link ColorAdjustment#saturation}.
  21735. *
  21736. * @method
  21737. * @param {Node<vec3>} color - The input color.
  21738. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  21739. * @return {Node<vec3>} The updated color.
  21740. */
  21741. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21742. const average = add( color.r, color.g, color.b ).div( 3.0 );
  21743. const mx = color.r.max( color.g.max( color.b ) );
  21744. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  21745. return mix( color.rgb, mx, amt );
  21746. } );
  21747. /**
  21748. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  21749. *
  21750. * @method
  21751. * @param {Node<vec3>} color - The input color.
  21752. * @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.
  21753. * @return {Node<vec3>} The updated color.
  21754. */
  21755. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21756. const k = vec3( 0.57735, 0.57735, 0.57735 );
  21757. const cosAngle = adjustment.cos();
  21758. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  21759. } );
  21760. /**
  21761. * Computes the luminance for the given RGB color value.
  21762. *
  21763. * @method
  21764. * @param {Node<vec3>} color - The color value to compute the luminance for.
  21765. * @param {Node<vec3>?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  21766. * @return {Node<vec3>} The luminance.
  21767. */
  21768. const luminance = (
  21769. color,
  21770. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  21771. ) => dot( color, luminanceCoefficients );
  21772. /**
  21773. * Color Decision List (CDL) v1.2
  21774. *
  21775. * Compact representation of color grading information, defined by slope, offset, power, and
  21776. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  21777. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  21778. *
  21779. * @method
  21780. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  21781. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  21782. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  21783. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  21784. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  21785. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  21786. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  21787. *
  21788. * References:
  21789. * - ASC CDL v1.2
  21790. * - {@link https://blender.stackexchange.com/a/55239/43930}
  21791. * - {@link https://docs.acescentral.com/specifications/acescc/}
  21792. */
  21793. const cdl = /*@__PURE__*/ Fn( ( [
  21794. color,
  21795. slope = vec3( 1 ),
  21796. offset = vec3( 0 ),
  21797. power = vec3( 1 ),
  21798. saturation = float( 1 ),
  21799. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  21800. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  21801. ] ) => {
  21802. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  21803. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  21804. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  21805. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  21806. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  21807. const pv = v.pow( power ).toVar();
  21808. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  21809. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  21810. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  21811. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  21812. return vec4( v.rgb, color.a );
  21813. } );
  21814. /** @module PosterizeNode **/
  21815. /**
  21816. * Represents a posterize effect which reduces the number of colors
  21817. * in an image, resulting in a more blocky and stylized appearance.
  21818. *
  21819. * @augments TempNode
  21820. */
  21821. class PosterizeNode extends TempNode {
  21822. static get type() {
  21823. return 'PosterizeNode';
  21824. }
  21825. /**
  21826. * Constructs a new posterize node.
  21827. *
  21828. * @param {Node} sourceNode - The input color.
  21829. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21830. */
  21831. constructor( sourceNode, stepsNode ) {
  21832. super();
  21833. /**
  21834. * The input color.
  21835. *
  21836. * @type {Node}
  21837. */
  21838. this.sourceNode = sourceNode;
  21839. /**
  21840. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21841. *
  21842. * @type {Node}
  21843. */
  21844. this.stepsNode = stepsNode;
  21845. }
  21846. setup() {
  21847. const { sourceNode, stepsNode } = this;
  21848. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  21849. }
  21850. }
  21851. /**
  21852. * TSL function for creating a posterize node.
  21853. *
  21854. * @function
  21855. * @param {Node} sourceNode - The input color.
  21856. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21857. * @returns {PosterizeNode}
  21858. */
  21859. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  21860. /** @module PassNode **/
  21861. const _size = /*@__PURE__*/ new Vector2();
  21862. /**
  21863. * Represents the texture of a pass node.
  21864. *
  21865. * @augments module:TextureNode~TextureNode
  21866. */
  21867. class PassTextureNode extends TextureNode {
  21868. static get type() {
  21869. return 'PassTextureNode';
  21870. }
  21871. /**
  21872. * Constructs a new pass texture node.
  21873. *
  21874. * @param {PassNode} passNode - The pass node.
  21875. * @param {Texture} texture - The output texture.
  21876. */
  21877. constructor( passNode, texture ) {
  21878. super( texture );
  21879. /**
  21880. * A reference to the pass node.
  21881. *
  21882. * @type {PassNode}
  21883. */
  21884. this.passNode = passNode;
  21885. this.setUpdateMatrix( false );
  21886. }
  21887. setup( builder ) {
  21888. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  21889. return super.setup( builder );
  21890. }
  21891. clone() {
  21892. return new this.constructor( this.passNode, this.value );
  21893. }
  21894. }
  21895. /**
  21896. * An extension of `PassTextureNode` which allows to manage more than one
  21897. * internal texture. Relevant for the `getPreviousTexture()` related API.
  21898. *
  21899. * @augments module:PassTextureNode~PassTextureNode
  21900. */
  21901. class PassMultipleTextureNode extends PassTextureNode {
  21902. static get type() {
  21903. return 'PassMultipleTextureNode';
  21904. }
  21905. /**
  21906. * Constructs a new pass texture node.
  21907. *
  21908. * @param {PassNode} passNode - The pass node.
  21909. * @param {String} textureName - The output texture name.
  21910. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  21911. */
  21912. constructor( passNode, textureName, previousTexture = false ) {
  21913. // null is passed to the super call since this class does not
  21914. // use an external texture for rendering pass data into. Instead
  21915. // the texture is managed by the pass node itself
  21916. super( passNode, null );
  21917. /**
  21918. * The output texture name.
  21919. *
  21920. * @type {String}
  21921. */
  21922. this.textureName = textureName;
  21923. /**
  21924. * Whether previous frame data should be used or not.
  21925. *
  21926. * @type {Boolean}
  21927. */
  21928. this.previousTexture = previousTexture;
  21929. }
  21930. /**
  21931. * Updates the texture reference of this node.
  21932. */
  21933. updateTexture() {
  21934. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  21935. }
  21936. setup( builder ) {
  21937. this.updateTexture();
  21938. return super.setup( builder );
  21939. }
  21940. clone() {
  21941. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  21942. }
  21943. }
  21944. /**
  21945. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  21946. * This pass produces a render for the given scene and camera and can provide multiple outputs
  21947. * via MRT for further processing.
  21948. *
  21949. * ```js
  21950. * const postProcessing = new PostProcessing( renderer );
  21951. *
  21952. * const scenePass = pass( scene, camera );
  21953. *
  21954. * postProcessing.outputNode = scenePass;
  21955. * ```
  21956. *
  21957. * @augments TempNode
  21958. */
  21959. class PassNode extends TempNode {
  21960. static get type() {
  21961. return 'PassNode';
  21962. }
  21963. /**
  21964. * Constructs a new pass node.
  21965. *
  21966. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  21967. * @param {Scene} scene - A reference to the scene.
  21968. * @param {Camera} camera - A reference to the camera.
  21969. * @param {Object} options - Options for the internal render target.
  21970. */
  21971. constructor( scope, scene, camera, options = {} ) {
  21972. super( 'vec4' );
  21973. /**
  21974. * The scope of the pass. The scope determines whether the node outputs color or depth.
  21975. *
  21976. * @type {('color'|'depth')}
  21977. */
  21978. this.scope = scope;
  21979. /**
  21980. * A reference to the scene.
  21981. *
  21982. * @type {Scene}
  21983. */
  21984. this.scene = scene;
  21985. /**
  21986. * A reference to the camera.
  21987. *
  21988. * @type {Camera}
  21989. */
  21990. this.camera = camera;
  21991. /**
  21992. * Options for the internal render target.
  21993. *
  21994. * @type {Object}
  21995. */
  21996. this.options = options;
  21997. /**
  21998. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  21999. *
  22000. * @private
  22001. * @type {Number}
  22002. * @default 1
  22003. */
  22004. this._pixelRatio = 1;
  22005. /**
  22006. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  22007. * @private
  22008. * @type {Number}
  22009. * @default 1
  22010. */
  22011. this._width = 1;
  22012. /**
  22013. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  22014. * @private
  22015. * @type {Number}
  22016. * @default 1
  22017. */
  22018. this._height = 1;
  22019. const depthTexture = new DepthTexture();
  22020. depthTexture.isRenderTargetTexture = true;
  22021. //depthTexture.type = FloatType;
  22022. depthTexture.name = 'depth';
  22023. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  22024. renderTarget.texture.name = 'output';
  22025. renderTarget.depthTexture = depthTexture;
  22026. /**
  22027. * The pass's render target.
  22028. *
  22029. * @type {RenderTarget}
  22030. */
  22031. this.renderTarget = renderTarget;
  22032. /**
  22033. * A dictionary holding the internal result textures.
  22034. *
  22035. * @private
  22036. * @type {Object<String, Texture>}
  22037. */
  22038. this._textures = {
  22039. output: renderTarget.texture,
  22040. depth: depthTexture
  22041. };
  22042. /**
  22043. * A dictionary holding the internal texture nodes.
  22044. *
  22045. * @private
  22046. * @type {Object<String, TextureNode>}
  22047. */
  22048. this._textureNodes = {};
  22049. /**
  22050. * A dictionary holding the internal depth nodes.
  22051. *
  22052. * @private
  22053. * @type {Object}
  22054. */
  22055. this._linearDepthNodes = {};
  22056. /**
  22057. * A dictionary holding the internal viewZ nodes.
  22058. *
  22059. * @private
  22060. * @type {Object}
  22061. */
  22062. this._viewZNodes = {};
  22063. /**
  22064. * A dictionary holding the texture data of the previous frame.
  22065. * Used for computing velocity/motion vectors.
  22066. *
  22067. * @private
  22068. * @type {Object<String, Texture>}
  22069. */
  22070. this._previousTextures = {};
  22071. /**
  22072. * A dictionary holding the texture nodes of the previous frame.
  22073. * Used for computing velocity/motion vectors.
  22074. *
  22075. * @private
  22076. * @type {Object<String, TextureNode>}
  22077. */
  22078. this._previousTextureNodes = {};
  22079. /**
  22080. * The `near` property of the camera as a uniform.
  22081. *
  22082. * @private
  22083. * @type {UniformNode}
  22084. */
  22085. this._cameraNear = uniform( 0 );
  22086. /**
  22087. * The `far` property of the camera as a uniform.
  22088. *
  22089. * @private
  22090. * @type {UniformNode}
  22091. */
  22092. this._cameraFar = uniform( 0 );
  22093. /**
  22094. * A MRT node configuring the MRT settings.
  22095. *
  22096. * @private
  22097. * @type {MRTNode?}
  22098. * @default null
  22099. */
  22100. this._mrt = null;
  22101. /**
  22102. * This flag can be used for type testing.
  22103. *
  22104. * @type {Boolean}
  22105. * @readonly
  22106. * @default true
  22107. */
  22108. this.isPassNode = true;
  22109. /**
  22110. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  22111. * scene once per frame in its {@link PassNode#updateBefore} method.
  22112. *
  22113. * @type {String}
  22114. * @default 'frame'
  22115. */
  22116. this.updateBeforeType = NodeUpdateType.FRAME;
  22117. }
  22118. /**
  22119. * Sets the given MRT node to setup MRT for this pass.
  22120. *
  22121. * @param {MRTNode} mrt - The MRT object.
  22122. * @return {PassNode} A reference to this pass.
  22123. */
  22124. setMRT( mrt ) {
  22125. this._mrt = mrt;
  22126. return this;
  22127. }
  22128. /**
  22129. * Returns the current MRT node.
  22130. *
  22131. * @return {MRTNode} The current MRT node.
  22132. */
  22133. getMRT() {
  22134. return this._mrt;
  22135. }
  22136. /**
  22137. * The method is overwritten so it always returns `true`.
  22138. *
  22139. * @return {Boolean} Whether this node is global or not.
  22140. */
  22141. isGlobal() {
  22142. return true;
  22143. }
  22144. /**
  22145. * Returns the texture for the given output name.
  22146. *
  22147. * @param {String} name - The output name to get the texture for.
  22148. * @return {Texture} The texture.
  22149. */
  22150. getTexture( name ) {
  22151. let texture = this._textures[ name ];
  22152. if ( texture === undefined ) {
  22153. const refTexture = this.renderTarget.texture;
  22154. texture = refTexture.clone();
  22155. texture.name = name;
  22156. this._textures[ name ] = texture;
  22157. this.renderTarget.textures.push( texture );
  22158. }
  22159. return texture;
  22160. }
  22161. /**
  22162. * Returns the texture holding the data of the previous frame for the given output name.
  22163. *
  22164. * @param {String} name - The output name to get the texture for.
  22165. * @return {Texture} The texture holding the data of the previous frame.
  22166. */
  22167. getPreviousTexture( name ) {
  22168. let texture = this._previousTextures[ name ];
  22169. if ( texture === undefined ) {
  22170. texture = this.getTexture( name ).clone();
  22171. this._previousTextures[ name ] = texture;
  22172. }
  22173. return texture;
  22174. }
  22175. /**
  22176. * Switches current and previous textures for the given output name.
  22177. *
  22178. * @param {String} name - The output name.
  22179. */
  22180. toggleTexture( name ) {
  22181. const prevTexture = this._previousTextures[ name ];
  22182. if ( prevTexture !== undefined ) {
  22183. const texture = this._textures[ name ];
  22184. const index = this.renderTarget.textures.indexOf( texture );
  22185. this.renderTarget.textures[ index ] = prevTexture;
  22186. this._textures[ name ] = prevTexture;
  22187. this._previousTextures[ name ] = texture;
  22188. this._textureNodes[ name ].updateTexture();
  22189. this._previousTextureNodes[ name ].updateTexture();
  22190. }
  22191. }
  22192. /**
  22193. * Returns the texture node for the given output name.
  22194. *
  22195. * @param {String} [name='output'] - The output name to get the texture node for.
  22196. * @return {TextureNode} The texture node.
  22197. */
  22198. getTextureNode( name = 'output' ) {
  22199. let textureNode = this._textureNodes[ name ];
  22200. if ( textureNode === undefined ) {
  22201. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  22202. textureNode.updateTexture();
  22203. this._textureNodes[ name ] = textureNode;
  22204. }
  22205. return textureNode;
  22206. }
  22207. /**
  22208. * Returns the previous texture node for the given output name.
  22209. *
  22210. * @param {String} [name='output'] - The output name to get the previous texture node for.
  22211. * @return {TextureNode} The previous texture node.
  22212. */
  22213. getPreviousTextureNode( name = 'output' ) {
  22214. let textureNode = this._previousTextureNodes[ name ];
  22215. if ( textureNode === undefined ) {
  22216. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  22217. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  22218. textureNode.updateTexture();
  22219. this._previousTextureNodes[ name ] = textureNode;
  22220. }
  22221. return textureNode;
  22222. }
  22223. /**
  22224. * Returns a viewZ node of this pass.
  22225. *
  22226. * @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.
  22227. * @return {Node} The viewZ node.
  22228. */
  22229. getViewZNode( name = 'depth' ) {
  22230. let viewZNode = this._viewZNodes[ name ];
  22231. if ( viewZNode === undefined ) {
  22232. const cameraNear = this._cameraNear;
  22233. const cameraFar = this._cameraFar;
  22234. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  22235. }
  22236. return viewZNode;
  22237. }
  22238. /**
  22239. * Returns a linear depth node of this pass.
  22240. *
  22241. * @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.
  22242. * @return {Node} The linear depth node.
  22243. */
  22244. getLinearDepthNode( name = 'depth' ) {
  22245. let linearDepthNode = this._linearDepthNodes[ name ];
  22246. if ( linearDepthNode === undefined ) {
  22247. const cameraNear = this._cameraNear;
  22248. const cameraFar = this._cameraFar;
  22249. const viewZNode = this.getViewZNode( name );
  22250. // TODO: just if ( builder.camera.isPerspectiveCamera )
  22251. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  22252. }
  22253. return linearDepthNode;
  22254. }
  22255. setup( { renderer } ) {
  22256. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  22257. // Disable MSAA for WebGL backend for now
  22258. if ( renderer.backend.isWebGLBackend === true ) {
  22259. this.renderTarget.samples = 0;
  22260. }
  22261. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  22262. }
  22263. updateBefore( frame ) {
  22264. const { renderer } = frame;
  22265. const { scene, camera } = this;
  22266. this._pixelRatio = renderer.getPixelRatio();
  22267. const size = renderer.getSize( _size );
  22268. this.setSize( size.width, size.height );
  22269. const currentRenderTarget = renderer.getRenderTarget();
  22270. const currentMRT = renderer.getMRT();
  22271. this._cameraNear.value = camera.near;
  22272. this._cameraFar.value = camera.far;
  22273. for ( const name in this._previousTextures ) {
  22274. this.toggleTexture( name );
  22275. }
  22276. renderer.setRenderTarget( this.renderTarget );
  22277. renderer.setMRT( this._mrt );
  22278. renderer.render( scene, camera );
  22279. renderer.setRenderTarget( currentRenderTarget );
  22280. renderer.setMRT( currentMRT );
  22281. }
  22282. /**
  22283. * Sets the size of the pass's render target. Honors the pixel ratio.
  22284. *
  22285. * @param {Number} width - The width to set.
  22286. * @param {Number} height - The height to set.
  22287. */
  22288. setSize( width, height ) {
  22289. this._width = width;
  22290. this._height = height;
  22291. const effectiveWidth = this._width * this._pixelRatio;
  22292. const effectiveHeight = this._height * this._pixelRatio;
  22293. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  22294. }
  22295. /**
  22296. * Sets the pixel ratio the pass's render target and updates the size.
  22297. *
  22298. * @param {Number} pixelRatio - The pixel ratio to set.
  22299. */
  22300. setPixelRatio( pixelRatio ) {
  22301. this._pixelRatio = pixelRatio;
  22302. this.setSize( this._width, this._height );
  22303. }
  22304. /**
  22305. * Frees internal resources. Should be called when the node is no longer in use.
  22306. */
  22307. dispose() {
  22308. this.renderTarget.dispose();
  22309. }
  22310. }
  22311. PassNode.COLOR = 'color';
  22312. PassNode.DEPTH = 'depth';
  22313. /**
  22314. * TSL function for creating a pass node.
  22315. *
  22316. * @function
  22317. * @param {Scene} scene - A reference to the scene.
  22318. * @param {Camera} camera - A reference to the camera.
  22319. * @param {Object} options - Options for the internal render target.
  22320. * @returns {PassNode}
  22321. */
  22322. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  22323. /**
  22324. * TSL function for creating a pass texture node.
  22325. *
  22326. * @function
  22327. * @param {PassNode} pass - The pass node.
  22328. * @param {Texture} texture - The output texture.
  22329. * @returns {PassTextureNode}
  22330. */
  22331. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  22332. /**
  22333. * TSL function for creating a depth pass node.
  22334. *
  22335. * @function
  22336. * @param {Scene} scene - A reference to the scene.
  22337. * @param {Camera} camera - A reference to the camera.
  22338. * @param {Object} options - Options for the internal render target.
  22339. * @returns {PassNode}
  22340. */
  22341. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  22342. /** @module ToonOutlinePassNode **/
  22343. /**
  22344. * Represents a render pass for producing a toon outline effect on compatible objects.
  22345. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  22346. * will receive the outline.
  22347. *
  22348. * ```js
  22349. * const postProcessing = new PostProcessing( renderer );
  22350. *
  22351. * const scenePass = toonOutlinePass( scene, camera );
  22352. *
  22353. * postProcessing.outputNode = scenePass;
  22354. * ```
  22355. * @augments PassNode
  22356. */
  22357. class ToonOutlinePassNode extends PassNode {
  22358. static get type() {
  22359. return 'ToonOutlinePassNode';
  22360. }
  22361. /**
  22362. * Constructs a new outline pass node.
  22363. *
  22364. * @param {Scene} scene - A reference to the scene.
  22365. * @param {Camera} camera - A reference to the camera.
  22366. * @param {Node} colorNode - Defines the outline's color.
  22367. * @param {Node} thicknessNode - Defines the outline's thickness.
  22368. * @param {Node} alphaNode - Defines the outline's alpha.
  22369. */
  22370. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  22371. super( PassNode.COLOR, scene, camera );
  22372. /**
  22373. * Defines the outline's color.
  22374. *
  22375. * @type {Node}
  22376. */
  22377. this.colorNode = colorNode;
  22378. /**
  22379. * Defines the outline's thickness.
  22380. *
  22381. * @type {Node}
  22382. */
  22383. this.thicknessNode = thicknessNode;
  22384. /**
  22385. * Defines the outline's alpha.
  22386. *
  22387. * @type {Node}
  22388. */
  22389. this.alphaNode = alphaNode;
  22390. /**
  22391. * An internal material cache.
  22392. *
  22393. * @private
  22394. * @type {WeakMap<Material, NodeMaterial>}
  22395. */
  22396. this._materialCache = new WeakMap();
  22397. }
  22398. updateBefore( frame ) {
  22399. const { renderer } = frame;
  22400. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  22401. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  22402. // only render outline for supported materials
  22403. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  22404. if ( material.wireframe === false ) {
  22405. const outlineMaterial = this._getOutlineMaterial( material );
  22406. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  22407. }
  22408. }
  22409. // default
  22410. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  22411. } );
  22412. super.updateBefore( frame );
  22413. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  22414. }
  22415. /**
  22416. * Creates the material used for outline rendering.
  22417. *
  22418. * @private
  22419. * @return {NodeMaterial} The outline material.
  22420. */
  22421. _createMaterial() {
  22422. const material = new NodeMaterial();
  22423. material.isMeshToonOutlineMaterial = true;
  22424. material.name = 'Toon_Outline';
  22425. material.side = BackSide;
  22426. // vertex node
  22427. const outlineNormal = normalLocal.negate();
  22428. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  22429. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  22430. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  22431. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  22432. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  22433. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  22434. // color node
  22435. material.colorNode = vec4( this.colorNode, this.alphaNode );
  22436. return material;
  22437. }
  22438. /**
  22439. * For the given toon material, this method returns a corresponding
  22440. * outline material.
  22441. *
  22442. * @private
  22443. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  22444. * @return {NodeMaterial} The outline material.
  22445. */
  22446. _getOutlineMaterial( originalMaterial ) {
  22447. let outlineMaterial = this._materialCache.get( originalMaterial );
  22448. if ( outlineMaterial === undefined ) {
  22449. outlineMaterial = this._createMaterial();
  22450. this._materialCache.set( originalMaterial, outlineMaterial );
  22451. }
  22452. return outlineMaterial;
  22453. }
  22454. }
  22455. /**
  22456. * TSL function for creating a toon outline pass node.
  22457. *
  22458. * @function
  22459. * @param {Scene} scene - A reference to the scene.
  22460. * @param {Camera} camera - A reference to the camera.
  22461. * @param {Color} color - Defines the outline's color.
  22462. * @param {Number} [thickness=0.003] - Defines the outline's thickness.
  22463. * @param {Number} [alpha=1] - Defines the outline's alpha.
  22464. * @returns {ToonOutlinePassNode}
  22465. */
  22466. 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 ) ) );
  22467. /** @module ToneMappingFunctions **/
  22468. /**
  22469. * Linear tone mapping, exposure only.
  22470. *
  22471. * @method
  22472. * @param {Node<vec3>} color - The color that should be tone mapped.
  22473. * @param {Node<float>} exposure - The exposure.
  22474. * @return {Node<vec3>} The tone mapped color.
  22475. */
  22476. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22477. return color.mul( exposure ).clamp();
  22478. } ).setLayout( {
  22479. name: 'linearToneMapping',
  22480. type: 'vec3',
  22481. inputs: [
  22482. { name: 'color', type: 'vec3' },
  22483. { name: 'exposure', type: 'float' }
  22484. ]
  22485. } );
  22486. /**
  22487. * Reinhard tone mapping.
  22488. *
  22489. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  22490. *
  22491. * @method
  22492. * @param {Node<vec3>} color - The color that should be tone mapped.
  22493. * @param {Node<float>} exposure - The exposure.
  22494. * @return {Node<vec3>} The tone mapped color.
  22495. */
  22496. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22497. color = color.mul( exposure );
  22498. return color.div( color.add( 1.0 ) ).clamp();
  22499. } ).setLayout( {
  22500. name: 'reinhardToneMapping',
  22501. type: 'vec3',
  22502. inputs: [
  22503. { name: 'color', type: 'vec3' },
  22504. { name: 'exposure', type: 'float' }
  22505. ]
  22506. } );
  22507. /**
  22508. * Cineon tone mapping.
  22509. *
  22510. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  22511. *
  22512. * @method
  22513. * @param {Node<vec3>} color - The color that should be tone mapped.
  22514. * @param {Node<float>} exposure - The exposure.
  22515. * @return {Node<vec3>} The tone mapped color.
  22516. */
  22517. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22518. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  22519. color = color.mul( exposure );
  22520. color = color.sub( 0.004 ).max( 0.0 );
  22521. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  22522. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  22523. return a.div( b ).pow( 2.2 );
  22524. } ).setLayout( {
  22525. name: 'cineonToneMapping',
  22526. type: 'vec3',
  22527. inputs: [
  22528. { name: 'color', type: 'vec3' },
  22529. { name: 'exposure', type: 'float' }
  22530. ]
  22531. } );
  22532. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  22533. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  22534. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  22535. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  22536. return a.div( b );
  22537. } );
  22538. /**
  22539. * ACESFilmic tone mapping.
  22540. *
  22541. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  22542. *
  22543. * @method
  22544. * @param {Node<vec3>} color - The color that should be tone mapped.
  22545. * @param {Node<float>} exposure - The exposure.
  22546. * @return {Node<vec3>} The tone mapped color.
  22547. */
  22548. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22549. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  22550. const ACESInputMat = mat3(
  22551. 0.59719, 0.35458, 0.04823,
  22552. 0.07600, 0.90834, 0.01566,
  22553. 0.02840, 0.13383, 0.83777
  22554. );
  22555. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  22556. const ACESOutputMat = mat3(
  22557. 1.60475, - 0.53108, - 0.07367,
  22558. - 0.10208, 1.10813, - 0.00605,
  22559. - 0.00327, - 0.07276, 1.07602
  22560. );
  22561. color = color.mul( exposure ).div( 0.6 );
  22562. color = ACESInputMat.mul( color );
  22563. // Apply RRT and ODT
  22564. color = RRTAndODTFit( color );
  22565. color = ACESOutputMat.mul( color );
  22566. // Clamp to [0, 1]
  22567. return color.clamp();
  22568. } ).setLayout( {
  22569. name: 'acesFilmicToneMapping',
  22570. type: 'vec3',
  22571. inputs: [
  22572. { name: 'color', type: 'vec3' },
  22573. { name: 'exposure', type: 'float' }
  22574. ]
  22575. } );
  22576. 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 ) );
  22577. 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 ) );
  22578. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  22579. const x = vec3( x_immutable ).toVar();
  22580. const x2 = vec3( x.mul( x ) ).toVar();
  22581. const x4 = vec3( x2.mul( x2 ) ).toVar();
  22582. 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 ) ) ) );
  22583. } );
  22584. /**
  22585. * AgX tone mapping.
  22586. *
  22587. * @method
  22588. * @param {Node<vec3>} color - The color that should be tone mapped.
  22589. * @param {Node<float>} exposure - The exposure.
  22590. * @return {Node<vec3>} The tone mapped color.
  22591. */
  22592. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22593. const colortone = vec3( color ).toVar();
  22594. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  22595. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  22596. const AgxMinEv = float( - 12.47393 );
  22597. const AgxMaxEv = float( 4.026069 );
  22598. colortone.mulAssign( exposure );
  22599. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  22600. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  22601. colortone.assign( max$1( colortone, 1e-10 ) );
  22602. colortone.assign( log2( colortone ) );
  22603. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  22604. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22605. colortone.assign( agxDefaultContrastApprox( colortone ) );
  22606. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  22607. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  22608. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  22609. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22610. return colortone;
  22611. } ).setLayout( {
  22612. name: 'agxToneMapping',
  22613. type: 'vec3',
  22614. inputs: [
  22615. { name: 'color', type: 'vec3' },
  22616. { name: 'exposure', type: 'float' }
  22617. ]
  22618. } );
  22619. /**
  22620. * Neutral tone mapping.
  22621. *
  22622. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  22623. *
  22624. * @method
  22625. * @param {Node<vec3>} color - The color that should be tone mapped.
  22626. * @param {Node<float>} exposure - The exposure.
  22627. * @return {Node<vec3>} The tone mapped color.
  22628. */
  22629. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22630. const StartCompression = float( 0.8 - 0.04 );
  22631. const Desaturation = float( 0.15 );
  22632. color = color.mul( exposure );
  22633. const x = min$1( color.r, min$1( color.g, color.b ) );
  22634. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  22635. color.subAssign( offset );
  22636. const peak = max$1( color.r, max$1( color.g, color.b ) );
  22637. If( peak.lessThan( StartCompression ), () => {
  22638. return color;
  22639. } );
  22640. const d = sub( 1, StartCompression );
  22641. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  22642. color.mulAssign( newPeak.div( peak ) );
  22643. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  22644. return mix( color, vec3( newPeak ), g );
  22645. } ).setLayout( {
  22646. name: 'neutralToneMapping',
  22647. type: 'vec3',
  22648. inputs: [
  22649. { name: 'color', type: 'vec3' },
  22650. { name: 'exposure', type: 'float' }
  22651. ]
  22652. } );
  22653. /** @module CodeNode **/
  22654. /**
  22655. * This class represents native code sections. It is the base
  22656. * class for modules like {@link FunctionNode} which allows to implement
  22657. * functions with native shader languages.
  22658. *
  22659. * @augments Node
  22660. */
  22661. class CodeNode extends Node {
  22662. static get type() {
  22663. return 'CodeNode';
  22664. }
  22665. /**
  22666. * Constructs a new code node.
  22667. *
  22668. * @param {String} [code=''] - The native code.
  22669. * @param {Array<Node>} [includes=[]] - An array of includes.
  22670. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22671. */
  22672. constructor( code = '', includes = [], language = '' ) {
  22673. super( 'code' );
  22674. /**
  22675. * This flag can be used for type testing.
  22676. *
  22677. * @type {Boolean}
  22678. * @readonly
  22679. * @default true
  22680. */
  22681. this.isCodeNode = true;
  22682. /**
  22683. * The native code.
  22684. *
  22685. * @type {String}
  22686. * @default ''
  22687. */
  22688. this.code = code;
  22689. /**
  22690. * An array of includes
  22691. *
  22692. * @type {Array<Node>}
  22693. * @default []
  22694. */
  22695. this.includes = includes;
  22696. /**
  22697. * The used language.
  22698. *
  22699. * @type {('js'|'wgsl'|'glsl')}
  22700. * @default ''
  22701. */
  22702. this.language = language;
  22703. }
  22704. /**
  22705. * The method is overwritten so it always returns `true`.
  22706. *
  22707. * @return {Boolean} Whether this node is global or not.
  22708. */
  22709. isGlobal() {
  22710. return true;
  22711. }
  22712. /**
  22713. * Sets the includes of this code node.
  22714. *
  22715. * @param {Array<Node>} includes - The includes to set.
  22716. * @return {CodeNode} A reference to this node.
  22717. */
  22718. setIncludes( includes ) {
  22719. this.includes = includes;
  22720. return this;
  22721. }
  22722. /**
  22723. * Returns the includes of this code node.
  22724. *
  22725. * @param {NodeBuilder} builder - The current node builder.
  22726. * @return {Array<Node>} The includes.
  22727. */
  22728. getIncludes( /*builder*/ ) {
  22729. return this.includes;
  22730. }
  22731. generate( builder ) {
  22732. const includes = this.getIncludes( builder );
  22733. for ( const include of includes ) {
  22734. include.build( builder );
  22735. }
  22736. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  22737. nodeCode.code = this.code;
  22738. return nodeCode.code;
  22739. }
  22740. serialize( data ) {
  22741. super.serialize( data );
  22742. data.code = this.code;
  22743. data.language = this.language;
  22744. }
  22745. deserialize( data ) {
  22746. super.deserialize( data );
  22747. this.code = data.code;
  22748. this.language = data.language;
  22749. }
  22750. }
  22751. /**
  22752. * TSL function for creating a code node.
  22753. *
  22754. * @function
  22755. * @param {String} [code=''] - The native code.
  22756. * @param {Array<Node>} [includes=[]] - An array of includes.
  22757. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22758. * @returns {CodeNode}
  22759. */
  22760. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  22761. /**
  22762. * TSL function for creating a JS code node.
  22763. *
  22764. * @function
  22765. * @param {String} src - The native code.
  22766. * @param {Array<Node>} includes - An array of includes.
  22767. * @returns {CodeNode}
  22768. */
  22769. const js = ( src, includes ) => code( src, includes, 'js' );
  22770. /**
  22771. * TSL function for creating a WGSL code node.
  22772. *
  22773. * @function
  22774. * @param {String} src - The native code.
  22775. * @param {Array<Node>} includes - An array of includes.
  22776. * @returns {CodeNode}
  22777. */
  22778. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  22779. /**
  22780. * TSL function for creating a GLSL code node.
  22781. *
  22782. * @function
  22783. * @param {String} src - The native code.
  22784. * @param {Array<Node>} includes - An array of includes.
  22785. * @returns {CodeNode}
  22786. */
  22787. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  22788. /**
  22789. * This class represents a native shader function. It can be used to implement
  22790. * certain aspects of a node material with native shader code. There are two predefined
  22791. * TSL functions for easier usage.
  22792. *
  22793. * - `wgslFn`: Creates a WGSL function node.
  22794. * - `glslFn`: Creates a GLSL function node.
  22795. *
  22796. * A basic example with one include looks like so:
  22797. *
  22798. * ```js
  22799. * const desaturateWGSLFn = wgslFn( `
  22800. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  22801. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  22802. * return vec3<f32>( dot( lum, color ) );
  22803. * }`
  22804. *);
  22805. * const someWGSLFn = wgslFn( `
  22806. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  22807. * return desaturate( color );
  22808. * }
  22809. * `, [ desaturateWGSLFn ] );
  22810. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  22811. *```
  22812. * @augments CodeNode
  22813. */
  22814. class FunctionNode extends CodeNode {
  22815. static get type() {
  22816. return 'FunctionNode';
  22817. }
  22818. /**
  22819. * Constructs a new function node.
  22820. *
  22821. * @param {String} [code=''] - The native code.
  22822. * @param {Array<Node>} [includes=[]] - An array of includes.
  22823. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22824. */
  22825. constructor( code = '', includes = [], language = '' ) {
  22826. super( code, includes, language );
  22827. }
  22828. getNodeType( builder ) {
  22829. return this.getNodeFunction( builder ).type;
  22830. }
  22831. /**
  22832. * Returns the inputs of this function node.
  22833. *
  22834. * @param {NodeBuilder} builder - The current node builder.
  22835. * @return {Array<NodeFunctionInput>} The inputs.
  22836. */
  22837. getInputs( builder ) {
  22838. return this.getNodeFunction( builder ).inputs;
  22839. }
  22840. /**
  22841. * Returns the node function for this function node.
  22842. *
  22843. * @param {NodeBuilder} builder - The current node builder.
  22844. * @return {NodeFunction} The node function.
  22845. */
  22846. getNodeFunction( builder ) {
  22847. const nodeData = builder.getDataFromNode( this );
  22848. let nodeFunction = nodeData.nodeFunction;
  22849. if ( nodeFunction === undefined ) {
  22850. nodeFunction = builder.parser.parseFunction( this.code );
  22851. nodeData.nodeFunction = nodeFunction;
  22852. }
  22853. return nodeFunction;
  22854. }
  22855. generate( builder, output ) {
  22856. super.generate( builder );
  22857. const nodeFunction = this.getNodeFunction( builder );
  22858. const name = nodeFunction.name;
  22859. const type = nodeFunction.type;
  22860. const nodeCode = builder.getCodeFromNode( this, type );
  22861. if ( name !== '' ) {
  22862. // use a custom property name
  22863. nodeCode.name = name;
  22864. }
  22865. const propertyName = builder.getPropertyName( nodeCode );
  22866. const code = this.getNodeFunction( builder ).getCode( propertyName );
  22867. nodeCode.code = code + '\n';
  22868. if ( output === 'property' ) {
  22869. return propertyName;
  22870. } else {
  22871. return builder.format( `${ propertyName }()`, type, output );
  22872. }
  22873. }
  22874. }
  22875. const nativeFn = ( code, includes = [], language = '' ) => {
  22876. for ( let i = 0; i < includes.length; i ++ ) {
  22877. const include = includes[ i ];
  22878. // TSL Function: glslFn, wgslFn
  22879. if ( typeof include === 'function' ) {
  22880. includes[ i ] = include.functionNode;
  22881. }
  22882. }
  22883. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  22884. const fn = ( ...params ) => functionNode.call( ...params );
  22885. fn.functionNode = functionNode;
  22886. return fn;
  22887. };
  22888. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  22889. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  22890. /** @module ScriptableValueNode **/
  22891. /**
  22892. * `ScriptableNode` uses this class to manage script inputs and outputs.
  22893. *
  22894. * @augments Node
  22895. */
  22896. class ScriptableValueNode extends Node {
  22897. static get type() {
  22898. return 'ScriptableValueNode';
  22899. }
  22900. /**
  22901. * Constructs a new scriptable node.
  22902. *
  22903. * @param {Any} [value=null] - The value.
  22904. */
  22905. constructor( value = null ) {
  22906. super();
  22907. /**
  22908. * A reference to the value.
  22909. *
  22910. * @private
  22911. * @default null
  22912. */
  22913. this._value = value;
  22914. /**
  22915. * Depending on the type of `_value`, this property might cache parsed data.
  22916. *
  22917. * @private
  22918. * @default null
  22919. */
  22920. this._cache = null;
  22921. /**
  22922. * If this node represents an input, this property represents the input type.
  22923. *
  22924. * @type {String?}
  22925. * @default null
  22926. */
  22927. this.inputType = null;
  22928. /**
  22929. * If this node represents an output, this property represents the output type.
  22930. *
  22931. * @type {String?}
  22932. * @default null
  22933. */
  22934. this.outputType = null;
  22935. /**
  22936. * An event dispatcher for managing events.
  22937. *
  22938. * @type {EventDispatcher}
  22939. */
  22940. this.events = new EventDispatcher();
  22941. /**
  22942. * This flag can be used for type testing.
  22943. *
  22944. * @type {Boolean}
  22945. * @readonly
  22946. * @default true
  22947. */
  22948. this.isScriptableValueNode = true;
  22949. }
  22950. /**
  22951. * Whether this node represents an output or not.
  22952. *
  22953. * @type {Boolean}
  22954. * @readonly
  22955. * @default true
  22956. */
  22957. get isScriptableOutputNode() {
  22958. return this.outputType !== null;
  22959. }
  22960. set value( val ) {
  22961. if ( this._value === val ) return;
  22962. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  22963. URL.revokeObjectURL( this._cache );
  22964. this._cache = null;
  22965. }
  22966. this._value = val;
  22967. this.events.dispatchEvent( { type: 'change' } );
  22968. this.refresh();
  22969. }
  22970. /**
  22971. * The node's value.
  22972. *
  22973. * @type {Any}
  22974. */
  22975. get value() {
  22976. return this._value;
  22977. }
  22978. /**
  22979. * Dispatches the `refresh` event.
  22980. */
  22981. refresh() {
  22982. this.events.dispatchEvent( { type: 'refresh' } );
  22983. }
  22984. /**
  22985. * The `value` property usually represents a node or even binary data in form of array buffers.
  22986. * In this case, this method tries to return the actual value behind the complex type.
  22987. *
  22988. * @return {Any} The value.
  22989. */
  22990. getValue() {
  22991. const value = this.value;
  22992. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  22993. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  22994. } else if ( value && value.value !== null && value.value !== undefined && (
  22995. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  22996. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  22997. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  22998. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  22999. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  23000. ( this.inputType === 'Color' && value.value.isColor ) ||
  23001. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  23002. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  23003. ) ) {
  23004. return value.value;
  23005. }
  23006. return this._cache || value;
  23007. }
  23008. /**
  23009. * Overwritten since the node type is inferred from the value.
  23010. *
  23011. * @param {NodeBuilder} builder - The current node builder.
  23012. * @return {String} The node type.
  23013. */
  23014. getNodeType( builder ) {
  23015. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  23016. }
  23017. setup() {
  23018. return this.value && this.value.isNode ? this.value : float();
  23019. }
  23020. serialize( data ) {
  23021. super.serialize( data );
  23022. if ( this.value !== null ) {
  23023. if ( this.inputType === 'ArrayBuffer' ) {
  23024. data.value = arrayBufferToBase64( this.value );
  23025. } else {
  23026. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  23027. }
  23028. } else {
  23029. data.value = null;
  23030. }
  23031. data.inputType = this.inputType;
  23032. data.outputType = this.outputType;
  23033. }
  23034. deserialize( data ) {
  23035. super.deserialize( data );
  23036. let value = null;
  23037. if ( data.value !== null ) {
  23038. if ( data.inputType === 'ArrayBuffer' ) {
  23039. value = base64ToArrayBuffer( data.value );
  23040. } else if ( data.inputType === 'Texture' ) {
  23041. value = data.meta.textures[ data.value ];
  23042. } else {
  23043. value = data.meta.nodes[ data.value ] || null;
  23044. }
  23045. }
  23046. this.value = value;
  23047. this.inputType = data.inputType;
  23048. this.outputType = data.outputType;
  23049. }
  23050. }
  23051. /**
  23052. * TSL function for creating a scriptable value node.
  23053. *
  23054. * @function
  23055. * @param {Any} [value=null] - The value.
  23056. * @returns {ScriptableValueNode}
  23057. */
  23058. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  23059. /** @module ScriptableNode **/
  23060. /**
  23061. * A Map-like data structure for managing resources of scriptable nodes.
  23062. *
  23063. * @augments Map
  23064. */
  23065. class Resources extends Map {
  23066. get( key, callback = null, ...params ) {
  23067. if ( this.has( key ) ) return super.get( key );
  23068. if ( callback !== null ) {
  23069. const value = callback( ...params );
  23070. this.set( key, value );
  23071. return value;
  23072. }
  23073. }
  23074. }
  23075. class Parameters {
  23076. constructor( scriptableNode ) {
  23077. this.scriptableNode = scriptableNode;
  23078. }
  23079. get parameters() {
  23080. return this.scriptableNode.parameters;
  23081. }
  23082. get layout() {
  23083. return this.scriptableNode.getLayout();
  23084. }
  23085. getInputLayout( id ) {
  23086. return this.scriptableNode.getInputLayout( id );
  23087. }
  23088. get( name ) {
  23089. const param = this.parameters[ name ];
  23090. const value = param ? param.getValue() : null;
  23091. return value;
  23092. }
  23093. }
  23094. /**
  23095. * Defines the resources (e.g. namespaces) of scriptable nodes.
  23096. *
  23097. * @type {Resources}
  23098. */
  23099. const ScriptableNodeResources = new Resources();
  23100. /**
  23101. * This type of node allows to implement nodes with custom scripts. The script
  23102. * section is represented as an instance of `CodeNode` written with JavaScript.
  23103. * The script itself must adhere to a specific structure.
  23104. *
  23105. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  23106. * - layout: The layout object defines the script's interface (inputs and outputs).
  23107. *
  23108. * ```js
  23109. * ScriptableNodeResources.set( 'TSL', TSL );
  23110. *
  23111. * const scriptableNode = scriptable( js( `
  23112. * layout = {
  23113. * outputType: 'node',
  23114. * elements: [
  23115. * { name: 'source', inputType: 'node' },
  23116. * ]
  23117. * };
  23118. *
  23119. * const { mul, oscSine } = TSL;
  23120. *
  23121. * function main() {
  23122. * const source = parameters.get( 'source' ) || float();
  23123. * return mul( source, oscSine() ) );
  23124. * }
  23125. *
  23126. * ` ) );
  23127. *
  23128. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  23129. *
  23130. * const material = new THREE.MeshBasicNodeMaterial();
  23131. * material.colorNode = scriptableNode;
  23132. * ```
  23133. *
  23134. * @augments Node
  23135. */
  23136. class ScriptableNode extends Node {
  23137. static get type() {
  23138. return 'ScriptableNode';
  23139. }
  23140. /**
  23141. * Constructs a new scriptable node.
  23142. *
  23143. * @param {CodeNode?} [codeNode=null] - The code node.
  23144. * @param {Object} [parameters={}] - The parameters definition.
  23145. */
  23146. constructor( codeNode = null, parameters = {} ) {
  23147. super();
  23148. /**
  23149. * The code node.
  23150. *
  23151. * @type {CodeNode?}
  23152. * @default null
  23153. */
  23154. this.codeNode = codeNode;
  23155. /**
  23156. * The parameters definition.
  23157. *
  23158. * @type {Object}
  23159. * @default {}
  23160. */
  23161. this.parameters = parameters;
  23162. this._local = new Resources();
  23163. this._output = scriptableValue();
  23164. this._outputs = {};
  23165. this._source = this.source;
  23166. this._method = null;
  23167. this._object = null;
  23168. this._value = null;
  23169. this._needsOutputUpdate = true;
  23170. this.onRefresh = this.onRefresh.bind( this );
  23171. /**
  23172. * This flag can be used for type testing.
  23173. *
  23174. * @type {Boolean}
  23175. * @readonly
  23176. * @default true
  23177. */
  23178. this.isScriptableNode = true;
  23179. }
  23180. /**
  23181. * The source code of the scriptable node.
  23182. *
  23183. * @type {String}
  23184. */
  23185. get source() {
  23186. return this.codeNode ? this.codeNode.code : '';
  23187. }
  23188. /**
  23189. * Sets the reference of a local script variable.
  23190. *
  23191. * @param {String} name - The variable name.
  23192. * @param {Object} value - The reference to set.
  23193. * @return {Resources} The resource map
  23194. */
  23195. setLocal( name, value ) {
  23196. return this._local.set( name, value );
  23197. }
  23198. /**
  23199. * Gets the value of a local script variable.
  23200. *
  23201. * @param {String} name - The variable name.
  23202. * @return {Object} The value.
  23203. */
  23204. getLocal( name ) {
  23205. return this._local.get( name );
  23206. }
  23207. /**
  23208. * Event listener for the `refresh` event.
  23209. */
  23210. onRefresh() {
  23211. this._refresh();
  23212. }
  23213. /**
  23214. * Returns an input from the layout with the given id/name.
  23215. *
  23216. * @param {String} id - The id/name of the input.
  23217. * @return {Object} The element entry.
  23218. */
  23219. getInputLayout( id ) {
  23220. for ( const element of this.getLayout() ) {
  23221. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  23222. return element;
  23223. }
  23224. }
  23225. }
  23226. /**
  23227. * Returns an output from the layout with the given id/name.
  23228. *
  23229. * @param {String} id - The id/name of the output.
  23230. * @return {Object} The element entry.
  23231. */
  23232. getOutputLayout( id ) {
  23233. for ( const element of this.getLayout() ) {
  23234. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  23235. return element;
  23236. }
  23237. }
  23238. }
  23239. /**
  23240. * Defines a script output for the given name and value.
  23241. *
  23242. * @param {String} name - The name of the output.
  23243. * @param {Node} value - The node value.
  23244. * @return {ScriptableNode} A reference to this node.
  23245. */
  23246. setOutput( name, value ) {
  23247. const outputs = this._outputs;
  23248. if ( outputs[ name ] === undefined ) {
  23249. outputs[ name ] = scriptableValue( value );
  23250. } else {
  23251. outputs[ name ].value = value;
  23252. }
  23253. return this;
  23254. }
  23255. /**
  23256. * Returns a script output for the given name.
  23257. *
  23258. * @param {String} name - The name of the output.
  23259. * @return {ScriptableValueNode} The node value.
  23260. */
  23261. getOutput( name ) {
  23262. return this._outputs[ name ];
  23263. }
  23264. /**
  23265. * Returns a parameter for the given name
  23266. *
  23267. * @param {String} name - The name of the parameter.
  23268. * @return {ScriptableValueNode} The node value.
  23269. */
  23270. getParameter( name ) {
  23271. return this.parameters[ name ];
  23272. }
  23273. /**
  23274. * Sets a value for the given parameter name.
  23275. *
  23276. * @param {String} name - The parameter name.
  23277. * @param {Any} value - The parameter value.
  23278. * @return {ScriptableNode} A reference to this node.
  23279. */
  23280. setParameter( name, value ) {
  23281. const parameters = this.parameters;
  23282. if ( value && value.isScriptableNode ) {
  23283. this.deleteParameter( name );
  23284. parameters[ name ] = value;
  23285. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  23286. } else if ( value && value.isScriptableValueNode ) {
  23287. this.deleteParameter( name );
  23288. parameters[ name ] = value;
  23289. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23290. } else if ( parameters[ name ] === undefined ) {
  23291. parameters[ name ] = scriptableValue( value );
  23292. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23293. } else {
  23294. parameters[ name ].value = value;
  23295. }
  23296. return this;
  23297. }
  23298. /**
  23299. * Returns the value of this node which is the value of
  23300. * the default output.
  23301. *
  23302. * @return {Node} The value.
  23303. */
  23304. getValue() {
  23305. return this.getDefaultOutput().getValue();
  23306. }
  23307. /**
  23308. * Deletes a parameter from the script.
  23309. *
  23310. * @param {String} name - The parameter to remove.
  23311. * @return {ScriptableNode} A reference to this node.
  23312. */
  23313. deleteParameter( name ) {
  23314. let valueNode = this.parameters[ name ];
  23315. if ( valueNode ) {
  23316. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23317. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  23318. }
  23319. return this;
  23320. }
  23321. /**
  23322. * Deletes all parameters from the script.
  23323. *
  23324. * @return {ScriptableNode} A reference to this node.
  23325. */
  23326. clearParameters() {
  23327. for ( const name of Object.keys( this.parameters ) ) {
  23328. this.deleteParameter( name );
  23329. }
  23330. this.needsUpdate = true;
  23331. return this;
  23332. }
  23333. /**
  23334. * Calls a function from the script.
  23335. *
  23336. * @param {String} name - The function name.
  23337. * @param {...Any} params - A list of parameters.
  23338. * @return {Any} The result of the function call.
  23339. */
  23340. call( name, ...params ) {
  23341. const object = this.getObject();
  23342. const method = object[ name ];
  23343. if ( typeof method === 'function' ) {
  23344. return method( ...params );
  23345. }
  23346. }
  23347. /**
  23348. * Asynchronously calls a function from the script.
  23349. *
  23350. * @param {String} name - The function name.
  23351. * @param {...Any} params - A list of parameters.
  23352. * @return {Promise<Any>} The result of the function call.
  23353. */
  23354. async callAsync( name, ...params ) {
  23355. const object = this.getObject();
  23356. const method = object[ name ];
  23357. if ( typeof method === 'function' ) {
  23358. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  23359. }
  23360. }
  23361. /**
  23362. * Overwritten since the node types is inferred from the script's output.
  23363. *
  23364. * @param {NodeBuilder} builder - The current node builder
  23365. * @return {String} The node type.
  23366. */
  23367. getNodeType( builder ) {
  23368. return this.getDefaultOutputNode().getNodeType( builder );
  23369. }
  23370. /**
  23371. * Refreshes the script node.
  23372. *
  23373. * @param {String?} [output=null] - An optional output.
  23374. */
  23375. refresh( output = null ) {
  23376. if ( output !== null ) {
  23377. this.getOutput( output ).refresh();
  23378. } else {
  23379. this._refresh();
  23380. }
  23381. }
  23382. /**
  23383. * Returns an object representation of the script.
  23384. *
  23385. * @return {Object} The result object.
  23386. */
  23387. getObject() {
  23388. if ( this.needsUpdate ) this.dispose();
  23389. if ( this._object !== null ) return this._object;
  23390. //
  23391. const refresh = () => this.refresh();
  23392. const setOutput = ( id, value ) => this.setOutput( id, value );
  23393. const parameters = new Parameters( this );
  23394. const THREE = ScriptableNodeResources.get( 'THREE' );
  23395. const TSL = ScriptableNodeResources.get( 'TSL' );
  23396. const method = this.getMethod();
  23397. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  23398. this._object = method( ...params );
  23399. const layout = this._object.layout;
  23400. if ( layout ) {
  23401. if ( layout.cache === false ) {
  23402. this._local.clear();
  23403. }
  23404. // default output
  23405. this._output.outputType = layout.outputType || null;
  23406. if ( Array.isArray( layout.elements ) ) {
  23407. for ( const element of layout.elements ) {
  23408. const id = element.id || element.name;
  23409. if ( element.inputType ) {
  23410. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  23411. this.getParameter( id ).inputType = element.inputType;
  23412. }
  23413. if ( element.outputType ) {
  23414. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  23415. this.getOutput( id ).outputType = element.outputType;
  23416. }
  23417. }
  23418. }
  23419. }
  23420. return this._object;
  23421. }
  23422. deserialize( data ) {
  23423. super.deserialize( data );
  23424. for ( const name in this.parameters ) {
  23425. let valueNode = this.parameters[ name ];
  23426. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23427. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  23428. }
  23429. }
  23430. /**
  23431. * Returns the layout of the script.
  23432. *
  23433. * @return {Object} The script's layout.
  23434. */
  23435. getLayout() {
  23436. return this.getObject().layout;
  23437. }
  23438. /**
  23439. * Returns default node output of the script.
  23440. *
  23441. * @return {Node} The default node output.
  23442. */
  23443. getDefaultOutputNode() {
  23444. const output = this.getDefaultOutput().value;
  23445. if ( output && output.isNode ) {
  23446. return output;
  23447. }
  23448. return float();
  23449. }
  23450. /**
  23451. * Returns default output of the script.
  23452. *
  23453. * @return {ScriptableValueNode} The default output.
  23454. */
  23455. getDefaultOutput() {
  23456. return this._exec()._output;
  23457. }
  23458. /**
  23459. * Returns a function created from the node's script.
  23460. *
  23461. * @return {Function} The function representing the node's code.
  23462. */
  23463. getMethod() {
  23464. if ( this.needsUpdate ) this.dispose();
  23465. if ( this._method !== null ) return this._method;
  23466. //
  23467. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  23468. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  23469. const properties = interfaceProps.join( ', ' );
  23470. const declarations = 'var ' + properties + '; var output = {};\n';
  23471. const returns = '\nreturn { ...output, ' + properties + ' };';
  23472. const code = declarations + this.codeNode.code + returns;
  23473. //
  23474. this._method = new Function( ...parametersProps, code );
  23475. return this._method;
  23476. }
  23477. /**
  23478. * Frees all internal resources.
  23479. */
  23480. dispose() {
  23481. if ( this._method === null ) return;
  23482. if ( this._object && typeof this._object.dispose === 'function' ) {
  23483. this._object.dispose();
  23484. }
  23485. this._method = null;
  23486. this._object = null;
  23487. this._source = null;
  23488. this._value = null;
  23489. this._needsOutputUpdate = true;
  23490. this._output.value = null;
  23491. this._outputs = {};
  23492. }
  23493. setup() {
  23494. return this.getDefaultOutputNode();
  23495. }
  23496. getCacheKey( force ) {
  23497. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  23498. for ( const param in this.parameters ) {
  23499. values.push( this.parameters[ param ].getCacheKey( force ) );
  23500. }
  23501. return hashArray( values );
  23502. }
  23503. set needsUpdate( value ) {
  23504. if ( value === true ) this.dispose();
  23505. }
  23506. get needsUpdate() {
  23507. return this.source !== this._source;
  23508. }
  23509. /**
  23510. * Executes the `main` function of the script.
  23511. *
  23512. * @private
  23513. * @return {ScriptableNode} A reference to this node.
  23514. */
  23515. _exec() {
  23516. if ( this.codeNode === null ) return this;
  23517. if ( this._needsOutputUpdate === true ) {
  23518. this._value = this.call( 'main' );
  23519. this._needsOutputUpdate = false;
  23520. }
  23521. this._output.value = this._value;
  23522. return this;
  23523. }
  23524. /**
  23525. * Executes the refresh.
  23526. *
  23527. * @private
  23528. */
  23529. _refresh() {
  23530. this.needsUpdate = true;
  23531. this._exec();
  23532. this._output.refresh();
  23533. }
  23534. }
  23535. /**
  23536. * TSL function for creating a scriptable node.
  23537. *
  23538. * @function
  23539. * @param {CodeNode?} [codeNode=null] - The code node.
  23540. * @param {Object} [parameters={}] - The parameters definition.
  23541. * @returns {ScriptableNode}
  23542. */
  23543. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  23544. /** @module Fog **/
  23545. /**
  23546. * Returns a node that represents the `z` coordinate in view space
  23547. * for the current fragment. It's a different representation of the
  23548. * default depth value.
  23549. *
  23550. * This value can be part of a computation that defines how the fog
  23551. * density increases when moving away from the camera.
  23552. *
  23553. * @param {NodeBuilder} builder - The current node builder.
  23554. * @return {Node} The viewZ node.
  23555. */
  23556. function getViewZNode( builder ) {
  23557. let viewZ;
  23558. const getViewZ = builder.context.getViewZ;
  23559. if ( getViewZ !== undefined ) {
  23560. viewZ = getViewZ( this );
  23561. }
  23562. return ( viewZ || positionView.z ).negate();
  23563. }
  23564. /**
  23565. * Constructs a new range factor node.
  23566. *
  23567. * @function
  23568. * @param {Node} near - Defines the near value.
  23569. * @param {Node} far - Defines the far value.
  23570. */
  23571. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  23572. const viewZ = getViewZNode( builder );
  23573. return smoothstep( near, far, viewZ );
  23574. } );
  23575. /**
  23576. * Represents an exponential squared fog. This type of fog gives
  23577. * a clear view near the camera and a faster than exponentially
  23578. * densening fog farther from the camera.
  23579. *
  23580. * @function
  23581. * @param {Node} density - Defines the fog density.
  23582. */
  23583. const densityFogFactor = Fn( ( [ density ], builder ) => {
  23584. const viewZ = getViewZNode( builder );
  23585. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  23586. } );
  23587. /**
  23588. * This class can be used to configure a fog for the scene.
  23589. * Nodes of this type are assigned to `Scene.fogNode`.
  23590. *
  23591. * @function
  23592. * @param {Node} color - Defines the color of the fog.
  23593. * @param {Node} factor - Defines how the fog is factored in the scene.
  23594. */
  23595. const fog = Fn( ( [ color, factor ] ) => {
  23596. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  23597. } );
  23598. // Deprecated
  23599. /**
  23600. * @function
  23601. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  23602. *
  23603. * @param {Node} color
  23604. * @param {Node} near
  23605. * @param {Node} far
  23606. * @returns {Function}
  23607. */
  23608. function rangeFog( color, near, far ) { // @deprecated, r171
  23609. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  23610. return fog( color, rangeFogFactor( near, far ) );
  23611. }
  23612. /**
  23613. * @function
  23614. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  23615. *
  23616. * @param {Node} color
  23617. * @param {Node} density
  23618. * @returns {Function}
  23619. */
  23620. function densityFog( color, density ) { // @deprecated, r171
  23621. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  23622. return fog( color, densityFogFactor( density ) );
  23623. }
  23624. /** @module RangeNode **/
  23625. let min = null;
  23626. let max = null;
  23627. /**
  23628. * `RangeNode` generates random instanced attribute data in a defined range.
  23629. * An exemplary use case for this utility node is to generate random per-instance
  23630. * colors:
  23631. * ```js
  23632. * const material = new MeshBasicNodeMaterial();
  23633. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  23634. * const mesh = new InstancedMesh( geometry, material, count );
  23635. * ```
  23636. * @augments Node
  23637. */
  23638. class RangeNode extends Node {
  23639. static get type() {
  23640. return 'RangeNode';
  23641. }
  23642. /**
  23643. * Constructs a new range node.
  23644. *
  23645. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23646. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23647. */
  23648. constructor( minNode = float(), maxNode = float() ) {
  23649. super();
  23650. /**
  23651. * A node defining the lower bound of the range.
  23652. *
  23653. * @type {Node<any>}
  23654. * @default float()
  23655. */
  23656. this.minNode = minNode;
  23657. /**
  23658. * A node defining the upper bound of the range.
  23659. *
  23660. * @type {Node<any>}
  23661. * @default float()
  23662. */
  23663. this.maxNode = maxNode;
  23664. }
  23665. /**
  23666. * Returns the vector length which is computed based on the range definition.
  23667. *
  23668. * @param {NodeBuilder} builder - The current node builder.
  23669. * @return {Number} The vector length.
  23670. */
  23671. getVectorLength( builder ) {
  23672. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  23673. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  23674. return minLength > maxLength ? minLength : maxLength;
  23675. }
  23676. /**
  23677. * This method is overwritten since the node type is inferred from range definition.
  23678. *
  23679. * @param {NodeBuilder} builder - The current node builder.
  23680. * @return {String} The node type.
  23681. */
  23682. getNodeType( builder ) {
  23683. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  23684. }
  23685. setup( builder ) {
  23686. const object = builder.object;
  23687. let output = null;
  23688. if ( object.count > 1 ) {
  23689. const minValue = this.minNode.value;
  23690. const maxValue = this.maxNode.value;
  23691. const minLength = builder.getTypeLength( getValueType( minValue ) );
  23692. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  23693. min = min || new Vector4();
  23694. max = max || new Vector4();
  23695. min.setScalar( 0 );
  23696. max.setScalar( 0 );
  23697. if ( minLength === 1 ) min.setScalar( minValue );
  23698. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  23699. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  23700. if ( maxLength === 1 ) max.setScalar( maxValue );
  23701. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  23702. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  23703. const stride = 4;
  23704. const length = stride * object.count;
  23705. const array = new Float32Array( length );
  23706. for ( let i = 0; i < length; i ++ ) {
  23707. const index = i % stride;
  23708. const minElementValue = min.getComponent( index );
  23709. const maxElementValue = max.getComponent( index );
  23710. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  23711. }
  23712. const nodeType = this.getNodeType( builder );
  23713. if ( object.count <= 4096 ) {
  23714. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  23715. } else {
  23716. // TODO: Improve anonymous buffer attribute creation removing this part
  23717. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  23718. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  23719. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  23720. }
  23721. } else {
  23722. output = float( 0 );
  23723. }
  23724. return output;
  23725. }
  23726. }
  23727. /**
  23728. * TSL function for creating a range node.
  23729. *
  23730. * @function
  23731. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23732. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23733. * @returns {RangeNode}
  23734. */
  23735. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  23736. /** @module ComputeBuiltinNode **/
  23737. /**
  23738. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  23739. * about the currently running dispatch and/or the device it is running on.
  23740. *
  23741. * This node can only be used with a WebGPU backend.
  23742. *
  23743. * @augments Node
  23744. */
  23745. class ComputeBuiltinNode extends Node {
  23746. static get type() {
  23747. return 'ComputeBuiltinNode';
  23748. }
  23749. /**
  23750. * Constructs a new compute builtin node.
  23751. *
  23752. * @param {String} builtinName - The built-in name.
  23753. * @param {String} nodeType - The node type.
  23754. */
  23755. constructor( builtinName, nodeType ) {
  23756. super( nodeType );
  23757. /**
  23758. * The built-in name.
  23759. *
  23760. * @private
  23761. * @type {String}
  23762. */
  23763. this._builtinName = builtinName;
  23764. }
  23765. /**
  23766. * This method is overwritten since hash is derived from the built-in name.
  23767. *
  23768. * @param {NodeBuilder} builder - The current node builder.
  23769. * @return {String} The hash.
  23770. */
  23771. getHash( builder ) {
  23772. return this.getBuiltinName( builder );
  23773. }
  23774. /**
  23775. * This method is overwritten since the node type is simply derived from `nodeType`..
  23776. *
  23777. * @param {NodeBuilder} builder - The current node builder.
  23778. * @return {String} The node type.
  23779. */
  23780. getNodeType( /*builder*/ ) {
  23781. return this.nodeType;
  23782. }
  23783. /**
  23784. * Sets the builtin name.
  23785. *
  23786. * @param {String} builtinName - The built-in name.
  23787. * @return {ComputeBuiltinNode} A reference to this node.
  23788. */
  23789. setBuiltinName( builtinName ) {
  23790. this._builtinName = builtinName;
  23791. return this;
  23792. }
  23793. /**
  23794. * Returns the builtin name.
  23795. *
  23796. * @param {NodeBuilder} builder - The current node builder.
  23797. * @return {String} The builtin name.
  23798. */
  23799. getBuiltinName( /*builder*/ ) {
  23800. return this._builtinName;
  23801. }
  23802. /**
  23803. * Whether the current node builder has the builtin or not.
  23804. *
  23805. * @param {NodeBuilder} builder - The current node builder.
  23806. */
  23807. hasBuiltin( builder ) {
  23808. builder.hasBuiltin( this._builtinName );
  23809. }
  23810. generate( builder, output ) {
  23811. const builtinName = this.getBuiltinName( builder );
  23812. const nodeType = this.getNodeType( builder );
  23813. if ( builder.shaderStage === 'compute' ) {
  23814. return builder.format( builtinName, nodeType, output );
  23815. } else {
  23816. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  23817. return builder.generateConst( nodeType );
  23818. }
  23819. }
  23820. serialize( data ) {
  23821. super.serialize( data );
  23822. data.global = this.global;
  23823. data._builtinName = this._builtinName;
  23824. }
  23825. deserialize( data ) {
  23826. super.deserialize( data );
  23827. this.global = data.global;
  23828. this._builtinName = data._builtinName;
  23829. }
  23830. }
  23831. /**
  23832. * TSL function for creating a compute builtin node.
  23833. *
  23834. * @function
  23835. * @param {String} name - The built-in name.
  23836. * @param {String} nodeType - The node type.
  23837. * @returns {ComputeBuiltinNode}
  23838. */
  23839. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  23840. /**
  23841. * TSL function for creating a `numWorkgroups` builtin node.
  23842. * Represents the number of workgroups dispatched by the compute shader.
  23843. * ```js
  23844. * // Run 512 invocations/threads with a workgroup size of 128.
  23845. * const computeFn = Fn(() => {
  23846. *
  23847. * // numWorkgroups.x = 4
  23848. * storageBuffer.element(0).assign(numWorkgroups.x)
  23849. *
  23850. * })().compute(512, [128]);
  23851. *
  23852. * // Run 512 invocations/threads with the default workgroup size of 64.
  23853. * const computeFn = Fn(() => {
  23854. *
  23855. * // numWorkgroups.x = 8
  23856. * storageBuffer.element(0).assign(numWorkgroups.x)
  23857. *
  23858. * })().compute(512);
  23859. * ```
  23860. *
  23861. * @function
  23862. * @returns {ComputeBuiltinNode<uvec3>}
  23863. */
  23864. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  23865. /**
  23866. * TSL function for creating a `workgroupId` builtin node.
  23867. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  23868. * ```js
  23869. * // Execute 12 compute threads with a workgroup size of 3.
  23870. * const computeFn = Fn( () => {
  23871. *
  23872. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  23873. *
  23874. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  23875. *
  23876. * } ).Else( () => {
  23877. *
  23878. * storageBuffer.element( instanceIndex ).assign( 0 );
  23879. *
  23880. * } );
  23881. *
  23882. * } )().compute( 12, [ 3 ] );
  23883. *
  23884. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  23885. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  23886. * ```
  23887. *
  23888. * @function
  23889. * @returns {ComputeBuiltinNode<uvec3>}
  23890. */
  23891. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  23892. /**
  23893. * TSL function for creating a `globalId` builtin node. A non-linearized 3-dimensional
  23894. * representation of the current invocation's position within a 3D global grid.
  23895. *
  23896. * @function
  23897. * @returns {ComputeBuiltinNode<uvec3>}
  23898. */
  23899. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  23900. /**
  23901. * TSL function for creating a `localId` builtin node. A non-linearized 3-dimensional
  23902. * representation of the current invocation's position within a 3D workgroup grid.
  23903. *
  23904. * @function
  23905. * @returns {ComputeBuiltinNode<uvec3>}
  23906. */
  23907. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  23908. /**
  23909. * TSL function for creating a `subgroupSize` builtin node. A device dependent variable
  23910. * that exposes the size of the current invocation's subgroup.
  23911. *
  23912. * @function
  23913. * @returns {ComputeBuiltinNode<uint>}
  23914. */
  23915. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  23916. /** @module BarrierNode **/
  23917. /**
  23918. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  23919. *
  23920. * This node can only be used with a WebGPU backend.
  23921. *
  23922. * @augments Node
  23923. */
  23924. class BarrierNode extends Node {
  23925. /**
  23926. * Constructs a new barrier node.
  23927. *
  23928. * @param {String} scope - The scope defines the behavior of the node.
  23929. */
  23930. constructor( scope ) {
  23931. super();
  23932. this.scope = scope;
  23933. }
  23934. generate( builder ) {
  23935. const { scope } = this;
  23936. const { renderer } = builder;
  23937. if ( renderer.backend.isWebGLBackend === true ) {
  23938. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  23939. } else {
  23940. builder.addLineFlowCode( `${scope}Barrier()`, this );
  23941. }
  23942. }
  23943. }
  23944. /**
  23945. * TSL function for creating a barrier node.
  23946. *
  23947. * @function
  23948. * @param {String} scope - The scope defines the behavior of the node..
  23949. * @returns {BarrierNode}
  23950. */
  23951. const barrier = nodeProxy( BarrierNode );
  23952. /**
  23953. * TSL function for creating a workgroup barrier. All compute shader
  23954. * invocations must wait for each invocation within a workgroup to
  23955. * complete before the barrier can be surpassed.
  23956. *
  23957. * @function
  23958. * @returns {BarrierNode}
  23959. */
  23960. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  23961. /**
  23962. * TSL function for creating a storage barrier. All invocations must
  23963. * wait for each access to variables within the 'storage' address space
  23964. * to complete before the barrier can be passed.
  23965. *
  23966. * @function
  23967. * @returns {BarrierNode}
  23968. */
  23969. const storageBarrier = () => barrier( 'storage' ).append();
  23970. /**
  23971. * TSL function for creating a texture barrier. All invocations must
  23972. * wait for each access to variables within the 'texture' address space
  23973. * to complete before the barrier can be passed.
  23974. *
  23975. * @function
  23976. * @returns {BarrierNode}
  23977. */
  23978. const textureBarrier = () => barrier( 'texture' ).append();
  23979. /** @module WorkgroupInfoNode **/
  23980. /**
  23981. * Represents an element of a 'workgroup' scoped buffer.
  23982. *
  23983. * @augments ArrayElementNode
  23984. */
  23985. class WorkgroupInfoElementNode extends ArrayElementNode {
  23986. /**
  23987. * Constructs a new workgroup info element node.
  23988. *
  23989. * @param {Node} workgroupInfoNode - The workgroup info node.
  23990. * @param {Node} indexNode - The index node that defines the element access.
  23991. */
  23992. constructor( workgroupInfoNode, indexNode ) {
  23993. super( workgroupInfoNode, indexNode );
  23994. /**
  23995. * This flag can be used for type testing.
  23996. *
  23997. * @type {Boolean}
  23998. * @readonly
  23999. * @default true
  24000. */
  24001. this.isWorkgroupInfoElementNode = true;
  24002. }
  24003. generate( builder, output ) {
  24004. let snippet;
  24005. const isAssignContext = builder.context.assign;
  24006. snippet = super.generate( builder );
  24007. if ( isAssignContext !== true ) {
  24008. const type = this.getNodeType( builder );
  24009. snippet = builder.format( snippet, type, output );
  24010. }
  24011. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  24012. return snippet;
  24013. }
  24014. }
  24015. /**
  24016. * A node allowing the user to create a 'workgroup' scoped buffer within the
  24017. * context of a compute shader. Typically, workgroup scoped buffers are
  24018. * created to hold data that is transferred from a global storage scope into
  24019. * a local workgroup scope. For invocations within a workgroup, data
  24020. * access speeds on 'workgroup' scoped buffers can be significantly faster
  24021. * than similar access operations on globally accessible storage buffers.
  24022. *
  24023. * This node can only be used with a WebGPU backend.
  24024. *
  24025. * @augments Node
  24026. */
  24027. class WorkgroupInfoNode extends Node {
  24028. /**
  24029. * Constructs a new buffer scoped to type scope.
  24030. *
  24031. * @param {String} scope - TODO.
  24032. * @param {String} bufferType - The data type of a 'workgroup' scoped buffer element.
  24033. * @param {Number} [bufferCount=0] - The number of elements in the buffer.
  24034. */
  24035. constructor( scope, bufferType, bufferCount = 0 ) {
  24036. super( bufferType );
  24037. /**
  24038. * The buffer type.
  24039. *
  24040. * @type {String}
  24041. */
  24042. this.bufferType = bufferType;
  24043. /**
  24044. * The buffer count.
  24045. *
  24046. * @type {Number}
  24047. * @default 0
  24048. */
  24049. this.bufferCount = bufferCount;
  24050. /**
  24051. * This flag can be used for type testing.
  24052. *
  24053. * @type {Boolean}
  24054. * @readonly
  24055. * @default true
  24056. */
  24057. this.isWorkgroupInfoNode = true;
  24058. /**
  24059. * The data type of the array buffer.
  24060. *
  24061. * @type {String}
  24062. */
  24063. this.elementType = bufferType;
  24064. /**
  24065. * TODO.
  24066. *
  24067. * @type {String}
  24068. */
  24069. this.scope = scope;
  24070. }
  24071. /**
  24072. * Sets the name/label of this node.
  24073. *
  24074. * @param {String} name - The name to set.
  24075. * @return {WorkgroupInfoNode} A reference to this node.
  24076. */
  24077. label( name ) {
  24078. this.name = name;
  24079. return this;
  24080. }
  24081. /**
  24082. * Sets the scope of this node.
  24083. *
  24084. * @param {String} scope - The scope to set.
  24085. * @return {WorkgroupInfoNode} A reference to this node.
  24086. */
  24087. setScope( scope ) {
  24088. this.scope = scope;
  24089. return this;
  24090. }
  24091. /**
  24092. * The data type of the array buffer.
  24093. *
  24094. * @return {String} The element type.
  24095. */
  24096. getElementType() {
  24097. return this.elementType;
  24098. }
  24099. /**
  24100. * Overwrites the default implementation since the input type
  24101. * is inferred from the scope.
  24102. *
  24103. * @param {NodeBuilder} builder - The current node builder.
  24104. * @return {String} The input type.
  24105. */
  24106. getInputType( /*builder*/ ) {
  24107. return `${this.scope}Array`;
  24108. }
  24109. /**
  24110. * This method can be used to access elements via an index node.
  24111. *
  24112. * @param {IndexNode} indexNode - indexNode.
  24113. * @return {WorkgroupInfoElementNode} A reference to an element.
  24114. */
  24115. element( indexNode ) {
  24116. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  24117. }
  24118. generate( builder ) {
  24119. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  24120. }
  24121. }
  24122. /**
  24123. * TSL function for creating a workgroup info node.
  24124. * Creates a new 'workgroup' scoped array buffer.
  24125. *
  24126. * @function
  24127. * @param {String} type - The data type of a 'workgroup' scoped buffer element.
  24128. * @param {Number} [count=0] - The number of elements in the buffer.
  24129. * @returns {WorkgroupInfoNode}
  24130. */
  24131. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  24132. /** @module AtomicFunctionNode **/
  24133. /**
  24134. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  24135. * within a shader. In an atomic function, any modification to an atomic variable will
  24136. * occur as an indivisible step with a defined order relative to other modifications.
  24137. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  24138. * atomic operations will not interfere with each other.
  24139. *
  24140. * This node can only be used with a WebGPU backend.
  24141. *
  24142. * @augments TempNode
  24143. */
  24144. class AtomicFunctionNode extends TempNode {
  24145. static get type() {
  24146. return 'AtomicFunctionNode';
  24147. }
  24148. /**
  24149. * Constructs a new atomic function node.
  24150. *
  24151. * @param {String} method - The signature of the atomic function to construct.
  24152. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24153. * @param {Node} valueNode - The value that mutates the atomic variable.
  24154. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24155. */
  24156. constructor( method, pointerNode, valueNode, storeNode = null ) {
  24157. super( 'uint' );
  24158. /**
  24159. * The signature of the atomic function to construct.
  24160. *
  24161. * @type {String}
  24162. */
  24163. this.method = method;
  24164. /**
  24165. * An atomic variable or element of an atomic buffer.
  24166. *
  24167. * @type {Node}
  24168. */
  24169. this.pointerNode = pointerNode;
  24170. /**
  24171. * A value that modifies the atomic variable.
  24172. *
  24173. * @type {Node}
  24174. */
  24175. this.valueNode = valueNode;
  24176. /**
  24177. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24178. *
  24179. * @type {Node?}
  24180. * @default null
  24181. */
  24182. this.storeNode = storeNode;
  24183. }
  24184. /**
  24185. * Overwrites the default implementation to return the type of
  24186. * the pointer node.
  24187. *
  24188. * @param {NodeBuilder} builder - The current node builder.
  24189. * @return {String} The input type.
  24190. */
  24191. getInputType( builder ) {
  24192. return this.pointerNode.getNodeType( builder );
  24193. }
  24194. /**
  24195. * Overwritten since the node type is inferred from the input type.
  24196. *
  24197. * @param {NodeBuilder} builder - The current node builder.
  24198. * @return {String} The node type.
  24199. */
  24200. getNodeType( builder ) {
  24201. return this.getInputType( builder );
  24202. }
  24203. generate( builder ) {
  24204. const method = this.method;
  24205. const type = this.getNodeType( builder );
  24206. const inputType = this.getInputType( builder );
  24207. const a = this.pointerNode;
  24208. const b = this.valueNode;
  24209. const params = [];
  24210. params.push( `&${ a.build( builder, inputType ) }` );
  24211. params.push( b.build( builder, inputType ) );
  24212. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  24213. if ( this.storeNode !== null ) {
  24214. const varSnippet = this.storeNode.build( builder, inputType );
  24215. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  24216. } else {
  24217. builder.addLineFlowCode( methodSnippet, this );
  24218. }
  24219. }
  24220. }
  24221. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  24222. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  24223. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  24224. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  24225. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  24226. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  24227. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  24228. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  24229. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  24230. /**
  24231. * TSL function for creating an atomic function node.
  24232. *
  24233. * @function
  24234. * @param {String} method - The signature of the atomic function to construct.
  24235. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24236. * @param {Node} valueNode - The value that mutates the atomic variable.
  24237. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24238. * @returns {AtomicFunctionNode}
  24239. */
  24240. const atomicNode = nodeProxy( AtomicFunctionNode );
  24241. /**
  24242. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  24243. *
  24244. * @function
  24245. * @param {String} method - The signature of the atomic function to construct.
  24246. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24247. * @param {Node} valueNode - The value that mutates the atomic variable.
  24248. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24249. * @returns {AtomicFunctionNode}
  24250. */
  24251. const atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  24252. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  24253. node.append();
  24254. return node;
  24255. };
  24256. /**
  24257. * Stores a value in the atomic variable.
  24258. *
  24259. * @function
  24260. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24261. * @param {Node} valueNode - The value that mutates the atomic variable.
  24262. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24263. * @returns {AtomicFunctionNode}
  24264. */
  24265. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  24266. /**
  24267. * Increments the value stored in the atomic variable.
  24268. *
  24269. * @function
  24270. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24271. * @param {Node} valueNode - The value that mutates the atomic variable.
  24272. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24273. * @returns {AtomicFunctionNode}
  24274. */
  24275. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  24276. /**
  24277. * Decrements the value stored in the atomic variable.
  24278. *
  24279. * @function
  24280. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24281. * @param {Node} valueNode - The value that mutates the atomic variable.
  24282. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24283. * @returns {AtomicFunctionNode}
  24284. */
  24285. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  24286. /**
  24287. * Stores in an atomic variable the maximum between its current value and a parameter.
  24288. *
  24289. * @function
  24290. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24291. * @param {Node} valueNode - The value that mutates the atomic variable.
  24292. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24293. * @returns {AtomicFunctionNode}
  24294. */
  24295. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  24296. /**
  24297. * Stores in an atomic variable the minimum between its current value and a parameter.
  24298. *
  24299. * @function
  24300. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24301. * @param {Node} valueNode - The value that mutates the atomic variable.
  24302. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24303. * @returns {AtomicFunctionNode}
  24304. */
  24305. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  24306. /**
  24307. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  24308. *
  24309. * @function
  24310. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24311. * @param {Node} valueNode - The value that mutates the atomic variable.
  24312. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24313. * @returns {AtomicFunctionNode}
  24314. */
  24315. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  24316. /**
  24317. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  24318. *
  24319. * @function
  24320. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24321. * @param {Node} valueNode - The value that mutates the atomic variable.
  24322. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24323. * @returns {AtomicFunctionNode}
  24324. */
  24325. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  24326. /**
  24327. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  24328. *
  24329. * @function
  24330. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24331. * @param {Node} valueNode - The value that mutates the atomic variable.
  24332. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24333. * @returns {AtomicFunctionNode}
  24334. */
  24335. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  24336. /** @module Lights **/
  24337. let uniformsLib;
  24338. function getLightData( light ) {
  24339. uniformsLib = uniformsLib || new WeakMap();
  24340. let uniforms = uniformsLib.get( light );
  24341. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  24342. return uniforms;
  24343. }
  24344. /**
  24345. * TSL function for getting a shadow matrix uniform node for the given light.
  24346. *
  24347. * @function
  24348. * @param {Light} light -The light source.
  24349. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  24350. */
  24351. function lightShadowMatrix( light ) {
  24352. const data = getLightData( light );
  24353. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24354. if ( light.castShadow !== true ) {
  24355. light.shadow.updateMatrices( light );
  24356. }
  24357. return light.shadow.matrix;
  24358. } ) );
  24359. }
  24360. /**
  24361. * TSL function for getting projected uv coordinates for the given light.
  24362. * Relevant when using maps with spot lights.
  24363. *
  24364. * @function
  24365. * @param {Light} light -The light source.
  24366. * @returns {Node<vec3>} The projected uvs.
  24367. */
  24368. function lightProjectionUV( light ) {
  24369. const data = getLightData( light );
  24370. if ( data.projectionUV === undefined ) {
  24371. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  24372. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  24373. }
  24374. return data.projectionUV;
  24375. }
  24376. /**
  24377. * TSL function for getting the position in world space for the given light.
  24378. *
  24379. * @function
  24380. * @param {Light} light -The light source.
  24381. * @returns {UniformNode<vec3>} The light's position in world space.
  24382. */
  24383. function lightPosition( light ) {
  24384. const data = getLightData( light );
  24385. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  24386. }
  24387. /**
  24388. * TSL function for getting the light target position in world space for the given light.
  24389. *
  24390. * @function
  24391. * @param {Light} light -The light source.
  24392. * @returns {UniformNode<vec3>} The light target position in world space.
  24393. */
  24394. function lightTargetPosition( light ) {
  24395. const data = getLightData( light );
  24396. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  24397. }
  24398. /**
  24399. * TSL function for getting the position in view space for the given light.
  24400. *
  24401. * @function
  24402. * @param {Light} light -The light source.
  24403. * @returns {UniformNode<vec3>} The light's position in view space.
  24404. */
  24405. function lightViewPosition( light ) {
  24406. const data = getLightData( light );
  24407. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  24408. self.value = self.value || new Vector3();
  24409. self.value.setFromMatrixPosition( light.matrixWorld );
  24410. self.value.applyMatrix4( camera.matrixWorldInverse );
  24411. } ) );
  24412. }
  24413. /**
  24414. * TSL function for getting the light target direction for the given light.
  24415. *
  24416. * @function
  24417. * @param {Light} light -The light source.
  24418. * @returns {Node<vec3>} The light's target direction.
  24419. */
  24420. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  24421. /** @module LightsNode **/
  24422. const sortLights = ( lights ) => {
  24423. return lights.sort( ( a, b ) => a.id - b.id );
  24424. };
  24425. const getLightNodeById = ( id, lightNodes ) => {
  24426. for ( const lightNode of lightNodes ) {
  24427. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  24428. return lightNode;
  24429. }
  24430. }
  24431. return null;
  24432. };
  24433. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  24434. /**
  24435. * This node represents the scene's lighting and manages the lighting model's life cycle
  24436. * for the current build 3D object. It is responsible for computing the total outgoing
  24437. * light in a given lighting context.
  24438. *
  24439. * @augments Node
  24440. */
  24441. class LightsNode extends Node {
  24442. static get type() {
  24443. return 'LightsNode';
  24444. }
  24445. /**
  24446. * Constructs a new lights node.
  24447. */
  24448. constructor() {
  24449. super( 'vec3' );
  24450. /**
  24451. * A node representing the total diffuse light.
  24452. *
  24453. * @type {Node<vec3>}
  24454. */
  24455. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  24456. /**
  24457. * A node representing the total specular light.
  24458. *
  24459. * @type {Node<vec3>}
  24460. */
  24461. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  24462. /**
  24463. * A node representing the outgoing light.
  24464. *
  24465. * @type {Node<vec3>}
  24466. */
  24467. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  24468. /**
  24469. * An array representing the lights in the scene.
  24470. *
  24471. * @private
  24472. * @type {Array<Light>}
  24473. */
  24474. this._lights = [];
  24475. /**
  24476. * For each light in the scene, this node will create a
  24477. * corresponding light node.
  24478. *
  24479. * @private
  24480. * @type {Array<LightingNode>?}
  24481. * @default null
  24482. */
  24483. this._lightNodes = null;
  24484. /**
  24485. * A hash for identifying the current light nodes setup.
  24486. *
  24487. * @private
  24488. * @type {String?}
  24489. * @default null
  24490. */
  24491. this._lightNodesHash = null;
  24492. /**
  24493. * `LightsNode` sets this property to `true` by default.
  24494. *
  24495. * @type {Boolean}
  24496. * @default true
  24497. */
  24498. this.global = true;
  24499. }
  24500. /**
  24501. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  24502. * light IDs into the cache key.
  24503. *
  24504. * @return {Number} The custom cache key.
  24505. */
  24506. customCacheKey() {
  24507. const lightIDs = [];
  24508. const lights = this._lights;
  24509. for ( let i = 0; i < lights.length; i ++ ) {
  24510. lightIDs.push( lights[ i ].id );
  24511. }
  24512. return hashArray( lightIDs );
  24513. }
  24514. /**
  24515. * Computes a hash value for identifying the current light nodes setup.
  24516. *
  24517. * @param {NodeBuilder} builder - A reference to the current node builder.
  24518. * @return {String} The computed hash.
  24519. */
  24520. getHash( builder ) {
  24521. if ( this._lightNodesHash === null ) {
  24522. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24523. const hash = [];
  24524. for ( const lightNode of this._lightNodes ) {
  24525. hash.push( lightNode.getSelf().getHash() );
  24526. }
  24527. this._lightNodesHash = 'lights-' + hash.join( ',' );
  24528. }
  24529. return this._lightNodesHash;
  24530. }
  24531. analyze( builder ) {
  24532. const properties = builder.getDataFromNode( this );
  24533. for ( const node of properties.nodes ) {
  24534. node.build( builder );
  24535. }
  24536. }
  24537. /**
  24538. * Creates lighting nodes for each scene light. This makes it possible to further
  24539. * process lights in the node system.
  24540. *
  24541. * @param {NodeBuilder} builder - A reference to the current node builder.
  24542. */
  24543. setupLightsNode( builder ) {
  24544. const lightNodes = [];
  24545. const previousLightNodes = this._lightNodes;
  24546. const lights = sortLights( this._lights );
  24547. const nodeLibrary = builder.renderer.library;
  24548. for ( const light of lights ) {
  24549. if ( light.isNode ) {
  24550. lightNodes.push( nodeObject( light ) );
  24551. } else {
  24552. let lightNode = null;
  24553. if ( previousLightNodes !== null ) {
  24554. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  24555. }
  24556. if ( lightNode === null ) {
  24557. // find the corresponding node type for a given light
  24558. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  24559. if ( lightNodeClass === null ) {
  24560. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  24561. continue;
  24562. }
  24563. let lightNode = null;
  24564. if ( ! _lightsNodeRef.has( light ) ) {
  24565. lightNode = nodeObject( new lightNodeClass( light ) );
  24566. _lightsNodeRef.set( light, lightNode );
  24567. } else {
  24568. lightNode = _lightsNodeRef.get( light );
  24569. }
  24570. lightNodes.push( lightNode );
  24571. }
  24572. }
  24573. }
  24574. this._lightNodes = lightNodes;
  24575. }
  24576. /**
  24577. * Setups the internal lights by building all respective
  24578. * light nodes.
  24579. *
  24580. * @param {NodeBuilder} builder - A reference to the current node builder.
  24581. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  24582. */
  24583. setupLights( builder, lightNodes ) {
  24584. for ( const lightNode of lightNodes ) {
  24585. lightNode.build( builder );
  24586. }
  24587. }
  24588. /**
  24589. * The implementation makes sure that for each light in the scene
  24590. * there is a corresponding light node. By building the light nodes
  24591. * and evaluating the lighting model the outgoing light is computed.
  24592. *
  24593. * @param {NodeBuilder} builder - A reference to the current node builder.
  24594. * @return {Node<vec3>} A node representing the outgoing light.
  24595. */
  24596. setup( builder ) {
  24597. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24598. const context = builder.context;
  24599. const lightingModel = context.lightingModel;
  24600. let outgoingLightNode = this.outgoingLightNode;
  24601. if ( lightingModel ) {
  24602. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  24603. context.outgoingLight = outgoingLightNode;
  24604. const stack = builder.addStack();
  24605. //
  24606. const properties = builder.getDataFromNode( this );
  24607. properties.nodes = stack.nodes;
  24608. //
  24609. lightingModel.start( context, stack, builder );
  24610. // lights
  24611. this.setupLights( builder, _lightNodes );
  24612. //
  24613. lightingModel.indirect( context, stack, builder );
  24614. //
  24615. const { backdrop, backdropAlpha } = context;
  24616. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  24617. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  24618. if ( backdrop !== null ) {
  24619. if ( backdropAlpha !== null ) {
  24620. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  24621. } else {
  24622. totalDiffuse = vec3( backdrop );
  24623. }
  24624. context.material.transparent = true;
  24625. }
  24626. totalDiffuseNode.assign( totalDiffuse );
  24627. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  24628. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  24629. //
  24630. lightingModel.finish( context, stack, builder );
  24631. //
  24632. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  24633. }
  24634. return outgoingLightNode;
  24635. }
  24636. /**
  24637. * Configures this node with an array of lights.
  24638. *
  24639. * @param {Array<Light>} lights - An array of lights.
  24640. * @return {LightsNode} A reference to this node.
  24641. */
  24642. setLights( lights ) {
  24643. this._lights = lights;
  24644. this._lightNodes = null;
  24645. this._lightNodesHash = null;
  24646. return this;
  24647. }
  24648. /**
  24649. * Returns an array of the scene's lights.
  24650. *
  24651. * @return {Array<Light>} The scene's lights.
  24652. */
  24653. getLights() {
  24654. return this._lights;
  24655. }
  24656. /**
  24657. * Whether the scene has lights or not.
  24658. *
  24659. * @type {Boolean}
  24660. */
  24661. get hasLights() {
  24662. return this._lights.length > 0;
  24663. }
  24664. }
  24665. /**
  24666. * TSL function for creating an instance of `LightsNode` and configuring
  24667. * it with the given array of lights.
  24668. *
  24669. * @function
  24670. * @param {Array<Light>} lights - An array of lights.
  24671. * @return {LightsNode} The created lights node.
  24672. */
  24673. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  24674. /** @module ShadowBaseNode **/
  24675. /**
  24676. * Base class for all shadow nodes.
  24677. *
  24678. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  24679. * Lighting nodes might share the same shadow node type or use specific ones depending on
  24680. * their requirements.
  24681. *
  24682. * @augments Node
  24683. */
  24684. class ShadowBaseNode extends Node {
  24685. static get type() {
  24686. return 'ShadowBaseNode';
  24687. }
  24688. /**
  24689. * Constructs a new shadow base node.
  24690. *
  24691. * @param {Light} light - The shadow casting light.
  24692. */
  24693. constructor( light ) {
  24694. super();
  24695. /**
  24696. * The shadow casting light.
  24697. *
  24698. * @type {Light}
  24699. */
  24700. this.light = light;
  24701. /**
  24702. * Overwritten since shadows are updated by default per render.
  24703. *
  24704. * @type {String}
  24705. * @default 'render'
  24706. */
  24707. this.updateBeforeType = NodeUpdateType.RENDER;
  24708. /**
  24709. * This flag can be used for type testing.
  24710. *
  24711. * @type {Boolean}
  24712. * @readonly
  24713. * @default true
  24714. */
  24715. this.isShadowBaseNode = true;
  24716. }
  24717. /**
  24718. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  24719. *
  24720. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  24721. */
  24722. setupShadowPosition( { material } ) {
  24723. // Use assign inside an Fn()
  24724. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  24725. }
  24726. /**
  24727. * Can be called when the shadow isn't required anymore. That can happen when
  24728. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  24729. * to `false`.
  24730. */
  24731. dispose() {
  24732. this.updateBeforeType = NodeUpdateType.NONE;
  24733. }
  24734. }
  24735. /**
  24736. * TSL object that represents the vertex position in world space during the shadow pass.
  24737. *
  24738. * @type {Node<vec3>}
  24739. */
  24740. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  24741. /** @module RendererUtils **/
  24742. /**
  24743. * Saves the state of the given renderer and stores it into the given state object.
  24744. *
  24745. * If not state object is provided, the function creates one.
  24746. *
  24747. * @function
  24748. * @param {Renderer} renderer - The renderer.
  24749. * @param {Object} [state={}] - The state.
  24750. * @return {Object} The state.
  24751. */
  24752. function saveRendererState( renderer, state = {} ) {
  24753. state.toneMapping = renderer.toneMapping;
  24754. state.toneMappingExposure = renderer.toneMappingExposure;
  24755. state.outputColorSpace = renderer.outputColorSpace;
  24756. state.renderTarget = renderer.getRenderTarget();
  24757. state.activeCubeFace = renderer.getActiveCubeFace();
  24758. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  24759. state.renderObjectFunction = renderer.getRenderObjectFunction();
  24760. state.pixelRatio = renderer.getPixelRatio();
  24761. state.mrt = renderer.getMRT();
  24762. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  24763. state.clearAlpha = renderer.getClearAlpha();
  24764. state.autoClear = renderer.autoClear;
  24765. state.scissorTest = renderer.getScissorTest();
  24766. return state;
  24767. }
  24768. /**
  24769. * Saves the state of the given renderer and stores it into the given state object.
  24770. * Besides, the function also resets the state of the renderer to its default values.
  24771. *
  24772. * If not state object is provided, the function creates one.
  24773. *
  24774. * @function
  24775. * @param {Renderer} renderer - The renderer.
  24776. * @param {Object} [state={}] - The state.
  24777. * @return {Object} The state.
  24778. */
  24779. function resetRendererState( renderer, state ) {
  24780. state = saveRendererState( renderer, state );
  24781. renderer.setMRT( null );
  24782. renderer.setRenderObjectFunction( null );
  24783. renderer.setClearColor( 0x000000, 1 );
  24784. renderer.autoClear = true;
  24785. return state;
  24786. }
  24787. /**
  24788. * Restores the state of the given renderer from the given state object.
  24789. *
  24790. * @function
  24791. * @param {Renderer} renderer - The renderer.
  24792. * @param {Object} state - The state to restore.
  24793. */
  24794. function restoreRendererState( renderer, state ) {
  24795. renderer.toneMapping = state.toneMapping;
  24796. renderer.toneMappingExposure = state.toneMappingExposure;
  24797. renderer.outputColorSpace = state.outputColorSpace;
  24798. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  24799. renderer.setRenderObjectFunction( state.renderObjectFunction );
  24800. renderer.setPixelRatio( state.pixelRatio );
  24801. renderer.setMRT( state.mrt );
  24802. renderer.setClearColor( state.clearColor, state.clearAlpha );
  24803. renderer.autoClear = state.autoClear;
  24804. renderer.setScissorTest( state.scissorTest );
  24805. }
  24806. /**
  24807. * Saves the state of the given scene and stores it into the given state object.
  24808. *
  24809. * If not state object is provided, the function creates one.
  24810. *
  24811. * @function
  24812. * @param {Scene} scene - The scene.
  24813. * @param {Object} [state={}] - The state.
  24814. * @return {Object} The state.
  24815. */
  24816. function saveSceneState( scene, state = {} ) {
  24817. state.background = scene.background;
  24818. state.backgroundNode = scene.backgroundNode;
  24819. state.overrideMaterial = scene.overrideMaterial;
  24820. return state;
  24821. }
  24822. /**
  24823. * Saves the state of the given scene and stores it into the given state object.
  24824. * Besides, the function also resets the state of the scene to its default values.
  24825. *
  24826. * If not state object is provided, the function creates one.
  24827. *
  24828. * @function
  24829. * @param {Scene} scene - The scene.
  24830. * @param {Object} [state={}] - The state.
  24831. * @return {Object} The state.
  24832. */
  24833. function resetSceneState( scene, state ) {
  24834. state = saveSceneState( scene, state );
  24835. scene.background = null;
  24836. scene.backgroundNode = null;
  24837. scene.overrideMaterial = null;
  24838. return state;
  24839. }
  24840. /**
  24841. * Restores the state of the given scene from the given state object.
  24842. *
  24843. * @function
  24844. * @param {Scene} scene - The scene.
  24845. * @param {Object} state - The state to restore.
  24846. */
  24847. function restoreSceneState( scene, state ) {
  24848. scene.background = state.background;
  24849. scene.backgroundNode = state.backgroundNode;
  24850. scene.overrideMaterial = state.overrideMaterial;
  24851. }
  24852. /**
  24853. * Saves the state of the given renderer and scene and stores it into the given state object.
  24854. *
  24855. * If not state object is provided, the function creates one.
  24856. *
  24857. * @function
  24858. * @param {Renderer} renderer - The renderer.
  24859. * @param {Scene} scene - The scene.
  24860. * @param {Object} [state={}] - The state.
  24861. * @return {Object} The state.
  24862. */
  24863. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  24864. state = saveRendererState( renderer, state );
  24865. state = saveSceneState( scene, state );
  24866. return state;
  24867. }
  24868. /**
  24869. * Saves the state of the given renderer and scene and stores it into the given state object.
  24870. * Besides, the function also resets the state of the renderer and scene to its default values.
  24871. *
  24872. * If not state object is provided, the function creates one.
  24873. *
  24874. * @function
  24875. * @param {Renderer} renderer - The renderer.
  24876. * @param {Scene} scene - The scene.
  24877. * @param {Object} [state={}] - The state.
  24878. * @return {Object} The state.
  24879. */
  24880. function resetRendererAndSceneState( renderer, scene, state ) {
  24881. state = resetRendererState( renderer, state );
  24882. state = resetSceneState( scene, state );
  24883. return state;
  24884. }
  24885. /**
  24886. * Restores the state of the given renderer and scene from the given state object.
  24887. *
  24888. * @function
  24889. * @param {Renderer} renderer - The renderer.
  24890. * @param {Scene} scene - The scene.
  24891. * @param {Object} state - The state to restore.
  24892. */
  24893. function restoreRendererAndSceneState( renderer, scene, state ) {
  24894. restoreRendererState( renderer, state );
  24895. restoreSceneState( scene, state );
  24896. }
  24897. var RendererUtils = /*#__PURE__*/Object.freeze({
  24898. __proto__: null,
  24899. resetRendererAndSceneState: resetRendererAndSceneState,
  24900. resetRendererState: resetRendererState,
  24901. resetSceneState: resetSceneState,
  24902. restoreRendererAndSceneState: restoreRendererAndSceneState,
  24903. restoreRendererState: restoreRendererState,
  24904. restoreSceneState: restoreSceneState,
  24905. saveRendererAndSceneState: saveRendererAndSceneState,
  24906. saveRendererState: saveRendererState,
  24907. saveSceneState: saveSceneState
  24908. });
  24909. /** @module ShadowNode **/
  24910. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  24911. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  24912. let dist = positionWorld.sub( position ).length();
  24913. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  24914. dist = dist.saturate(); // clamp to [ 0, 1 ]
  24915. return dist;
  24916. } );
  24917. const linearShadowDistance = ( light ) => {
  24918. const camera = light.shadow.camera;
  24919. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  24920. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  24921. const referencePosition = objectPosition( light );
  24922. return linearDistance( referencePosition, nearDistance, farDistance );
  24923. };
  24924. const getShadowMaterial = ( light ) => {
  24925. let material = shadowMaterialLib.get( light );
  24926. if ( material === undefined ) {
  24927. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  24928. material = new NodeMaterial();
  24929. material.colorNode = vec4( 0, 0, 0, 1 );
  24930. material.depthNode = depthNode;
  24931. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  24932. material.name = 'ShadowMaterial';
  24933. material.fog = false;
  24934. shadowMaterialLib.set( light, material );
  24935. }
  24936. return material;
  24937. };
  24938. /**
  24939. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  24940. * with a binary `[0,1]` result.
  24941. *
  24942. * @method
  24943. * @param {Object} inputs - The input parameter object.
  24944. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24945. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24946. * @return {Node<float>} The filtering result.
  24947. */
  24948. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  24949. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  24950. } );
  24951. /**
  24952. * A shadow filtering function performing PCF filtering.
  24953. *
  24954. * @method
  24955. * @param {Object} inputs - The input parameter object.
  24956. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24957. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24958. * @param {LightShadow} inputs.shadow - The light shadow.
  24959. * @return {Node<float>} The filtering result.
  24960. */
  24961. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  24962. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  24963. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  24964. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  24965. const texelSize = vec2( 1 ).div( mapSize );
  24966. const dx0 = texelSize.x.negate().mul( radius );
  24967. const dy0 = texelSize.y.negate().mul( radius );
  24968. const dx1 = texelSize.x.mul( radius );
  24969. const dy1 = texelSize.y.mul( radius );
  24970. const dx2 = dx0.div( 2 );
  24971. const dy2 = dy0.div( 2 );
  24972. const dx3 = dx1.div( 2 );
  24973. const dy3 = dy1.div( 2 );
  24974. return add(
  24975. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  24976. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  24977. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  24978. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  24979. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  24980. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  24981. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  24982. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  24983. depthCompare( shadowCoord.xy, shadowCoord.z ),
  24984. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  24985. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  24986. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  24987. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  24988. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  24989. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  24990. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  24991. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  24992. ).mul( 1 / 17 );
  24993. } );
  24994. /**
  24995. * A shadow filtering function performing PCF soft filtering.
  24996. *
  24997. * @method
  24998. * @param {Object} inputs - The input parameter object.
  24999. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25000. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25001. * @param {LightShadow} inputs.shadow - The light shadow.
  25002. * @return {Node<float>} The filtering result.
  25003. */
  25004. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25005. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25006. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25007. const texelSize = vec2( 1 ).div( mapSize );
  25008. const dx = texelSize.x;
  25009. const dy = texelSize.y;
  25010. const uv = shadowCoord.xy;
  25011. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  25012. uv.subAssign( f.mul( texelSize ) );
  25013. return add(
  25014. depthCompare( uv, shadowCoord.z ),
  25015. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  25016. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  25017. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  25018. mix(
  25019. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  25020. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  25021. f.x
  25022. ),
  25023. mix(
  25024. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  25025. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  25026. f.x
  25027. ),
  25028. mix(
  25029. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  25030. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  25031. f.y
  25032. ),
  25033. mix(
  25034. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  25035. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  25036. f.y
  25037. ),
  25038. mix(
  25039. mix(
  25040. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  25041. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  25042. f.x
  25043. ),
  25044. mix(
  25045. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  25046. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  25047. f.x
  25048. ),
  25049. f.y
  25050. )
  25051. ).mul( 1 / 9 );
  25052. } );
  25053. /**
  25054. * A shadow filtering function performing VSM filtering.
  25055. *
  25056. * @method
  25057. * @param {Object} inputs - The input parameter object.
  25058. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25059. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25060. * @return {Node<float>} The filtering result.
  25061. */
  25062. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25063. const occlusion = float( 1 ).toVar();
  25064. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  25065. const hardShadow = step( shadowCoord.z, distribution.x );
  25066. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  25067. const distance = shadowCoord.z.sub( distribution.x );
  25068. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  25069. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  25070. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  25071. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  25072. } );
  25073. return occlusion;
  25074. } );
  25075. /**
  25076. * Represents the shader code for the first VSM render pass.
  25077. *
  25078. * @method
  25079. * @param {Object} inputs - The input parameter object.
  25080. * @param {Node<float>} inputs.samples - The number of samples
  25081. * @param {Node<float>} inputs.radius - The radius.
  25082. * @param {Node<float>} inputs.size - The size.
  25083. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  25084. * @return {Node<vec2>} The VSM output.
  25085. */
  25086. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25087. const mean = float( 0 ).toVar();
  25088. const squaredMean = float( 0 ).toVar();
  25089. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25090. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  25091. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25092. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25093. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  25094. mean.addAssign( depth );
  25095. squaredMean.addAssign( depth.mul( depth ) );
  25096. } );
  25097. mean.divAssign( samples );
  25098. squaredMean.divAssign( samples );
  25099. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25100. return vec2( mean, std_dev );
  25101. } );
  25102. /**
  25103. * Represents the shader code for the second VSM render pass.
  25104. *
  25105. * @method
  25106. * @param {Object} inputs - The input parameter object.
  25107. * @param {Node<float>} inputs.samples - The number of samples
  25108. * @param {Node<float>} inputs.radius - The radius.
  25109. * @param {Node<float>} inputs.size - The size.
  25110. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  25111. * @return {Node<vec2>} The VSM output.
  25112. */
  25113. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25114. const mean = float( 0 ).toVar();
  25115. const squaredMean = float( 0 ).toVar();
  25116. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25117. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  25118. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25119. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25120. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  25121. mean.addAssign( distribution.x );
  25122. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  25123. } );
  25124. mean.divAssign( samples );
  25125. squaredMean.divAssign( samples );
  25126. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25127. return vec2( mean, std_dev );
  25128. } );
  25129. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  25130. //
  25131. let _rendererState;
  25132. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  25133. /**
  25134. * Represents the default shadow implementation for lighting nodes.
  25135. *
  25136. * @augments module:ShadowBaseNode~ShadowBaseNode
  25137. */
  25138. class ShadowNode extends ShadowBaseNode {
  25139. static get type() {
  25140. return 'ShadowNode';
  25141. }
  25142. /**
  25143. * Constructs a new shadow node.
  25144. *
  25145. * @param {Light} light - The shadow casting light.
  25146. * @param {LightShadow?} [shadow=null] - An optional light shadow.
  25147. */
  25148. constructor( light, shadow = null ) {
  25149. super( light );
  25150. /**
  25151. * The light shadow which defines the properties light's
  25152. * shadow.
  25153. *
  25154. * @type {LightShadow?}
  25155. * @default null
  25156. */
  25157. this.shadow = shadow || light.shadow;
  25158. /**
  25159. * A reference to the shadow map which is a render target.
  25160. *
  25161. * @type {RenderTarget?}
  25162. * @default null
  25163. */
  25164. this.shadowMap = null;
  25165. /**
  25166. * Only relevant for VSM shadows. Render target for the
  25167. * first VSM render pass.
  25168. *
  25169. * @type {RenderTarget?}
  25170. * @default null
  25171. */
  25172. this.vsmShadowMapVertical = null;
  25173. /**
  25174. * Only relevant for VSM shadows. Render target for the
  25175. * second VSM render pass.
  25176. *
  25177. * @type {RenderTarget?}
  25178. * @default null
  25179. */
  25180. this.vsmShadowMapHorizontal = null;
  25181. /**
  25182. * Only relevant for VSM shadows. Node material which
  25183. * is used to render the first VSM pass.
  25184. *
  25185. * @type {NodeMaterial?}
  25186. * @default null
  25187. */
  25188. this.vsmMaterialVertical = null;
  25189. /**
  25190. * Only relevant for VSM shadows. Node material which
  25191. * is used to render the second VSM pass.
  25192. *
  25193. * @type {NodeMaterial?}
  25194. * @default null
  25195. */
  25196. this.vsmMaterialHorizontal = null;
  25197. /**
  25198. * A reference to the output node which defines the
  25199. * final result of this shadow node.
  25200. *
  25201. * @type {Node?}
  25202. * @private
  25203. * @default null
  25204. */
  25205. this._node = null;
  25206. /**
  25207. * This flag can be used for type testing.
  25208. *
  25209. * @type {Boolean}
  25210. * @readonly
  25211. * @default true
  25212. */
  25213. this.isShadowNode = true;
  25214. }
  25215. /**
  25216. * Setups the shadow filtering.
  25217. *
  25218. * @param {NodeBuilder} builder - A reference to the current node builder.
  25219. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25220. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25221. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25222. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25223. * @param {LightShadow} inputs.shadow - The light shadow.
  25224. * @return {Node<float>} The result node of the shadow filtering.
  25225. */
  25226. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  25227. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25228. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25229. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25230. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25231. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25232. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  25233. return frustumTest.select( shadowNode, float( 1 ) );
  25234. }
  25235. /**
  25236. * Setups the shadow coordinates.
  25237. *
  25238. * @param {NodeBuilder} builder - A reference to the current node builder.
  25239. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25240. * @return {Node<vec3>} The shadow coordinates.
  25241. */
  25242. setupShadowCoord( builder, shadowPosition ) {
  25243. const { shadow } = this;
  25244. const { renderer } = builder;
  25245. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25246. let shadowCoord = shadowPosition;
  25247. let coordZ;
  25248. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  25249. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25250. coordZ = shadowCoord.z;
  25251. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25252. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  25253. }
  25254. } else {
  25255. const w = shadowCoord.w;
  25256. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  25257. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  25258. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  25259. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  25260. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  25261. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  25262. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  25263. }
  25264. shadowCoord = vec3(
  25265. shadowCoord.x,
  25266. shadowCoord.y.oneMinus(), // follow webgpu standards
  25267. coordZ.add( bias )
  25268. );
  25269. return shadowCoord;
  25270. }
  25271. /**
  25272. * Returns the shadow filtering function for the given shadow type.
  25273. *
  25274. * @param {Number} type - The shadow type.
  25275. * @return {Function} The filtering function.
  25276. */
  25277. getShadowFilterFn( type ) {
  25278. return _shadowFilterLib[ type ];
  25279. }
  25280. /**
  25281. * Setups the shadow output node.
  25282. *
  25283. * @param {NodeBuilder} builder - A reference to the current node builder.
  25284. * @return {Node<vec3>} The shadow output node.
  25285. */
  25286. setupShadow( builder ) {
  25287. const { renderer } = builder;
  25288. const { light, shadow } = this;
  25289. const shadowMapType = renderer.shadowMap.type;
  25290. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  25291. depthTexture.compareFunction = LessCompare;
  25292. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25293. shadowMap.depthTexture = depthTexture;
  25294. shadow.camera.updateProjectionMatrix();
  25295. // VSM
  25296. if ( shadowMapType === VSMShadowMap ) {
  25297. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  25298. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25299. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25300. const shadowPassVertical = texture( depthTexture );
  25301. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  25302. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  25303. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25304. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25305. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  25306. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  25307. material.name = 'VSMVertical';
  25308. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  25309. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  25310. material.name = 'VSMHorizontal';
  25311. }
  25312. //
  25313. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  25314. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  25315. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  25316. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  25317. //
  25318. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  25319. if ( filterFn === null ) {
  25320. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  25321. }
  25322. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  25323. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  25324. const shadowColor = texture( shadowMap.texture, shadowCoord );
  25325. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  25326. this.shadowMap = shadowMap;
  25327. this.shadow.map = shadowMap;
  25328. return shadowOutput;
  25329. }
  25330. /**
  25331. * The implementation performs the setup of the output node. An output is only
  25332. * produces if shadow mapping is globally enabled in the renderer.
  25333. *
  25334. * @param {NodeBuilder} builder - A reference to the current node builder.
  25335. * @return {ShaderCallNodeInternal} The output node.
  25336. */
  25337. setup( builder ) {
  25338. if ( builder.renderer.shadowMap.enabled === false ) return;
  25339. return Fn( () => {
  25340. let node = this._node;
  25341. this.setupShadowPosition( builder );
  25342. if ( node === null ) {
  25343. this._node = node = this.setupShadow( builder );
  25344. }
  25345. if ( builder.material.shadowNode ) { // @deprecated, r171
  25346. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  25347. }
  25348. if ( builder.material.receivedShadowNode ) {
  25349. node = builder.material.receivedShadowNode( node );
  25350. }
  25351. return node;
  25352. } )();
  25353. }
  25354. /**
  25355. * Renders the shadow. The logic of this function could be included
  25356. * into {@link ShadowNode#updateShadow} however more specialized shadow
  25357. * nodes might require a custom shadow map rendering. By having a
  25358. * dedicated method, it's easier to overwrite the default behavior.
  25359. *
  25360. * @param {NodeFrame} frame - A reference to the current node frame.
  25361. */
  25362. renderShadow( frame ) {
  25363. const { shadow, shadowMap, light } = this;
  25364. const { renderer, scene } = frame;
  25365. shadow.updateMatrices( light );
  25366. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25367. renderer.render( scene, shadow.camera );
  25368. }
  25369. /**
  25370. * Updates the shadow.
  25371. *
  25372. * @param {NodeFrame} frame - A reference to the current node frame.
  25373. */
  25374. updateShadow( frame ) {
  25375. const { shadowMap, light, shadow } = this;
  25376. const { renderer, scene, camera } = frame;
  25377. const shadowType = renderer.shadowMap.type;
  25378. const depthVersion = shadowMap.depthTexture.version;
  25379. this._depthVersionCached = depthVersion;
  25380. shadow.camera.layers.mask = camera.layers.mask;
  25381. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25382. const currentMRT = renderer.getMRT();
  25383. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  25384. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  25385. scene.overrideMaterial = getShadowMaterial( light );
  25386. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  25387. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  25388. if ( useVelocity ) {
  25389. getDataFromObject( object ).useVelocity = true;
  25390. }
  25391. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25392. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  25393. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25394. }
  25395. } );
  25396. renderer.setRenderTarget( shadowMap );
  25397. this.renderShadow( frame );
  25398. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25399. // vsm blur pass
  25400. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  25401. this.vsmPass( renderer );
  25402. }
  25403. restoreRendererAndSceneState( renderer, scene, _rendererState );
  25404. }
  25405. /**
  25406. * For VSM additional render passes are required.
  25407. *
  25408. * @param {Renderer} renderer - A reference to the current renderer.
  25409. */
  25410. vsmPass( renderer ) {
  25411. const { shadow } = this;
  25412. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25413. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25414. renderer.setRenderTarget( this.vsmShadowMapVertical );
  25415. _quadMesh.material = this.vsmMaterialVertical;
  25416. _quadMesh.render( renderer );
  25417. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  25418. _quadMesh.material = this.vsmMaterialHorizontal;
  25419. _quadMesh.render( renderer );
  25420. }
  25421. /**
  25422. * Frees the internal resources of this shadow node.
  25423. */
  25424. dispose() {
  25425. this.shadowMap.dispose();
  25426. this.shadowMap = null;
  25427. if ( this.vsmShadowMapVertical !== null ) {
  25428. this.vsmShadowMapVertical.dispose();
  25429. this.vsmShadowMapVertical = null;
  25430. this.vsmMaterialVertical.dispose();
  25431. this.vsmMaterialVertical = null;
  25432. }
  25433. if ( this.vsmShadowMapHorizontal !== null ) {
  25434. this.vsmShadowMapHorizontal.dispose();
  25435. this.vsmShadowMapHorizontal = null;
  25436. this.vsmMaterialHorizontal.dispose();
  25437. this.vsmMaterialHorizontal = null;
  25438. }
  25439. super.dispose();
  25440. }
  25441. /**
  25442. * The implementation performs the update of the shadow map if necessary.
  25443. *
  25444. * @param {NodeFrame} frame - A reference to the current node frame.
  25445. */
  25446. updateBefore( frame ) {
  25447. const { shadow } = this;
  25448. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  25449. if ( needsUpdate ) {
  25450. this.updateShadow( frame );
  25451. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  25452. shadow.needsUpdate = false;
  25453. }
  25454. }
  25455. }
  25456. }
  25457. /**
  25458. * TSL function for creating an instance of `ShadowNode`.
  25459. *
  25460. * @function
  25461. * @param {Light} light - The shadow casting light.
  25462. * @param {LightShadow} shadow - The light shadow.
  25463. * @return {ShadowNode} The created shadow node.
  25464. */
  25465. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  25466. /**
  25467. * Base class for analytic light nodes.
  25468. *
  25469. * @augments LightingNode
  25470. */
  25471. class AnalyticLightNode extends LightingNode {
  25472. static get type() {
  25473. return 'AnalyticLightNode';
  25474. }
  25475. /**
  25476. * Constructs a new analytic light node.
  25477. *
  25478. * @param {Light?} [light=null] - The light source.
  25479. */
  25480. constructor( light = null ) {
  25481. super();
  25482. /**
  25483. * The light source.
  25484. *
  25485. * @type {Light?}
  25486. * @default null
  25487. */
  25488. this.light = light;
  25489. /**
  25490. * The light's color value.
  25491. *
  25492. * @type {Color}
  25493. */
  25494. this.color = new Color();
  25495. /**
  25496. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  25497. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  25498. *
  25499. * @type {Node}
  25500. */
  25501. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  25502. /**
  25503. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  25504. * The final color node is represented by a different node when using shadows.
  25505. *
  25506. * @type {Node?}
  25507. * @default null
  25508. */
  25509. this.baseColorNode = null;
  25510. /**
  25511. * Represents the light's shadow.
  25512. *
  25513. * @type {ShadowNode?}
  25514. * @default null
  25515. */
  25516. this.shadowNode = null;
  25517. /**
  25518. * Represents the light's shadow color.
  25519. *
  25520. * @type {Node?}
  25521. * @default null
  25522. */
  25523. this.shadowColorNode = null;
  25524. /**
  25525. * This flag can be used for type testing.
  25526. *
  25527. * @type {Boolean}
  25528. * @readonly
  25529. * @default true
  25530. */
  25531. this.isAnalyticLightNode = true;
  25532. /**
  25533. * Overwritten since analytic light nodes are updated
  25534. * once per frame.
  25535. *
  25536. * @type {String}
  25537. * @default 'frame'
  25538. */
  25539. this.updateType = NodeUpdateType.FRAME;
  25540. }
  25541. /**
  25542. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  25543. * `light.id` and `light.castShadow` into the cache key.
  25544. *
  25545. * @return {Number} The custom cache key.
  25546. */
  25547. customCacheKey() {
  25548. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  25549. }
  25550. getHash() {
  25551. return this.light.uuid;
  25552. }
  25553. /**
  25554. * Setups the shadow node for this light. The method exists so concrete light classes
  25555. * can setup different types of shadow nodes.
  25556. *
  25557. * @return {ShadowNode} The created shadow node.
  25558. */
  25559. setupShadowNode() {
  25560. return shadow( this.light );
  25561. }
  25562. /**
  25563. * Setups the shadow for this light. This method is only executed if the light
  25564. * cast shadows and the current build object receives shadows. It incorporates
  25565. * shadows into the lighting computation.
  25566. *
  25567. * @param {NodeBuilder} builder - The current node builder.
  25568. */
  25569. setupShadow( builder ) {
  25570. const { renderer } = builder;
  25571. if ( renderer.shadowMap.enabled === false ) return;
  25572. let shadowColorNode = this.shadowColorNode;
  25573. if ( shadowColorNode === null ) {
  25574. const customShadowNode = this.light.shadow.shadowNode;
  25575. let shadowNode;
  25576. if ( customShadowNode !== undefined ) {
  25577. shadowNode = nodeObject( customShadowNode );
  25578. } else {
  25579. shadowNode = this.setupShadowNode( builder );
  25580. }
  25581. this.shadowNode = shadowNode;
  25582. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  25583. this.baseColorNode = this.colorNode;
  25584. }
  25585. //
  25586. this.colorNode = shadowColorNode;
  25587. }
  25588. /**
  25589. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  25590. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  25591. * invocate the respective interface methods.
  25592. *
  25593. * @param {NodeBuilder} builder - The current node builder.
  25594. */
  25595. setup( builder ) {
  25596. this.colorNode = this.baseColorNode || this.colorNode;
  25597. if ( this.light.castShadow ) {
  25598. if ( builder.object.receiveShadow ) {
  25599. this.setupShadow( builder );
  25600. }
  25601. } else if ( this.shadowNode !== null ) {
  25602. this.shadowNode.dispose();
  25603. this.shadowNode = null;
  25604. this.shadowColorNode = null;
  25605. }
  25606. }
  25607. /**
  25608. * The update method is used to update light uniforms per frame.
  25609. * Potentially overwritten in concrete light nodes to update light
  25610. * specific uniforms.
  25611. *
  25612. * @param {NodeFrame} frame - A reference to the current node frame.
  25613. */
  25614. update( /*frame*/ ) {
  25615. const { light } = this;
  25616. this.color.copy( light.color ).multiplyScalar( light.intensity );
  25617. }
  25618. }
  25619. /** @module LightUtils **/
  25620. /**
  25621. * Represents a `discard` shader operation in TSL.
  25622. *
  25623. * @method
  25624. * @param {Object} inputs - The input parameter object.
  25625. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  25626. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  25627. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  25628. * @return {Node<float>} The distance falloff.
  25629. */
  25630. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  25631. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  25632. // based upon Frostbite 3 Moving to Physically-based Rendering
  25633. // page 32, equation 26: E[window1]
  25634. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25635. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  25636. return cutoffDistance.greaterThan( 0 ).select(
  25637. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  25638. distanceFalloff
  25639. );
  25640. } ); // validated
  25641. /** @module PointShadowNode **/
  25642. const _clearColor$2 = /*@__PURE__*/ new Color();
  25643. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  25644. // vector suitable for 2D texture mapping. This code uses the following layout for the
  25645. // 2D texture:
  25646. //
  25647. // xzXZ
  25648. // y Y
  25649. //
  25650. // Y - Positive y direction
  25651. // y - Negative y direction
  25652. // X - Positive x direction
  25653. // x - Negative x direction
  25654. // Z - Positive z direction
  25655. // z - Negative z direction
  25656. //
  25657. // Source and test bed:
  25658. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  25659. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  25660. const v = pos.toVar();
  25661. // Number of texels to avoid at the edge of each square
  25662. const absV = abs( v );
  25663. // Intersect unit cube
  25664. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  25665. absV.mulAssign( scaleToCube );
  25666. // Apply scale to avoid seams
  25667. // two texels less per square (one texel will do for NEAREST)
  25668. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  25669. // Unwrap
  25670. // space: -1 ... 1 range for each square
  25671. //
  25672. // #X## dim := ( 4 , 2 )
  25673. // # # center := ( 1 , 1 )
  25674. const planar = vec2( v.xy ).toVar();
  25675. const almostATexel = texelSizeY.mul( 1.5 );
  25676. const almostOne = almostATexel.oneMinus();
  25677. If( absV.z.greaterThanEqual( almostOne ), () => {
  25678. If( v.z.greaterThan( 0.0 ), () => {
  25679. planar.x.assign( sub( 4.0, v.x ) );
  25680. } );
  25681. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  25682. const signX = sign( v.x );
  25683. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  25684. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  25685. const signY = sign( v.y );
  25686. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  25687. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  25688. } );
  25689. // Transform to UV space
  25690. // scale := 0.5 / dim
  25691. // translate := ( center + 0.5 ) / dim
  25692. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  25693. } ).setLayout( {
  25694. name: 'cubeToUV',
  25695. type: 'vec2',
  25696. inputs: [
  25697. { name: 'pos', type: 'vec3' },
  25698. { name: 'texelSizeY', type: 'float' }
  25699. ]
  25700. } );
  25701. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  25702. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  25703. } );
  25704. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  25705. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25706. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  25707. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  25708. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  25709. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  25710. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  25711. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  25712. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  25713. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  25714. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  25715. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  25716. .mul( 1.0 / 9.0 );
  25717. } );
  25718. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  25719. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  25720. // the vector from the light to the world-space position of the fragment.
  25721. const lightToPosition = shadowCoord.xyz.toVar();
  25722. const lightToPositionLength = lightToPosition.length();
  25723. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  25724. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  25725. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25726. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  25727. const result = float( 1.0 ).toVar();
  25728. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  25729. // dp = normalized distance from light to fragment position
  25730. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  25731. dp.addAssign( bias );
  25732. // bd3D = base direction 3D
  25733. const bd3D = lightToPosition.normalize();
  25734. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  25735. // percentage-closer filtering
  25736. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  25737. } );
  25738. return result;
  25739. } );
  25740. const _viewport = /*@__PURE__*/ new Vector4();
  25741. const _viewportSize = /*@__PURE__*/ new Vector2();
  25742. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  25743. /**
  25744. * Represents the shadow implementation for point light nodes.
  25745. *
  25746. * @augments module:ShadowNode~ShadowNode
  25747. */
  25748. class PointShadowNode extends ShadowNode {
  25749. static get type() {
  25750. return 'PointShadowNode';
  25751. }
  25752. /**
  25753. * Constructs a new point shadow node.
  25754. *
  25755. * @param {PointLight} light - The shadow casting point light.
  25756. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25757. */
  25758. constructor( light, shadow = null ) {
  25759. super( light, shadow );
  25760. }
  25761. /**
  25762. * Overwrites the default implementation to return point light shadow specific
  25763. * filtering functions.
  25764. *
  25765. * @param {Number} type - The shadow type.
  25766. * @return {Function} The filtering function.
  25767. */
  25768. getShadowFilterFn( type ) {
  25769. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  25770. }
  25771. /**
  25772. * Overwrites the default implementation so the unaltered shadow position is used.
  25773. *
  25774. * @param {NodeBuilder} builder - A reference to the current node builder.
  25775. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25776. * @return {Node<vec3>} The shadow coordinates.
  25777. */
  25778. setupShadowCoord( builder, shadowPosition ) {
  25779. return shadowPosition;
  25780. }
  25781. /**
  25782. * Overwrites the default implementation to only use point light specific
  25783. * shadow filter functions.
  25784. *
  25785. * @param {NodeBuilder} builder - A reference to the current node builder.
  25786. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25787. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25788. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  25789. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25790. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25791. * @param {LightShadow} inputs.shadow - The light shadow.
  25792. * @return {Node<float>} The result node of the shadow filtering.
  25793. */
  25794. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  25795. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  25796. }
  25797. /**
  25798. * Overwrites the default implementation with point light specific
  25799. * rendering code.
  25800. *
  25801. * @param {NodeFrame} frame - A reference to the current node frame.
  25802. */
  25803. renderShadow( frame ) {
  25804. const { shadow, shadowMap, light } = this;
  25805. const { renderer, scene } = frame;
  25806. const shadowFrameExtents = shadow.getFrameExtents();
  25807. _shadowMapSize.copy( shadow.mapSize );
  25808. _shadowMapSize.multiply( shadowFrameExtents );
  25809. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  25810. _viewportSize.copy( shadow.mapSize );
  25811. //
  25812. const previousAutoClear = renderer.autoClear;
  25813. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  25814. const previousClearAlpha = renderer.getClearAlpha();
  25815. renderer.autoClear = false;
  25816. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  25817. renderer.clear();
  25818. const viewportCount = shadow.getViewportCount();
  25819. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  25820. const viewport = shadow.getViewport( vp );
  25821. const x = _viewportSize.x * viewport.x;
  25822. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  25823. _viewport.set(
  25824. x,
  25825. y,
  25826. _viewportSize.x * viewport.z,
  25827. _viewportSize.y * viewport.w
  25828. );
  25829. shadowMap.viewport.copy( _viewport );
  25830. shadow.updateMatrices( light, vp );
  25831. renderer.render( scene, shadow.camera );
  25832. }
  25833. //
  25834. renderer.autoClear = previousAutoClear;
  25835. renderer.setClearColor( previousClearColor, previousClearAlpha );
  25836. }
  25837. }
  25838. /**
  25839. * TSL function for creating an instance of `PointShadowNode`.
  25840. *
  25841. * @function
  25842. * @param {PointLight} light - The shadow casting point light.
  25843. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25844. * @return {PointShadowNode} The created point shadow node.
  25845. */
  25846. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  25847. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  25848. const lightingModel = builder.context.lightingModel;
  25849. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  25850. const lightDirection = lVector.normalize();
  25851. const lightDistance = lVector.length();
  25852. const lightAttenuation = getDistanceAttenuation( {
  25853. lightDistance,
  25854. cutoffDistance,
  25855. decayExponent
  25856. } );
  25857. const lightColor = color.mul( lightAttenuation );
  25858. const reflectedLight = builder.context.reflectedLight;
  25859. lightingModel.direct( {
  25860. lightDirection,
  25861. lightColor,
  25862. reflectedLight
  25863. }, builder.stack, builder );
  25864. } );
  25865. /**
  25866. * Module for representing point lights as nodes.
  25867. *
  25868. * @augments AnalyticLightNode
  25869. */
  25870. class PointLightNode extends AnalyticLightNode {
  25871. static get type() {
  25872. return 'PointLightNode';
  25873. }
  25874. /**
  25875. * Constructs a new point light node.
  25876. *
  25877. * @param {PointLight?} [light=null] - The point light source.
  25878. */
  25879. constructor( light = null ) {
  25880. super( light );
  25881. /**
  25882. * Uniform node representing the cutoff distance.
  25883. *
  25884. * @type {UniformNode<float>}
  25885. */
  25886. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  25887. /**
  25888. * Uniform node representing the decay exponent.
  25889. *
  25890. * @type {UniformNode<float>}
  25891. */
  25892. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  25893. }
  25894. /**
  25895. * Overwritten to updated point light specific uniforms.
  25896. *
  25897. * @param {NodeFrame} frame - A reference to the current node frame.
  25898. */
  25899. update( frame ) {
  25900. const { light } = this;
  25901. super.update( frame );
  25902. this.cutoffDistanceNode.value = light.distance;
  25903. this.decayExponentNode.value = light.decay;
  25904. }
  25905. /**
  25906. * Overwritten to setup point light specific shadow.
  25907. *
  25908. * @return {PointShadowNode}
  25909. */
  25910. setupShadowNode() {
  25911. return pointShadow( this.light );
  25912. }
  25913. setup( builder ) {
  25914. super.setup( builder );
  25915. directPointLight( {
  25916. color: this.colorNode,
  25917. lightViewPosition: lightViewPosition( this.light ),
  25918. cutoffDistance: this.cutoffDistanceNode,
  25919. decayExponent: this.decayExponentNode
  25920. } ).append();
  25921. }
  25922. }
  25923. /** @module Procedural **/
  25924. /**
  25925. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  25926. *
  25927. * @method
  25928. * @param {Node<vec2>} coord - The uv coordinates.
  25929. * @return {Node<float>} The result data.
  25930. */
  25931. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  25932. const uv = coord.mul( 2.0 );
  25933. const cx = uv.x.floor();
  25934. const cy = uv.y.floor();
  25935. const result = cx.add( cy ).mod( 2.0 );
  25936. return result.sign();
  25937. } );
  25938. /** @module Shapes **/
  25939. /**
  25940. * Generates a circle based on the uv coordinates.
  25941. *
  25942. * @method
  25943. * @param {Node<vec2>} coord - The uv to generate the circle.
  25944. * @return {Node<float>} The circle shape.
  25945. */
  25946. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  25947. const alpha = float( 1 ).toVar();
  25948. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  25949. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  25950. const dlen = float( len2.fwidth() ).toVar();
  25951. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  25952. } else {
  25953. len2.greaterThan( 1.0 ).discard();
  25954. }
  25955. return alpha;
  25956. } );
  25957. // Three.js Transpiler
  25958. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  25959. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  25960. const f = float( f_immutable ).toVar();
  25961. const t = float( t_immutable ).toVar();
  25962. const b = bool( b_immutable ).toVar();
  25963. return select( b, t, f );
  25964. } ).setLayout( {
  25965. name: 'mx_select',
  25966. type: 'float',
  25967. inputs: [
  25968. { name: 'b', type: 'bool' },
  25969. { name: 't', type: 'float' },
  25970. { name: 'f', type: 'float' }
  25971. ]
  25972. } );
  25973. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  25974. const b = bool( b_immutable ).toVar();
  25975. const val = float( val_immutable ).toVar();
  25976. return select( b, val.negate(), val );
  25977. } ).setLayout( {
  25978. name: 'mx_negate_if',
  25979. type: 'float',
  25980. inputs: [
  25981. { name: 'val', type: 'float' },
  25982. { name: 'b', type: 'bool' }
  25983. ]
  25984. } );
  25985. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  25986. const x = float( x_immutable ).toVar();
  25987. return int( floor( x ) );
  25988. } ).setLayout( {
  25989. name: 'mx_floor',
  25990. type: 'int',
  25991. inputs: [
  25992. { name: 'x', type: 'float' }
  25993. ]
  25994. } );
  25995. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  25996. const x = float( x_immutable ).toVar();
  25997. i.assign( mx_floor( x ) );
  25998. return x.sub( float( i ) );
  25999. } );
  26000. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26001. const t = float( t_immutable ).toVar();
  26002. const s = float( s_immutable ).toVar();
  26003. const v3 = float( v3_immutable ).toVar();
  26004. const v2 = float( v2_immutable ).toVar();
  26005. const v1 = float( v1_immutable ).toVar();
  26006. const v0 = float( v0_immutable ).toVar();
  26007. const s1 = float( sub( 1.0, s ) ).toVar();
  26008. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26009. } ).setLayout( {
  26010. name: 'mx_bilerp_0',
  26011. type: 'float',
  26012. inputs: [
  26013. { name: 'v0', type: 'float' },
  26014. { name: 'v1', type: 'float' },
  26015. { name: 'v2', type: 'float' },
  26016. { name: 'v3', type: 'float' },
  26017. { name: 's', type: 'float' },
  26018. { name: 't', type: 'float' }
  26019. ]
  26020. } );
  26021. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26022. const t = float( t_immutable ).toVar();
  26023. const s = float( s_immutable ).toVar();
  26024. const v3 = vec3( v3_immutable ).toVar();
  26025. const v2 = vec3( v2_immutable ).toVar();
  26026. const v1 = vec3( v1_immutable ).toVar();
  26027. const v0 = vec3( v0_immutable ).toVar();
  26028. const s1 = float( sub( 1.0, s ) ).toVar();
  26029. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26030. } ).setLayout( {
  26031. name: 'mx_bilerp_1',
  26032. type: 'vec3',
  26033. inputs: [
  26034. { name: 'v0', type: 'vec3' },
  26035. { name: 'v1', type: 'vec3' },
  26036. { name: 'v2', type: 'vec3' },
  26037. { name: 'v3', type: 'vec3' },
  26038. { name: 's', type: 'float' },
  26039. { name: 't', type: 'float' }
  26040. ]
  26041. } );
  26042. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  26043. 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 ] ) => {
  26044. const r = float( r_immutable ).toVar();
  26045. const t = float( t_immutable ).toVar();
  26046. const s = float( s_immutable ).toVar();
  26047. const v7 = float( v7_immutable ).toVar();
  26048. const v6 = float( v6_immutable ).toVar();
  26049. const v5 = float( v5_immutable ).toVar();
  26050. const v4 = float( v4_immutable ).toVar();
  26051. const v3 = float( v3_immutable ).toVar();
  26052. const v2 = float( v2_immutable ).toVar();
  26053. const v1 = float( v1_immutable ).toVar();
  26054. const v0 = float( v0_immutable ).toVar();
  26055. const s1 = float( sub( 1.0, s ) ).toVar();
  26056. const t1 = float( sub( 1.0, t ) ).toVar();
  26057. const r1 = float( sub( 1.0, r ) ).toVar();
  26058. 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 ) ) ) ) ) );
  26059. } ).setLayout( {
  26060. name: 'mx_trilerp_0',
  26061. type: 'float',
  26062. inputs: [
  26063. { name: 'v0', type: 'float' },
  26064. { name: 'v1', type: 'float' },
  26065. { name: 'v2', type: 'float' },
  26066. { name: 'v3', type: 'float' },
  26067. { name: 'v4', type: 'float' },
  26068. { name: 'v5', type: 'float' },
  26069. { name: 'v6', type: 'float' },
  26070. { name: 'v7', type: 'float' },
  26071. { name: 's', type: 'float' },
  26072. { name: 't', type: 'float' },
  26073. { name: 'r', type: 'float' }
  26074. ]
  26075. } );
  26076. 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 ] ) => {
  26077. const r = float( r_immutable ).toVar();
  26078. const t = float( t_immutable ).toVar();
  26079. const s = float( s_immutable ).toVar();
  26080. const v7 = vec3( v7_immutable ).toVar();
  26081. const v6 = vec3( v6_immutable ).toVar();
  26082. const v5 = vec3( v5_immutable ).toVar();
  26083. const v4 = vec3( v4_immutable ).toVar();
  26084. const v3 = vec3( v3_immutable ).toVar();
  26085. const v2 = vec3( v2_immutable ).toVar();
  26086. const v1 = vec3( v1_immutable ).toVar();
  26087. const v0 = vec3( v0_immutable ).toVar();
  26088. const s1 = float( sub( 1.0, s ) ).toVar();
  26089. const t1 = float( sub( 1.0, t ) ).toVar();
  26090. const r1 = float( sub( 1.0, r ) ).toVar();
  26091. 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 ) ) ) ) ) );
  26092. } ).setLayout( {
  26093. name: 'mx_trilerp_1',
  26094. type: 'vec3',
  26095. inputs: [
  26096. { name: 'v0', type: 'vec3' },
  26097. { name: 'v1', type: 'vec3' },
  26098. { name: 'v2', type: 'vec3' },
  26099. { name: 'v3', type: 'vec3' },
  26100. { name: 'v4', type: 'vec3' },
  26101. { name: 'v5', type: 'vec3' },
  26102. { name: 'v6', type: 'vec3' },
  26103. { name: 'v7', type: 'vec3' },
  26104. { name: 's', type: 'float' },
  26105. { name: 't', type: 'float' },
  26106. { name: 'r', type: 'float' }
  26107. ]
  26108. } );
  26109. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  26110. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26111. const y = float( y_immutable ).toVar();
  26112. const x = float( x_immutable ).toVar();
  26113. const hash = uint( hash_immutable ).toVar();
  26114. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  26115. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  26116. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  26117. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26118. } ).setLayout( {
  26119. name: 'mx_gradient_float_0',
  26120. type: 'float',
  26121. inputs: [
  26122. { name: 'hash', type: 'uint' },
  26123. { name: 'x', type: 'float' },
  26124. { name: 'y', type: 'float' }
  26125. ]
  26126. } );
  26127. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26128. const z = float( z_immutable ).toVar();
  26129. const y = float( y_immutable ).toVar();
  26130. const x = float( x_immutable ).toVar();
  26131. const hash = uint( hash_immutable ).toVar();
  26132. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  26133. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  26134. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  26135. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26136. } ).setLayout( {
  26137. name: 'mx_gradient_float_1',
  26138. type: 'float',
  26139. inputs: [
  26140. { name: 'hash', type: 'uint' },
  26141. { name: 'x', type: 'float' },
  26142. { name: 'y', type: 'float' },
  26143. { name: 'z', type: 'float' }
  26144. ]
  26145. } );
  26146. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  26147. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26148. const y = float( y_immutable ).toVar();
  26149. const x = float( x_immutable ).toVar();
  26150. const hash = uvec3( hash_immutable ).toVar();
  26151. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  26152. } ).setLayout( {
  26153. name: 'mx_gradient_vec3_0',
  26154. type: 'vec3',
  26155. inputs: [
  26156. { name: 'hash', type: 'uvec3' },
  26157. { name: 'x', type: 'float' },
  26158. { name: 'y', type: 'float' }
  26159. ]
  26160. } );
  26161. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26162. const z = float( z_immutable ).toVar();
  26163. const y = float( y_immutable ).toVar();
  26164. const x = float( x_immutable ).toVar();
  26165. const hash = uvec3( hash_immutable ).toVar();
  26166. 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 ) );
  26167. } ).setLayout( {
  26168. name: 'mx_gradient_vec3_1',
  26169. type: 'vec3',
  26170. inputs: [
  26171. { name: 'hash', type: 'uvec3' },
  26172. { name: 'x', type: 'float' },
  26173. { name: 'y', type: 'float' },
  26174. { name: 'z', type: 'float' }
  26175. ]
  26176. } );
  26177. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  26178. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26179. const v = float( v_immutable ).toVar();
  26180. return mul( 0.6616, v );
  26181. } ).setLayout( {
  26182. name: 'mx_gradient_scale2d_0',
  26183. type: 'float',
  26184. inputs: [
  26185. { name: 'v', type: 'float' }
  26186. ]
  26187. } );
  26188. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26189. const v = float( v_immutable ).toVar();
  26190. return mul( 0.9820, v );
  26191. } ).setLayout( {
  26192. name: 'mx_gradient_scale3d_0',
  26193. type: 'float',
  26194. inputs: [
  26195. { name: 'v', type: 'float' }
  26196. ]
  26197. } );
  26198. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26199. const v = vec3( v_immutable ).toVar();
  26200. return mul( 0.6616, v );
  26201. } ).setLayout( {
  26202. name: 'mx_gradient_scale2d_1',
  26203. type: 'vec3',
  26204. inputs: [
  26205. { name: 'v', type: 'vec3' }
  26206. ]
  26207. } );
  26208. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  26209. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26210. const v = vec3( v_immutable ).toVar();
  26211. return mul( 0.9820, v );
  26212. } ).setLayout( {
  26213. name: 'mx_gradient_scale3d_1',
  26214. type: 'vec3',
  26215. inputs: [
  26216. { name: 'v', type: 'vec3' }
  26217. ]
  26218. } );
  26219. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  26220. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  26221. const k = int( k_immutable ).toVar();
  26222. const x = uint( x_immutable ).toVar();
  26223. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  26224. } ).setLayout( {
  26225. name: 'mx_rotl32',
  26226. type: 'uint',
  26227. inputs: [
  26228. { name: 'x', type: 'uint' },
  26229. { name: 'k', type: 'int' }
  26230. ]
  26231. } );
  26232. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  26233. a.subAssign( c );
  26234. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  26235. c.addAssign( b );
  26236. b.subAssign( a );
  26237. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  26238. a.addAssign( c );
  26239. c.subAssign( b );
  26240. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  26241. b.addAssign( a );
  26242. a.subAssign( c );
  26243. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  26244. c.addAssign( b );
  26245. b.subAssign( a );
  26246. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  26247. a.addAssign( c );
  26248. c.subAssign( b );
  26249. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  26250. b.addAssign( a );
  26251. } );
  26252. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  26253. const c = uint( c_immutable ).toVar();
  26254. const b = uint( b_immutable ).toVar();
  26255. const a = uint( a_immutable ).toVar();
  26256. c.bitXorAssign( b );
  26257. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  26258. a.bitXorAssign( c );
  26259. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  26260. b.bitXorAssign( a );
  26261. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  26262. c.bitXorAssign( b );
  26263. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  26264. a.bitXorAssign( c );
  26265. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  26266. b.bitXorAssign( a );
  26267. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  26268. c.bitXorAssign( b );
  26269. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  26270. return c;
  26271. } ).setLayout( {
  26272. name: 'mx_bjfinal',
  26273. type: 'uint',
  26274. inputs: [
  26275. { name: 'a', type: 'uint' },
  26276. { name: 'b', type: 'uint' },
  26277. { name: 'c', type: 'uint' }
  26278. ]
  26279. } );
  26280. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  26281. const bits = uint( bits_immutable ).toVar();
  26282. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  26283. } ).setLayout( {
  26284. name: 'mx_bits_to_01',
  26285. type: 'float',
  26286. inputs: [
  26287. { name: 'bits', type: 'uint' }
  26288. ]
  26289. } );
  26290. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  26291. const t = float( t_immutable ).toVar();
  26292. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  26293. } ).setLayout( {
  26294. name: 'mx_fade',
  26295. type: 'float',
  26296. inputs: [
  26297. { name: 't', type: 'float' }
  26298. ]
  26299. } );
  26300. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26301. const x = int( x_immutable ).toVar();
  26302. const len = uint( uint( 1 ) ).toVar();
  26303. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  26304. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  26305. } ).setLayout( {
  26306. name: 'mx_hash_int_0',
  26307. type: 'uint',
  26308. inputs: [
  26309. { name: 'x', type: 'int' }
  26310. ]
  26311. } );
  26312. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26313. const y = int( y_immutable ).toVar();
  26314. const x = int( x_immutable ).toVar();
  26315. const len = uint( uint( 2 ) ).toVar();
  26316. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26317. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26318. a.addAssign( uint( x ) );
  26319. b.addAssign( uint( y ) );
  26320. return mx_bjfinal( a, b, c );
  26321. } ).setLayout( {
  26322. name: 'mx_hash_int_1',
  26323. type: 'uint',
  26324. inputs: [
  26325. { name: 'x', type: 'int' },
  26326. { name: 'y', type: 'int' }
  26327. ]
  26328. } );
  26329. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26330. const z = int( z_immutable ).toVar();
  26331. const y = int( y_immutable ).toVar();
  26332. const x = int( x_immutable ).toVar();
  26333. const len = uint( uint( 3 ) ).toVar();
  26334. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26335. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26336. a.addAssign( uint( x ) );
  26337. b.addAssign( uint( y ) );
  26338. c.addAssign( uint( z ) );
  26339. return mx_bjfinal( a, b, c );
  26340. } ).setLayout( {
  26341. name: 'mx_hash_int_2',
  26342. type: 'uint',
  26343. inputs: [
  26344. { name: 'x', type: 'int' },
  26345. { name: 'y', type: 'int' },
  26346. { name: 'z', type: 'int' }
  26347. ]
  26348. } );
  26349. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  26350. const xx = int( xx_immutable ).toVar();
  26351. const z = int( z_immutable ).toVar();
  26352. const y = int( y_immutable ).toVar();
  26353. const x = int( x_immutable ).toVar();
  26354. const len = uint( uint( 4 ) ).toVar();
  26355. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26356. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26357. a.addAssign( uint( x ) );
  26358. b.addAssign( uint( y ) );
  26359. c.addAssign( uint( z ) );
  26360. mx_bjmix( a, b, c );
  26361. a.addAssign( uint( xx ) );
  26362. return mx_bjfinal( a, b, c );
  26363. } ).setLayout( {
  26364. name: 'mx_hash_int_3',
  26365. type: 'uint',
  26366. inputs: [
  26367. { name: 'x', type: 'int' },
  26368. { name: 'y', type: 'int' },
  26369. { name: 'z', type: 'int' },
  26370. { name: 'xx', type: 'int' }
  26371. ]
  26372. } );
  26373. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  26374. const yy = int( yy_immutable ).toVar();
  26375. const xx = int( xx_immutable ).toVar();
  26376. const z = int( z_immutable ).toVar();
  26377. const y = int( y_immutable ).toVar();
  26378. const x = int( x_immutable ).toVar();
  26379. const len = uint( uint( 5 ) ).toVar();
  26380. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26381. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26382. a.addAssign( uint( x ) );
  26383. b.addAssign( uint( y ) );
  26384. c.addAssign( uint( z ) );
  26385. mx_bjmix( a, b, c );
  26386. a.addAssign( uint( xx ) );
  26387. b.addAssign( uint( yy ) );
  26388. return mx_bjfinal( a, b, c );
  26389. } ).setLayout( {
  26390. name: 'mx_hash_int_4',
  26391. type: 'uint',
  26392. inputs: [
  26393. { name: 'x', type: 'int' },
  26394. { name: 'y', type: 'int' },
  26395. { name: 'z', type: 'int' },
  26396. { name: 'xx', type: 'int' },
  26397. { name: 'yy', type: 'int' }
  26398. ]
  26399. } );
  26400. 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 ] );
  26401. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26402. const y = int( y_immutable ).toVar();
  26403. const x = int( x_immutable ).toVar();
  26404. const h = uint( mx_hash_int( x, y ) ).toVar();
  26405. const result = uvec3().toVar();
  26406. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26407. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26408. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26409. return result;
  26410. } ).setLayout( {
  26411. name: 'mx_hash_vec3_0',
  26412. type: 'uvec3',
  26413. inputs: [
  26414. { name: 'x', type: 'int' },
  26415. { name: 'y', type: 'int' }
  26416. ]
  26417. } );
  26418. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26419. const z = int( z_immutable ).toVar();
  26420. const y = int( y_immutable ).toVar();
  26421. const x = int( x_immutable ).toVar();
  26422. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  26423. const result = uvec3().toVar();
  26424. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26425. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26426. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26427. return result;
  26428. } ).setLayout( {
  26429. name: 'mx_hash_vec3_1',
  26430. type: 'uvec3',
  26431. inputs: [
  26432. { name: 'x', type: 'int' },
  26433. { name: 'y', type: 'int' },
  26434. { name: 'z', type: 'int' }
  26435. ]
  26436. } );
  26437. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  26438. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26439. const p = vec2( p_immutable ).toVar();
  26440. const X = int().toVar(), Y = int().toVar();
  26441. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26442. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26443. const u = float( mx_fade( fx ) ).toVar();
  26444. const v = float( mx_fade( fy ) ).toVar();
  26445. 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();
  26446. return mx_gradient_scale2d( result );
  26447. } ).setLayout( {
  26448. name: 'mx_perlin_noise_float_0',
  26449. type: 'float',
  26450. inputs: [
  26451. { name: 'p', type: 'vec2' }
  26452. ]
  26453. } );
  26454. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26455. const p = vec3( p_immutable ).toVar();
  26456. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26457. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26458. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26459. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26460. const u = float( mx_fade( fx ) ).toVar();
  26461. const v = float( mx_fade( fy ) ).toVar();
  26462. const w = float( mx_fade( fz ) ).toVar();
  26463. 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();
  26464. return mx_gradient_scale3d( result );
  26465. } ).setLayout( {
  26466. name: 'mx_perlin_noise_float_1',
  26467. type: 'float',
  26468. inputs: [
  26469. { name: 'p', type: 'vec3' }
  26470. ]
  26471. } );
  26472. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  26473. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26474. const p = vec2( p_immutable ).toVar();
  26475. const X = int().toVar(), Y = int().toVar();
  26476. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26477. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26478. const u = float( mx_fade( fx ) ).toVar();
  26479. const v = float( mx_fade( fy ) ).toVar();
  26480. 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();
  26481. return mx_gradient_scale2d( result );
  26482. } ).setLayout( {
  26483. name: 'mx_perlin_noise_vec3_0',
  26484. type: 'vec3',
  26485. inputs: [
  26486. { name: 'p', type: 'vec2' }
  26487. ]
  26488. } );
  26489. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26490. const p = vec3( p_immutable ).toVar();
  26491. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26492. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26493. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26494. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26495. const u = float( mx_fade( fx ) ).toVar();
  26496. const v = float( mx_fade( fy ) ).toVar();
  26497. const w = float( mx_fade( fz ) ).toVar();
  26498. 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();
  26499. return mx_gradient_scale3d( result );
  26500. } ).setLayout( {
  26501. name: 'mx_perlin_noise_vec3_1',
  26502. type: 'vec3',
  26503. inputs: [
  26504. { name: 'p', type: 'vec3' }
  26505. ]
  26506. } );
  26507. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  26508. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26509. const p = float( p_immutable ).toVar();
  26510. const ix = int( mx_floor( p ) ).toVar();
  26511. return mx_bits_to_01( mx_hash_int( ix ) );
  26512. } ).setLayout( {
  26513. name: 'mx_cell_noise_float_0',
  26514. type: 'float',
  26515. inputs: [
  26516. { name: 'p', type: 'float' }
  26517. ]
  26518. } );
  26519. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26520. const p = vec2( p_immutable ).toVar();
  26521. const ix = int( mx_floor( p.x ) ).toVar();
  26522. const iy = int( mx_floor( p.y ) ).toVar();
  26523. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  26524. } ).setLayout( {
  26525. name: 'mx_cell_noise_float_1',
  26526. type: 'float',
  26527. inputs: [
  26528. { name: 'p', type: 'vec2' }
  26529. ]
  26530. } );
  26531. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26532. const p = vec3( p_immutable ).toVar();
  26533. const ix = int( mx_floor( p.x ) ).toVar();
  26534. const iy = int( mx_floor( p.y ) ).toVar();
  26535. const iz = int( mx_floor( p.z ) ).toVar();
  26536. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  26537. } ).setLayout( {
  26538. name: 'mx_cell_noise_float_2',
  26539. type: 'float',
  26540. inputs: [
  26541. { name: 'p', type: 'vec3' }
  26542. ]
  26543. } );
  26544. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26545. const p = vec4( p_immutable ).toVar();
  26546. const ix = int( mx_floor( p.x ) ).toVar();
  26547. const iy = int( mx_floor( p.y ) ).toVar();
  26548. const iz = int( mx_floor( p.z ) ).toVar();
  26549. const iw = int( mx_floor( p.w ) ).toVar();
  26550. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  26551. } ).setLayout( {
  26552. name: 'mx_cell_noise_float_3',
  26553. type: 'float',
  26554. inputs: [
  26555. { name: 'p', type: 'vec4' }
  26556. ]
  26557. } );
  26558. 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 ] );
  26559. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26560. const p = float( p_immutable ).toVar();
  26561. const ix = int( mx_floor( p ) ).toVar();
  26562. 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 ) ) ) );
  26563. } ).setLayout( {
  26564. name: 'mx_cell_noise_vec3_0',
  26565. type: 'vec3',
  26566. inputs: [
  26567. { name: 'p', type: 'float' }
  26568. ]
  26569. } );
  26570. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26571. const p = vec2( p_immutable ).toVar();
  26572. const ix = int( mx_floor( p.x ) ).toVar();
  26573. const iy = int( mx_floor( p.y ) ).toVar();
  26574. 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 ) ) ) );
  26575. } ).setLayout( {
  26576. name: 'mx_cell_noise_vec3_1',
  26577. type: 'vec3',
  26578. inputs: [
  26579. { name: 'p', type: 'vec2' }
  26580. ]
  26581. } );
  26582. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26583. const p = vec3( p_immutable ).toVar();
  26584. const ix = int( mx_floor( p.x ) ).toVar();
  26585. const iy = int( mx_floor( p.y ) ).toVar();
  26586. const iz = int( mx_floor( p.z ) ).toVar();
  26587. 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 ) ) ) );
  26588. } ).setLayout( {
  26589. name: 'mx_cell_noise_vec3_2',
  26590. type: 'vec3',
  26591. inputs: [
  26592. { name: 'p', type: 'vec3' }
  26593. ]
  26594. } );
  26595. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26596. const p = vec4( p_immutable ).toVar();
  26597. const ix = int( mx_floor( p.x ) ).toVar();
  26598. const iy = int( mx_floor( p.y ) ).toVar();
  26599. const iz = int( mx_floor( p.z ) ).toVar();
  26600. const iw = int( mx_floor( p.w ) ).toVar();
  26601. 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 ) ) ) );
  26602. } ).setLayout( {
  26603. name: 'mx_cell_noise_vec3_3',
  26604. type: 'vec3',
  26605. inputs: [
  26606. { name: 'p', type: 'vec4' }
  26607. ]
  26608. } );
  26609. 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 ] );
  26610. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26611. const diminish = float( diminish_immutable ).toVar();
  26612. const lacunarity = float( lacunarity_immutable ).toVar();
  26613. const octaves = int( octaves_immutable ).toVar();
  26614. const p = vec3( p_immutable ).toVar();
  26615. const result = float( 0.0 ).toVar();
  26616. const amplitude = float( 1.0 ).toVar();
  26617. Loop( octaves, () => {
  26618. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  26619. amplitude.mulAssign( diminish );
  26620. p.mulAssign( lacunarity );
  26621. } );
  26622. return result;
  26623. } ).setLayout( {
  26624. name: 'mx_fractal_noise_float',
  26625. type: 'float',
  26626. inputs: [
  26627. { name: 'p', type: 'vec3' },
  26628. { name: 'octaves', type: 'int' },
  26629. { name: 'lacunarity', type: 'float' },
  26630. { name: 'diminish', type: 'float' }
  26631. ]
  26632. } );
  26633. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26634. const diminish = float( diminish_immutable ).toVar();
  26635. const lacunarity = float( lacunarity_immutable ).toVar();
  26636. const octaves = int( octaves_immutable ).toVar();
  26637. const p = vec3( p_immutable ).toVar();
  26638. const result = vec3( 0.0 ).toVar();
  26639. const amplitude = float( 1.0 ).toVar();
  26640. Loop( octaves, () => {
  26641. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  26642. amplitude.mulAssign( diminish );
  26643. p.mulAssign( lacunarity );
  26644. } );
  26645. return result;
  26646. } ).setLayout( {
  26647. name: 'mx_fractal_noise_vec3',
  26648. type: 'vec3',
  26649. inputs: [
  26650. { name: 'p', type: 'vec3' },
  26651. { name: 'octaves', type: 'int' },
  26652. { name: 'lacunarity', type: 'float' },
  26653. { name: 'diminish', type: 'float' }
  26654. ]
  26655. } );
  26656. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26657. const diminish = float( diminish_immutable ).toVar();
  26658. const lacunarity = float( lacunarity_immutable ).toVar();
  26659. const octaves = int( octaves_immutable ).toVar();
  26660. const p = vec3( p_immutable ).toVar();
  26661. 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 ) );
  26662. } ).setLayout( {
  26663. name: 'mx_fractal_noise_vec2',
  26664. type: 'vec2',
  26665. inputs: [
  26666. { name: 'p', type: 'vec3' },
  26667. { name: 'octaves', type: 'int' },
  26668. { name: 'lacunarity', type: 'float' },
  26669. { name: 'diminish', type: 'float' }
  26670. ]
  26671. } );
  26672. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26673. const diminish = float( diminish_immutable ).toVar();
  26674. const lacunarity = float( lacunarity_immutable ).toVar();
  26675. const octaves = int( octaves_immutable ).toVar();
  26676. const p = vec3( p_immutable ).toVar();
  26677. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  26678. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  26679. return vec4( c, f );
  26680. } ).setLayout( {
  26681. name: 'mx_fractal_noise_vec4',
  26682. type: 'vec4',
  26683. inputs: [
  26684. { name: 'p', type: 'vec3' },
  26685. { name: 'octaves', type: 'int' },
  26686. { name: 'lacunarity', type: 'float' },
  26687. { name: 'diminish', type: 'float' }
  26688. ]
  26689. } );
  26690. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  26691. const metric = int( metric_immutable ).toVar();
  26692. const jitter = float( jitter_immutable ).toVar();
  26693. const yoff = int( yoff_immutable ).toVar();
  26694. const xoff = int( xoff_immutable ).toVar();
  26695. const y = int( y_immutable ).toVar();
  26696. const x = int( x_immutable ).toVar();
  26697. const p = vec2( p_immutable ).toVar();
  26698. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  26699. const off = vec2( tmp.x, tmp.y ).toVar();
  26700. off.subAssign( 0.5 );
  26701. off.mulAssign( jitter );
  26702. off.addAssign( 0.5 );
  26703. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  26704. const diff = vec2( cellpos.sub( p ) ).toVar();
  26705. If( metric.equal( int( 2 ) ), () => {
  26706. return abs( diff.x ).add( abs( diff.y ) );
  26707. } );
  26708. If( metric.equal( int( 3 ) ), () => {
  26709. return max$1( abs( diff.x ), abs( diff.y ) );
  26710. } );
  26711. return dot( diff, diff );
  26712. } ).setLayout( {
  26713. name: 'mx_worley_distance_0',
  26714. type: 'float',
  26715. inputs: [
  26716. { name: 'p', type: 'vec2' },
  26717. { name: 'x', type: 'int' },
  26718. { name: 'y', type: 'int' },
  26719. { name: 'xoff', type: 'int' },
  26720. { name: 'yoff', type: 'int' },
  26721. { name: 'jitter', type: 'float' },
  26722. { name: 'metric', type: 'int' }
  26723. ]
  26724. } );
  26725. 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 ] ) => {
  26726. const metric = int( metric_immutable ).toVar();
  26727. const jitter = float( jitter_immutable ).toVar();
  26728. const zoff = int( zoff_immutable ).toVar();
  26729. const yoff = int( yoff_immutable ).toVar();
  26730. const xoff = int( xoff_immutable ).toVar();
  26731. const z = int( z_immutable ).toVar();
  26732. const y = int( y_immutable ).toVar();
  26733. const x = int( x_immutable ).toVar();
  26734. const p = vec3( p_immutable ).toVar();
  26735. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  26736. off.subAssign( 0.5 );
  26737. off.mulAssign( jitter );
  26738. off.addAssign( 0.5 );
  26739. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  26740. const diff = vec3( cellpos.sub( p ) ).toVar();
  26741. If( metric.equal( int( 2 ) ), () => {
  26742. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  26743. } );
  26744. If( metric.equal( int( 3 ) ), () => {
  26745. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  26746. } );
  26747. return dot( diff, diff );
  26748. } ).setLayout( {
  26749. name: 'mx_worley_distance_1',
  26750. type: 'float',
  26751. inputs: [
  26752. { name: 'p', type: 'vec3' },
  26753. { name: 'x', type: 'int' },
  26754. { name: 'y', type: 'int' },
  26755. { name: 'z', type: 'int' },
  26756. { name: 'xoff', type: 'int' },
  26757. { name: 'yoff', type: 'int' },
  26758. { name: 'zoff', type: 'int' },
  26759. { name: 'jitter', type: 'float' },
  26760. { name: 'metric', type: 'int' }
  26761. ]
  26762. } );
  26763. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  26764. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26765. const metric = int( metric_immutable ).toVar();
  26766. const jitter = float( jitter_immutable ).toVar();
  26767. const p = vec2( p_immutable ).toVar();
  26768. const X = int().toVar(), Y = int().toVar();
  26769. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26770. const sqdist = float( 1e6 ).toVar();
  26771. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26772. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26773. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26774. sqdist.assign( min$1( sqdist, dist ) );
  26775. } );
  26776. } );
  26777. If( metric.equal( int( 0 ) ), () => {
  26778. sqdist.assign( sqrt( sqdist ) );
  26779. } );
  26780. return sqdist;
  26781. } ).setLayout( {
  26782. name: 'mx_worley_noise_float_0',
  26783. type: 'float',
  26784. inputs: [
  26785. { name: 'p', type: 'vec2' },
  26786. { name: 'jitter', type: 'float' },
  26787. { name: 'metric', type: 'int' }
  26788. ]
  26789. } );
  26790. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26791. const metric = int( metric_immutable ).toVar();
  26792. const jitter = float( jitter_immutable ).toVar();
  26793. const p = vec2( p_immutable ).toVar();
  26794. const X = int().toVar(), Y = int().toVar();
  26795. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26796. const sqdist = vec2( 1e6, 1e6 ).toVar();
  26797. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26798. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26799. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26800. If( dist.lessThan( sqdist.x ), () => {
  26801. sqdist.y.assign( sqdist.x );
  26802. sqdist.x.assign( dist );
  26803. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26804. sqdist.y.assign( dist );
  26805. } );
  26806. } );
  26807. } );
  26808. If( metric.equal( int( 0 ) ), () => {
  26809. sqdist.assign( sqrt( sqdist ) );
  26810. } );
  26811. return sqdist;
  26812. } ).setLayout( {
  26813. name: 'mx_worley_noise_vec2_0',
  26814. type: 'vec2',
  26815. inputs: [
  26816. { name: 'p', type: 'vec2' },
  26817. { name: 'jitter', type: 'float' },
  26818. { name: 'metric', type: 'int' }
  26819. ]
  26820. } );
  26821. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26822. const metric = int( metric_immutable ).toVar();
  26823. const jitter = float( jitter_immutable ).toVar();
  26824. const p = vec2( p_immutable ).toVar();
  26825. const X = int().toVar(), Y = int().toVar();
  26826. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26827. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  26828. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26829. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26830. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26831. If( dist.lessThan( sqdist.x ), () => {
  26832. sqdist.z.assign( sqdist.y );
  26833. sqdist.y.assign( sqdist.x );
  26834. sqdist.x.assign( dist );
  26835. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26836. sqdist.z.assign( sqdist.y );
  26837. sqdist.y.assign( dist );
  26838. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  26839. sqdist.z.assign( dist );
  26840. } );
  26841. } );
  26842. } );
  26843. If( metric.equal( int( 0 ) ), () => {
  26844. sqdist.assign( sqrt( sqdist ) );
  26845. } );
  26846. return sqdist;
  26847. } ).setLayout( {
  26848. name: 'mx_worley_noise_vec3_0',
  26849. type: 'vec3',
  26850. inputs: [
  26851. { name: 'p', type: 'vec2' },
  26852. { name: 'jitter', type: 'float' },
  26853. { name: 'metric', type: 'int' }
  26854. ]
  26855. } );
  26856. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26857. const metric = int( metric_immutable ).toVar();
  26858. const jitter = float( jitter_immutable ).toVar();
  26859. const p = vec3( p_immutable ).toVar();
  26860. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26861. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26862. const sqdist = float( 1e6 ).toVar();
  26863. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26864. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26865. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26866. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26867. sqdist.assign( min$1( sqdist, dist ) );
  26868. } );
  26869. } );
  26870. } );
  26871. If( metric.equal( int( 0 ) ), () => {
  26872. sqdist.assign( sqrt( sqdist ) );
  26873. } );
  26874. return sqdist;
  26875. } ).setLayout( {
  26876. name: 'mx_worley_noise_float_1',
  26877. type: 'float',
  26878. inputs: [
  26879. { name: 'p', type: 'vec3' },
  26880. { name: 'jitter', type: 'float' },
  26881. { name: 'metric', type: 'int' }
  26882. ]
  26883. } );
  26884. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  26885. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26886. const metric = int( metric_immutable ).toVar();
  26887. const jitter = float( jitter_immutable ).toVar();
  26888. const p = vec3( p_immutable ).toVar();
  26889. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26890. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26891. const sqdist = vec2( 1e6, 1e6 ).toVar();
  26892. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26893. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26894. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26895. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26896. If( dist.lessThan( sqdist.x ), () => {
  26897. sqdist.y.assign( sqdist.x );
  26898. sqdist.x.assign( dist );
  26899. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26900. sqdist.y.assign( dist );
  26901. } );
  26902. } );
  26903. } );
  26904. } );
  26905. If( metric.equal( int( 0 ) ), () => {
  26906. sqdist.assign( sqrt( sqdist ) );
  26907. } );
  26908. return sqdist;
  26909. } ).setLayout( {
  26910. name: 'mx_worley_noise_vec2_1',
  26911. type: 'vec2',
  26912. inputs: [
  26913. { name: 'p', type: 'vec3' },
  26914. { name: 'jitter', type: 'float' },
  26915. { name: 'metric', type: 'int' }
  26916. ]
  26917. } );
  26918. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  26919. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26920. const metric = int( metric_immutable ).toVar();
  26921. const jitter = float( jitter_immutable ).toVar();
  26922. const p = vec3( p_immutable ).toVar();
  26923. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26924. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26925. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  26926. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26927. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26928. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26929. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26930. If( dist.lessThan( sqdist.x ), () => {
  26931. sqdist.z.assign( sqdist.y );
  26932. sqdist.y.assign( sqdist.x );
  26933. sqdist.x.assign( dist );
  26934. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26935. sqdist.z.assign( sqdist.y );
  26936. sqdist.y.assign( dist );
  26937. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  26938. sqdist.z.assign( dist );
  26939. } );
  26940. } );
  26941. } );
  26942. } );
  26943. If( metric.equal( int( 0 ) ), () => {
  26944. sqdist.assign( sqrt( sqdist ) );
  26945. } );
  26946. return sqdist;
  26947. } ).setLayout( {
  26948. name: 'mx_worley_noise_vec3_1',
  26949. type: 'vec3',
  26950. inputs: [
  26951. { name: 'p', type: 'vec3' },
  26952. { name: 'jitter', type: 'float' },
  26953. { name: 'metric', type: 'int' }
  26954. ]
  26955. } );
  26956. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  26957. // Three.js Transpiler
  26958. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  26959. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  26960. const s = hsv.y;
  26961. const v = hsv.z;
  26962. const result = vec3().toVar();
  26963. If( s.lessThan( 0.0001 ), () => {
  26964. result.assign( vec3( v, v, v ) );
  26965. } ).Else( () => {
  26966. let h = hsv.x;
  26967. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  26968. const hi = int( trunc( h ) );
  26969. const f = h.sub( float( hi ) );
  26970. const p = v.mul( s.oneMinus() );
  26971. const q = v.mul( s.mul( f ).oneMinus() );
  26972. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  26973. If( hi.equal( int( 0 ) ), () => {
  26974. result.assign( vec3( v, t, p ) );
  26975. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  26976. result.assign( vec3( q, v, p ) );
  26977. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  26978. result.assign( vec3( p, v, t ) );
  26979. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  26980. result.assign( vec3( p, q, v ) );
  26981. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  26982. result.assign( vec3( t, p, v ) );
  26983. } ).Else( () => {
  26984. result.assign( vec3( v, p, q ) );
  26985. } );
  26986. } );
  26987. return result;
  26988. } ).setLayout( {
  26989. name: 'mx_hsvtorgb',
  26990. type: 'vec3',
  26991. inputs: [
  26992. { name: 'hsv', type: 'vec3' }
  26993. ]
  26994. } );
  26995. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  26996. const c = vec3( c_immutable ).toVar();
  26997. const r = float( c.x ).toVar();
  26998. const g = float( c.y ).toVar();
  26999. const b = float( c.z ).toVar();
  27000. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  27001. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  27002. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  27003. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  27004. v.assign( maxcomp );
  27005. If( maxcomp.greaterThan( 0.0 ), () => {
  27006. s.assign( delta.div( maxcomp ) );
  27007. } ).Else( () => {
  27008. s.assign( 0.0 );
  27009. } );
  27010. If( s.lessThanEqual( 0.0 ), () => {
  27011. h.assign( 0.0 );
  27012. } ).Else( () => {
  27013. If( r.greaterThanEqual( maxcomp ), () => {
  27014. h.assign( g.sub( b ).div( delta ) );
  27015. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  27016. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  27017. } ).Else( () => {
  27018. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  27019. } );
  27020. h.mulAssign( 1.0 / 6.0 );
  27021. If( h.lessThan( 0.0 ), () => {
  27022. h.addAssign( 1.0 );
  27023. } );
  27024. } );
  27025. return vec3( h, s, v );
  27026. } ).setLayout( {
  27027. name: 'mx_rgbtohsv',
  27028. type: 'vec3',
  27029. inputs: [
  27030. { name: 'c', type: 'vec3' }
  27031. ]
  27032. } );
  27033. // Three.js Transpiler
  27034. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  27035. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  27036. const color = vec3( color_immutable ).toVar();
  27037. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  27038. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  27039. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  27040. return mix( linSeg, powSeg, isAbove );
  27041. } ).setLayout( {
  27042. name: 'mx_srgb_texture_to_lin_rec709',
  27043. type: 'vec3',
  27044. inputs: [
  27045. { name: 'color', type: 'vec3' }
  27046. ]
  27047. } );
  27048. const mx_aastep = ( threshold, value ) => {
  27049. threshold = float( threshold );
  27050. value = float( value );
  27051. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  27052. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  27053. };
  27054. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  27055. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  27056. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  27057. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  27058. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  27059. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  27060. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  27061. const mx_safepower = ( in1, in2 = 1 ) => {
  27062. in1 = float( in1 );
  27063. return in1.abs().pow( in2 ).mul( in1.sign() );
  27064. };
  27065. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  27066. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27067. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27068. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27069. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  27070. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  27071. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  27072. return noise_vec4.mul( amplitude ).add( pivot );
  27073. };
  27074. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27075. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27076. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27077. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  27078. 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 );
  27079. 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 );
  27080. 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 );
  27081. 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 );
  27082. /** @module getParallaxCorrectNormal **/
  27083. /**
  27084. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  27085. *
  27086. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  27087. *
  27088. * ```js
  27089. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  27090. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  27091. * ```
  27092. * @function
  27093. * @param {Node<vec3>} normal - The normal to correct.
  27094. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  27095. * @param {Node<vec3>} cubePos - The cube position.
  27096. * @return {Node<vec3>} The parallax corrected normal.
  27097. */
  27098. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  27099. const nDir = normalize( normal ).toVar( 'nDir' );
  27100. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  27101. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  27102. const rbminmax = vec3().toVar( 'rbminmax' );
  27103. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  27104. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  27105. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  27106. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  27107. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  27108. return boxIntersection.sub( cubePos );
  27109. } );
  27110. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  27111. // normal is assumed to have unit length
  27112. const x = normal.x, y = normal.y, z = normal.z;
  27113. // band 0
  27114. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  27115. // band 1
  27116. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  27117. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  27118. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  27119. // band 2
  27120. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  27121. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  27122. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  27123. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  27124. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  27125. return result;
  27126. } );
  27127. // constants
  27128. var TSL = /*#__PURE__*/Object.freeze({
  27129. __proto__: null,
  27130. BRDF_GGX: BRDF_GGX,
  27131. BRDF_Lambert: BRDF_Lambert,
  27132. BasicShadowFilter: BasicShadowFilter,
  27133. Break: Break,
  27134. Const: Const,
  27135. Continue: Continue,
  27136. DFGApprox: DFGApprox,
  27137. D_GGX: D_GGX,
  27138. Discard: Discard,
  27139. EPSILON: EPSILON,
  27140. F_Schlick: F_Schlick,
  27141. Fn: Fn,
  27142. INFINITY: INFINITY,
  27143. If: If,
  27144. Loop: Loop,
  27145. NodeAccess: NodeAccess,
  27146. NodeShaderStage: NodeShaderStage,
  27147. NodeType: NodeType,
  27148. NodeUpdateType: NodeUpdateType,
  27149. PCFShadowFilter: PCFShadowFilter,
  27150. PCFSoftShadowFilter: PCFSoftShadowFilter,
  27151. PI: PI,
  27152. PI2: PI2,
  27153. Return: Return,
  27154. Schlick_to_F0: Schlick_to_F0,
  27155. ScriptableNodeResources: ScriptableNodeResources,
  27156. ShaderNode: ShaderNode,
  27157. TBNViewMatrix: TBNViewMatrix,
  27158. VSMShadowFilter: VSMShadowFilter,
  27159. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  27160. Var: Var,
  27161. abs: abs,
  27162. acesFilmicToneMapping: acesFilmicToneMapping,
  27163. acos: acos,
  27164. add: add,
  27165. addMethodChaining: addMethodChaining,
  27166. addNodeElement: addNodeElement,
  27167. agxToneMapping: agxToneMapping,
  27168. all: all,
  27169. alphaT: alphaT,
  27170. and: and,
  27171. anisotropy: anisotropy,
  27172. anisotropyB: anisotropyB,
  27173. anisotropyT: anisotropyT,
  27174. any: any,
  27175. append: append,
  27176. arrayBuffer: arrayBuffer,
  27177. asin: asin,
  27178. assign: assign,
  27179. atan: atan,
  27180. atan2: atan2,
  27181. atomicAdd: atomicAdd,
  27182. atomicAnd: atomicAnd,
  27183. atomicFunc: atomicFunc,
  27184. atomicMax: atomicMax,
  27185. atomicMin: atomicMin,
  27186. atomicOr: atomicOr,
  27187. atomicStore: atomicStore,
  27188. atomicSub: atomicSub,
  27189. atomicXor: atomicXor,
  27190. attenuationColor: attenuationColor,
  27191. attenuationDistance: attenuationDistance,
  27192. attribute: attribute,
  27193. attributeArray: attributeArray,
  27194. backgroundBlurriness: backgroundBlurriness,
  27195. backgroundIntensity: backgroundIntensity,
  27196. backgroundRotation: backgroundRotation,
  27197. batch: batch,
  27198. billboarding: billboarding,
  27199. bitAnd: bitAnd,
  27200. bitNot: bitNot,
  27201. bitOr: bitOr,
  27202. bitXor: bitXor,
  27203. bitangentGeometry: bitangentGeometry,
  27204. bitangentLocal: bitangentLocal,
  27205. bitangentView: bitangentView,
  27206. bitangentWorld: bitangentWorld,
  27207. bitcast: bitcast,
  27208. blendBurn: blendBurn,
  27209. blendColor: blendColor,
  27210. blendDodge: blendDodge,
  27211. blendOverlay: blendOverlay,
  27212. blendScreen: blendScreen,
  27213. blur: blur,
  27214. bool: bool,
  27215. buffer: buffer,
  27216. bufferAttribute: bufferAttribute,
  27217. bumpMap: bumpMap,
  27218. burn: burn,
  27219. bvec2: bvec2,
  27220. bvec3: bvec3,
  27221. bvec4: bvec4,
  27222. bypass: bypass,
  27223. cache: cache,
  27224. call: call,
  27225. cameraFar: cameraFar,
  27226. cameraNear: cameraNear,
  27227. cameraNormalMatrix: cameraNormalMatrix,
  27228. cameraPosition: cameraPosition,
  27229. cameraProjectionMatrix: cameraProjectionMatrix,
  27230. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  27231. cameraViewMatrix: cameraViewMatrix,
  27232. cameraWorldMatrix: cameraWorldMatrix,
  27233. cbrt: cbrt,
  27234. cdl: cdl,
  27235. ceil: ceil,
  27236. checker: checker,
  27237. cineonToneMapping: cineonToneMapping,
  27238. clamp: clamp,
  27239. clearcoat: clearcoat,
  27240. clearcoatRoughness: clearcoatRoughness,
  27241. code: code,
  27242. color: color,
  27243. colorSpaceToWorking: colorSpaceToWorking,
  27244. colorToDirection: colorToDirection,
  27245. compute: compute,
  27246. cond: cond,
  27247. context: context,
  27248. convert: convert,
  27249. convertColorSpace: convertColorSpace,
  27250. convertToTexture: convertToTexture,
  27251. cos: cos,
  27252. cross: cross,
  27253. cubeTexture: cubeTexture,
  27254. dFdx: dFdx,
  27255. dFdy: dFdy,
  27256. dashSize: dashSize,
  27257. defaultBuildStages: defaultBuildStages,
  27258. defaultShaderStages: defaultShaderStages,
  27259. defined: defined,
  27260. degrees: degrees,
  27261. deltaTime: deltaTime,
  27262. densityFog: densityFog,
  27263. densityFogFactor: densityFogFactor,
  27264. depth: depth,
  27265. depthPass: depthPass,
  27266. difference: difference,
  27267. diffuseColor: diffuseColor,
  27268. directPointLight: directPointLight,
  27269. directionToColor: directionToColor,
  27270. dispersion: dispersion,
  27271. distance: distance,
  27272. div: div,
  27273. dodge: dodge,
  27274. dot: dot,
  27275. drawIndex: drawIndex,
  27276. dynamicBufferAttribute: dynamicBufferAttribute,
  27277. element: element,
  27278. emissive: emissive,
  27279. equal: equal,
  27280. equals: equals,
  27281. equirectUV: equirectUV,
  27282. exp: exp,
  27283. exp2: exp2,
  27284. expression: expression,
  27285. faceDirection: faceDirection,
  27286. faceForward: faceForward,
  27287. faceforward: faceforward,
  27288. float: float,
  27289. floor: floor,
  27290. fog: fog,
  27291. fract: fract,
  27292. frameGroup: frameGroup,
  27293. frameId: frameId,
  27294. frontFacing: frontFacing,
  27295. fwidth: fwidth,
  27296. gain: gain,
  27297. gapSize: gapSize,
  27298. getConstNodeType: getConstNodeType,
  27299. getCurrentStack: getCurrentStack,
  27300. getDirection: getDirection,
  27301. getDistanceAttenuation: getDistanceAttenuation,
  27302. getGeometryRoughness: getGeometryRoughness,
  27303. getNormalFromDepth: getNormalFromDepth,
  27304. getParallaxCorrectNormal: getParallaxCorrectNormal,
  27305. getRoughness: getRoughness,
  27306. getScreenPosition: getScreenPosition,
  27307. getShIrradianceAt: getShIrradianceAt,
  27308. getTextureIndex: getTextureIndex,
  27309. getViewPosition: getViewPosition,
  27310. globalId: globalId,
  27311. glsl: glsl,
  27312. glslFn: glslFn,
  27313. grayscale: grayscale,
  27314. greaterThan: greaterThan,
  27315. greaterThanEqual: greaterThanEqual,
  27316. hash: hash,
  27317. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  27318. highpModelViewMatrix: highpModelViewMatrix,
  27319. hue: hue,
  27320. instance: instance,
  27321. instanceIndex: instanceIndex,
  27322. instancedArray: instancedArray,
  27323. instancedBufferAttribute: instancedBufferAttribute,
  27324. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  27325. instancedMesh: instancedMesh,
  27326. int: int,
  27327. inverseSqrt: inverseSqrt,
  27328. inversesqrt: inversesqrt,
  27329. invocationLocalIndex: invocationLocalIndex,
  27330. invocationSubgroupIndex: invocationSubgroupIndex,
  27331. ior: ior,
  27332. iridescence: iridescence,
  27333. iridescenceIOR: iridescenceIOR,
  27334. iridescenceThickness: iridescenceThickness,
  27335. ivec2: ivec2,
  27336. ivec3: ivec3,
  27337. ivec4: ivec4,
  27338. js: js,
  27339. label: label,
  27340. length: length,
  27341. lengthSq: lengthSq,
  27342. lessThan: lessThan,
  27343. lessThanEqual: lessThanEqual,
  27344. lightPosition: lightPosition,
  27345. lightProjectionUV: lightProjectionUV,
  27346. lightShadowMatrix: lightShadowMatrix,
  27347. lightTargetDirection: lightTargetDirection,
  27348. lightTargetPosition: lightTargetPosition,
  27349. lightViewPosition: lightViewPosition,
  27350. lightingContext: lightingContext,
  27351. lights: lights,
  27352. linearDepth: linearDepth,
  27353. linearToneMapping: linearToneMapping,
  27354. localId: localId,
  27355. log: log,
  27356. log2: log2,
  27357. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  27358. loop: loop,
  27359. luminance: luminance,
  27360. mat2: mat2,
  27361. mat3: mat3,
  27362. mat4: mat4,
  27363. matcapUV: matcapUV,
  27364. materialAO: materialAO,
  27365. materialAlphaTest: materialAlphaTest,
  27366. materialAnisotropy: materialAnisotropy,
  27367. materialAnisotropyVector: materialAnisotropyVector,
  27368. materialAttenuationColor: materialAttenuationColor,
  27369. materialAttenuationDistance: materialAttenuationDistance,
  27370. materialClearcoat: materialClearcoat,
  27371. materialClearcoatNormal: materialClearcoatNormal,
  27372. materialClearcoatRoughness: materialClearcoatRoughness,
  27373. materialColor: materialColor,
  27374. materialDispersion: materialDispersion,
  27375. materialEmissive: materialEmissive,
  27376. materialIOR: materialIOR,
  27377. materialIridescence: materialIridescence,
  27378. materialIridescenceIOR: materialIridescenceIOR,
  27379. materialIridescenceThickness: materialIridescenceThickness,
  27380. materialLightMap: materialLightMap,
  27381. materialLineDashOffset: materialLineDashOffset,
  27382. materialLineDashSize: materialLineDashSize,
  27383. materialLineGapSize: materialLineGapSize,
  27384. materialLineScale: materialLineScale,
  27385. materialLineWidth: materialLineWidth,
  27386. materialMetalness: materialMetalness,
  27387. materialNormal: materialNormal,
  27388. materialOpacity: materialOpacity,
  27389. materialPointSize: materialPointSize,
  27390. materialReference: materialReference,
  27391. materialReflectivity: materialReflectivity,
  27392. materialRefractionRatio: materialRefractionRatio,
  27393. materialRotation: materialRotation,
  27394. materialRoughness: materialRoughness,
  27395. materialSheen: materialSheen,
  27396. materialSheenRoughness: materialSheenRoughness,
  27397. materialShininess: materialShininess,
  27398. materialSpecular: materialSpecular,
  27399. materialSpecularColor: materialSpecularColor,
  27400. materialSpecularIntensity: materialSpecularIntensity,
  27401. materialSpecularStrength: materialSpecularStrength,
  27402. materialThickness: materialThickness,
  27403. materialTransmission: materialTransmission,
  27404. max: max$1,
  27405. maxMipLevel: maxMipLevel,
  27406. mediumpModelViewMatrix: mediumpModelViewMatrix,
  27407. metalness: metalness,
  27408. min: min$1,
  27409. mix: mix,
  27410. mixElement: mixElement,
  27411. mod: mod,
  27412. modInt: modInt,
  27413. modelDirection: modelDirection,
  27414. modelNormalMatrix: modelNormalMatrix,
  27415. modelPosition: modelPosition,
  27416. modelScale: modelScale,
  27417. modelViewMatrix: modelViewMatrix,
  27418. modelViewPosition: modelViewPosition,
  27419. modelViewProjection: modelViewProjection,
  27420. modelWorldMatrix: modelWorldMatrix,
  27421. modelWorldMatrixInverse: modelWorldMatrixInverse,
  27422. morphReference: morphReference,
  27423. mrt: mrt,
  27424. mul: mul,
  27425. mx_aastep: mx_aastep,
  27426. mx_cell_noise_float: mx_cell_noise_float,
  27427. mx_contrast: mx_contrast,
  27428. mx_fractal_noise_float: mx_fractal_noise_float,
  27429. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  27430. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  27431. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  27432. mx_hsvtorgb: mx_hsvtorgb,
  27433. mx_noise_float: mx_noise_float,
  27434. mx_noise_vec3: mx_noise_vec3,
  27435. mx_noise_vec4: mx_noise_vec4,
  27436. mx_ramplr: mx_ramplr,
  27437. mx_ramptb: mx_ramptb,
  27438. mx_rgbtohsv: mx_rgbtohsv,
  27439. mx_safepower: mx_safepower,
  27440. mx_splitlr: mx_splitlr,
  27441. mx_splittb: mx_splittb,
  27442. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  27443. mx_transform_uv: mx_transform_uv,
  27444. mx_worley_noise_float: mx_worley_noise_float,
  27445. mx_worley_noise_vec2: mx_worley_noise_vec2,
  27446. mx_worley_noise_vec3: mx_worley_noise_vec3,
  27447. negate: negate,
  27448. neutralToneMapping: neutralToneMapping,
  27449. nodeArray: nodeArray,
  27450. nodeImmutable: nodeImmutable,
  27451. nodeObject: nodeObject,
  27452. nodeObjects: nodeObjects,
  27453. nodeProxy: nodeProxy,
  27454. normalFlat: normalFlat,
  27455. normalGeometry: normalGeometry,
  27456. normalLocal: normalLocal,
  27457. normalMap: normalMap,
  27458. normalView: normalView,
  27459. normalWorld: normalWorld,
  27460. normalize: normalize,
  27461. not: not,
  27462. notEqual: notEqual,
  27463. numWorkgroups: numWorkgroups,
  27464. objectDirection: objectDirection,
  27465. objectGroup: objectGroup,
  27466. objectPosition: objectPosition,
  27467. objectScale: objectScale,
  27468. objectViewPosition: objectViewPosition,
  27469. objectWorldMatrix: objectWorldMatrix,
  27470. oneMinus: oneMinus,
  27471. or: or,
  27472. orthographicDepthToViewZ: orthographicDepthToViewZ,
  27473. oscSawtooth: oscSawtooth,
  27474. oscSine: oscSine,
  27475. oscSquare: oscSquare,
  27476. oscTriangle: oscTriangle,
  27477. output: output,
  27478. outputStruct: outputStruct,
  27479. overlay: overlay,
  27480. overloadingFn: overloadingFn,
  27481. parabola: parabola,
  27482. parallaxDirection: parallaxDirection,
  27483. parallaxUV: parallaxUV,
  27484. parameter: parameter,
  27485. pass: pass,
  27486. passTexture: passTexture,
  27487. pcurve: pcurve,
  27488. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  27489. pmremTexture: pmremTexture,
  27490. pointUV: pointUV,
  27491. pointWidth: pointWidth,
  27492. positionGeometry: positionGeometry,
  27493. positionLocal: positionLocal,
  27494. positionPrevious: positionPrevious,
  27495. positionView: positionView,
  27496. positionViewDirection: positionViewDirection,
  27497. positionWorld: positionWorld,
  27498. positionWorldDirection: positionWorldDirection,
  27499. posterize: posterize,
  27500. pow: pow,
  27501. pow2: pow2,
  27502. pow3: pow3,
  27503. pow4: pow4,
  27504. property: property,
  27505. radians: radians,
  27506. rand: rand,
  27507. range: range,
  27508. rangeFog: rangeFog,
  27509. rangeFogFactor: rangeFogFactor,
  27510. reciprocal: reciprocal,
  27511. reference: reference,
  27512. referenceBuffer: referenceBuffer,
  27513. reflect: reflect,
  27514. reflectVector: reflectVector,
  27515. reflectView: reflectView,
  27516. reflector: reflector,
  27517. refract: refract,
  27518. refractVector: refractVector,
  27519. refractView: refractView,
  27520. reinhardToneMapping: reinhardToneMapping,
  27521. remainder: remainder,
  27522. remap: remap,
  27523. remapClamp: remapClamp,
  27524. renderGroup: renderGroup,
  27525. renderOutput: renderOutput,
  27526. rendererReference: rendererReference,
  27527. rotate: rotate,
  27528. rotateUV: rotateUV,
  27529. roughness: roughness,
  27530. round: round,
  27531. rtt: rtt,
  27532. sRGBTransferEOTF: sRGBTransferEOTF,
  27533. sRGBTransferOETF: sRGBTransferOETF,
  27534. sampler: sampler,
  27535. saturate: saturate,
  27536. saturation: saturation,
  27537. screen: screen,
  27538. screenCoordinate: screenCoordinate,
  27539. screenSize: screenSize,
  27540. screenUV: screenUV,
  27541. scriptable: scriptable,
  27542. scriptableValue: scriptableValue,
  27543. select: select,
  27544. setCurrentStack: setCurrentStack,
  27545. shaderStages: shaderStages,
  27546. shadow: shadow,
  27547. shadowPositionWorld: shadowPositionWorld,
  27548. shapeCircle: shapeCircle,
  27549. sharedUniformGroup: sharedUniformGroup,
  27550. sheen: sheen,
  27551. sheenRoughness: sheenRoughness,
  27552. shiftLeft: shiftLeft,
  27553. shiftRight: shiftRight,
  27554. shininess: shininess,
  27555. sign: sign,
  27556. sin: sin,
  27557. sinc: sinc,
  27558. skinning: skinning,
  27559. skinningReference: skinningReference,
  27560. smoothstep: smoothstep,
  27561. smoothstepElement: smoothstepElement,
  27562. specularColor: specularColor,
  27563. specularF90: specularF90,
  27564. spherizeUV: spherizeUV,
  27565. split: split,
  27566. spritesheetUV: spritesheetUV,
  27567. sqrt: sqrt,
  27568. stack: stack,
  27569. step: step,
  27570. storage: storage,
  27571. storageBarrier: storageBarrier,
  27572. storageObject: storageObject,
  27573. storageTexture: storageTexture,
  27574. string: string,
  27575. sub: sub,
  27576. subgroupIndex: subgroupIndex,
  27577. subgroupSize: subgroupSize,
  27578. tan: tan,
  27579. tangentGeometry: tangentGeometry,
  27580. tangentLocal: tangentLocal,
  27581. tangentView: tangentView,
  27582. tangentWorld: tangentWorld,
  27583. temp: temp,
  27584. texture: texture,
  27585. texture3D: texture3D,
  27586. textureBarrier: textureBarrier,
  27587. textureBicubic: textureBicubic,
  27588. textureCubeUV: textureCubeUV,
  27589. textureLoad: textureLoad,
  27590. textureSize: textureSize,
  27591. textureStore: textureStore,
  27592. thickness: thickness,
  27593. time: time,
  27594. timerDelta: timerDelta,
  27595. timerGlobal: timerGlobal,
  27596. timerLocal: timerLocal,
  27597. toOutputColorSpace: toOutputColorSpace,
  27598. toWorkingColorSpace: toWorkingColorSpace,
  27599. toneMapping: toneMapping,
  27600. toneMappingExposure: toneMappingExposure,
  27601. toonOutlinePass: toonOutlinePass,
  27602. transformDirection: transformDirection,
  27603. transformNormal: transformNormal,
  27604. transformNormalToView: transformNormalToView,
  27605. transformedBentNormalView: transformedBentNormalView,
  27606. transformedBitangentView: transformedBitangentView,
  27607. transformedBitangentWorld: transformedBitangentWorld,
  27608. transformedClearcoatNormalView: transformedClearcoatNormalView,
  27609. transformedNormalView: transformedNormalView,
  27610. transformedNormalWorld: transformedNormalWorld,
  27611. transformedTangentView: transformedTangentView,
  27612. transformedTangentWorld: transformedTangentWorld,
  27613. transmission: transmission,
  27614. transpose: transpose,
  27615. triNoise3D: triNoise3D,
  27616. triplanarTexture: triplanarTexture,
  27617. triplanarTextures: triplanarTextures,
  27618. trunc: trunc,
  27619. tslFn: tslFn,
  27620. uint: uint,
  27621. uniform: uniform,
  27622. uniformArray: uniformArray,
  27623. uniformGroup: uniformGroup,
  27624. uniforms: uniforms,
  27625. userData: userData,
  27626. uv: uv,
  27627. uvec2: uvec2,
  27628. uvec3: uvec3,
  27629. uvec4: uvec4,
  27630. varying: varying,
  27631. varyingProperty: varyingProperty,
  27632. vec2: vec2,
  27633. vec3: vec3,
  27634. vec4: vec4,
  27635. vectorComponents: vectorComponents,
  27636. velocity: velocity,
  27637. vertexColor: vertexColor,
  27638. vertexIndex: vertexIndex,
  27639. vertexStage: vertexStage,
  27640. vibrance: vibrance,
  27641. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  27642. viewZToOrthographicDepth: viewZToOrthographicDepth,
  27643. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  27644. viewport: viewport,
  27645. viewportBottomLeft: viewportBottomLeft,
  27646. viewportCoordinate: viewportCoordinate,
  27647. viewportDepthTexture: viewportDepthTexture,
  27648. viewportLinearDepth: viewportLinearDepth,
  27649. viewportMipTexture: viewportMipTexture,
  27650. viewportResolution: viewportResolution,
  27651. viewportSafeUV: viewportSafeUV,
  27652. viewportSharedTexture: viewportSharedTexture,
  27653. viewportSize: viewportSize,
  27654. viewportTexture: viewportTexture,
  27655. viewportTopLeft: viewportTopLeft,
  27656. viewportUV: viewportUV,
  27657. wgsl: wgsl,
  27658. wgslFn: wgslFn,
  27659. workgroupArray: workgroupArray,
  27660. workgroupBarrier: workgroupBarrier,
  27661. workgroupId: workgroupId,
  27662. workingToColorSpace: workingToColorSpace,
  27663. xor: xor
  27664. });
  27665. const _clearColor$1 = /*@__PURE__*/ new Color4();
  27666. /**
  27667. * This renderer module manages the background.
  27668. *
  27669. * @private
  27670. * @augments DataMap
  27671. */
  27672. class Background extends DataMap {
  27673. /**
  27674. * Constructs a new background management component.
  27675. *
  27676. * @param {Renderer} renderer - The renderer.
  27677. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  27678. */
  27679. constructor( renderer, nodes ) {
  27680. super();
  27681. /**
  27682. * The renderer.
  27683. *
  27684. * @type {Renderer}
  27685. */
  27686. this.renderer = renderer;
  27687. /**
  27688. * Renderer component for managing nodes related logic.
  27689. *
  27690. * @type {Nodes}
  27691. */
  27692. this.nodes = nodes;
  27693. }
  27694. /**
  27695. * Updates the background for the given scene. Depending on how `Scene.background`
  27696. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  27697. * or add a mesh to the render list for rendering the background as a textured plane
  27698. * or skybox.
  27699. *
  27700. * @param {Scene} scene - The scene.
  27701. * @param {RenderList} renderList - The current render list.
  27702. * @param {RenderContext} renderContext - The current render context.
  27703. */
  27704. update( scene, renderList, renderContext ) {
  27705. const renderer = this.renderer;
  27706. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  27707. let forceClear = false;
  27708. if ( background === null ) {
  27709. // no background settings, use clear color configuration from the renderer
  27710. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27711. _clearColor$1.a = renderer._clearColor.a;
  27712. } else if ( background.isColor === true ) {
  27713. // background is an opaque color
  27714. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27715. _clearColor$1.a = 1;
  27716. forceClear = true;
  27717. } else if ( background.isNode === true ) {
  27718. const sceneData = this.get( scene );
  27719. const backgroundNode = background;
  27720. _clearColor$1.copy( renderer._clearColor );
  27721. let backgroundMesh = sceneData.backgroundMesh;
  27722. if ( backgroundMesh === undefined ) {
  27723. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  27724. // @TODO: Add Texture2D support using node context
  27725. getUV: () => backgroundRotation.mul( normalWorld ),
  27726. getTextureLevel: () => backgroundBlurriness
  27727. } );
  27728. let viewProj = modelViewProjection;
  27729. viewProj = viewProj.setZ( viewProj.w );
  27730. const nodeMaterial = new NodeMaterial();
  27731. nodeMaterial.name = 'Background.material';
  27732. nodeMaterial.side = BackSide;
  27733. nodeMaterial.depthTest = false;
  27734. nodeMaterial.depthWrite = false;
  27735. nodeMaterial.fog = false;
  27736. nodeMaterial.lights = false;
  27737. nodeMaterial.vertexNode = viewProj;
  27738. nodeMaterial.colorNode = backgroundMeshNode;
  27739. sceneData.backgroundMeshNode = backgroundMeshNode;
  27740. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  27741. backgroundMesh.frustumCulled = false;
  27742. backgroundMesh.name = 'Background.mesh';
  27743. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  27744. this.matrixWorld.copyPosition( camera.matrixWorld );
  27745. };
  27746. }
  27747. const backgroundCacheKey = backgroundNode.getCacheKey();
  27748. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  27749. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  27750. sceneData.backgroundMeshNode.needsUpdate = true;
  27751. backgroundMesh.material.needsUpdate = true;
  27752. sceneData.backgroundCacheKey = backgroundCacheKey;
  27753. }
  27754. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  27755. } else {
  27756. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  27757. }
  27758. //
  27759. if ( renderer.autoClear === true || forceClear === true ) {
  27760. const clearColorValue = renderContext.clearColorValue;
  27761. clearColorValue.r = _clearColor$1.r;
  27762. clearColorValue.g = _clearColor$1.g;
  27763. clearColorValue.b = _clearColor$1.b;
  27764. clearColorValue.a = _clearColor$1.a;
  27765. // premultiply alpha
  27766. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  27767. clearColorValue.r *= clearColorValue.a;
  27768. clearColorValue.g *= clearColorValue.a;
  27769. clearColorValue.b *= clearColorValue.a;
  27770. }
  27771. //
  27772. renderContext.depthClearValue = renderer._clearDepth;
  27773. renderContext.stencilClearValue = renderer._clearStencil;
  27774. renderContext.clearColor = renderer.autoClearColor === true;
  27775. renderContext.clearDepth = renderer.autoClearDepth === true;
  27776. renderContext.clearStencil = renderer.autoClearStencil === true;
  27777. } else {
  27778. renderContext.clearColor = false;
  27779. renderContext.clearDepth = false;
  27780. renderContext.clearStencil = false;
  27781. }
  27782. }
  27783. }
  27784. let _id$6 = 0;
  27785. /**
  27786. * A bind group represents a collection of bindings and thus a collection
  27787. * or resources. Bind groups are assigned to pipelines to provide them
  27788. * with the required resources (like uniform buffers or textures).
  27789. *
  27790. * @private
  27791. */
  27792. class BindGroup {
  27793. /**
  27794. * Constructs a new bind group.
  27795. *
  27796. * @param {String} name - The bind group's name.
  27797. * @param {Array<Binding>} bindings - An array of bindings.
  27798. * @param {Number} index - The group index.
  27799. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  27800. */
  27801. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  27802. /**
  27803. * The bind group's name.
  27804. *
  27805. * @type {String}
  27806. */
  27807. this.name = name;
  27808. /**
  27809. * An array of bindings.
  27810. *
  27811. * @type {Array<Binding>}
  27812. */
  27813. this.bindings = bindings;
  27814. /**
  27815. * The group index.
  27816. *
  27817. * @type {Number}
  27818. */
  27819. this.index = index;
  27820. /**
  27821. * An array of reference bindings.
  27822. *
  27823. * @type {Array<Binding>}
  27824. */
  27825. this.bindingsReference = bindingsReference;
  27826. /**
  27827. * The group's ID.
  27828. *
  27829. * @type {Number}
  27830. */
  27831. this.id = _id$6 ++;
  27832. }
  27833. }
  27834. /**
  27835. * This module represents the state of a node builder after it was
  27836. * used to build the nodes for a render object. The state holds the
  27837. * results of the build for further processing in the renderer.
  27838. *
  27839. * Render objects with identical cache keys share the same node builder state.
  27840. *
  27841. * @private
  27842. */
  27843. class NodeBuilderState {
  27844. /**
  27845. * Constructs a new node builder state.
  27846. *
  27847. * @param {String?} vertexShader - The native vertex shader code.
  27848. * @param {String?} fragmentShader - The native fragment shader code.
  27849. * @param {String?} computeShader - The native compute shader code.
  27850. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  27851. * @param {Array<BindGroup>} bindings - An array of bind groups.
  27852. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  27853. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  27854. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  27855. * @param {NodeMaterialObserver} monitor - A node material observer.
  27856. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  27857. */
  27858. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  27859. /**
  27860. * The native vertex shader code.
  27861. *
  27862. * @type {String}
  27863. */
  27864. this.vertexShader = vertexShader;
  27865. /**
  27866. * The native fragment shader code.
  27867. *
  27868. * @type {String}
  27869. */
  27870. this.fragmentShader = fragmentShader;
  27871. /**
  27872. * The native compute shader code.
  27873. *
  27874. * @type {String}
  27875. */
  27876. this.computeShader = computeShader;
  27877. /**
  27878. * An array with transform attribute objects.
  27879. * Only relevant when using compute shaders with WebGL 2.
  27880. *
  27881. * @type {Array<Object>}
  27882. */
  27883. this.transforms = transforms;
  27884. /**
  27885. * An array of node attributes representing
  27886. * the attributes of the shaders.
  27887. *
  27888. * @type {Array<NodeAttribute>}
  27889. */
  27890. this.nodeAttributes = nodeAttributes;
  27891. /**
  27892. * An array of bind groups representing the uniform or storage
  27893. * buffers, texture or samplers of the shader.
  27894. *
  27895. * @type {Array<BindGroup>}
  27896. */
  27897. this.bindings = bindings;
  27898. /**
  27899. * An array of nodes that implement their `update()` method.
  27900. *
  27901. * @type {Array<Node>}
  27902. */
  27903. this.updateNodes = updateNodes;
  27904. /**
  27905. * An array of nodes that implement their `updateBefore()` method.
  27906. *
  27907. * @type {Array<Node>}
  27908. */
  27909. this.updateBeforeNodes = updateBeforeNodes;
  27910. /**
  27911. * An array of nodes that implement their `updateAfter()` method.
  27912. *
  27913. * @type {Array<Node>}
  27914. */
  27915. this.updateAfterNodes = updateAfterNodes;
  27916. /**
  27917. * A node material observer.
  27918. *
  27919. * @type {NodeMaterialObserver}
  27920. */
  27921. this.monitor = monitor;
  27922. /**
  27923. * How often this state is used by render objects.
  27924. *
  27925. * @type {Number}
  27926. */
  27927. this.usedTimes = 0;
  27928. }
  27929. /**
  27930. * This method is used to create a array of bind groups based
  27931. * on the existing bind groups of this state. Shared groups are
  27932. * not cloned.
  27933. *
  27934. * @return {Array<BindGroup>} A array of bind groups.
  27935. */
  27936. createBindings() {
  27937. const bindings = [];
  27938. for ( const instanceGroup of this.bindings ) {
  27939. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // TODO: Is it safe to always check the first binding in the group?
  27940. if ( shared !== true ) {
  27941. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  27942. bindings.push( bindingsGroup );
  27943. for ( const instanceBinding of instanceGroup.bindings ) {
  27944. bindingsGroup.bindings.push( instanceBinding.clone() );
  27945. }
  27946. } else {
  27947. bindings.push( instanceGroup );
  27948. }
  27949. }
  27950. return bindings;
  27951. }
  27952. }
  27953. /**
  27954. * {@link NodeBuilder} is going to create instances of this class during the build process
  27955. * of nodes. They represent the final shader attributes that are going to be generated
  27956. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  27957. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  27958. */
  27959. class NodeAttribute {
  27960. /**
  27961. * Constructs a new node attribute.
  27962. *
  27963. * @param {String} name - The name of the attribute.
  27964. * @param {String} type - The type of the attribute.
  27965. * @param {Node?} node - An optional reference to the node.
  27966. */
  27967. constructor( name, type, node = null ) {
  27968. /**
  27969. * This flag can be used for type testing.
  27970. *
  27971. * @type {Boolean}
  27972. * @readonly
  27973. * @default true
  27974. */
  27975. this.isNodeAttribute = true;
  27976. /**
  27977. * The name of the attribute.
  27978. *
  27979. * @type {String}
  27980. */
  27981. this.name = name;
  27982. /**
  27983. * The type of the attribute.
  27984. *
  27985. * @type {String}
  27986. */
  27987. this.type = type;
  27988. /**
  27989. * An optional reference to the node.
  27990. *
  27991. * @type {Node?}
  27992. * @default null
  27993. */
  27994. this.node = node;
  27995. }
  27996. }
  27997. /**
  27998. * {@link NodeBuilder} is going to create instances of this class during the build process
  27999. * of nodes. They represent the final shader uniforms that are going to be generated
  28000. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  28001. * for this purpose.
  28002. */
  28003. class NodeUniform {
  28004. /**
  28005. * Constructs a new node uniform.
  28006. *
  28007. * @param {String} name - The name of the uniform.
  28008. * @param {String} type - The type of the uniform.
  28009. * @param {UniformNode} node - An reference to the node.
  28010. */
  28011. constructor( name, type, node ) {
  28012. /**
  28013. * This flag can be used for type testing.
  28014. *
  28015. * @type {Boolean}
  28016. * @readonly
  28017. * @default true
  28018. */
  28019. this.isNodeUniform = true;
  28020. /**
  28021. * The name of the uniform.
  28022. *
  28023. * @type {String}
  28024. */
  28025. this.name = name;
  28026. /**
  28027. * The type of the uniform.
  28028. *
  28029. * @type {String}
  28030. */
  28031. this.type = type;
  28032. /**
  28033. * An reference to the node.
  28034. *
  28035. * @type {UniformNode}
  28036. */
  28037. this.node = node.getSelf();
  28038. }
  28039. /**
  28040. * The value of the uniform node.
  28041. *
  28042. * @type {Any}
  28043. */
  28044. get value() {
  28045. return this.node.value;
  28046. }
  28047. set value( val ) {
  28048. this.node.value = val;
  28049. }
  28050. /**
  28051. * The id of the uniform node.
  28052. *
  28053. * @type {Number}
  28054. */
  28055. get id() {
  28056. return this.node.id;
  28057. }
  28058. /**
  28059. * The uniform node's group.
  28060. *
  28061. * @type {UniformGroupNode}
  28062. */
  28063. get groupNode() {
  28064. return this.node.groupNode;
  28065. }
  28066. }
  28067. /**
  28068. * {@link NodeBuilder} is going to create instances of this class during the build process
  28069. * of nodes. They represent the final shader variables that are going to be generated
  28070. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  28071. * this purpose.
  28072. */
  28073. class NodeVar {
  28074. /**
  28075. * Constructs a new node variable.
  28076. *
  28077. * @param {String} name - The name of the variable.
  28078. * @param {String} type - The type of the variable.
  28079. * @param {Boolean} [readOnly=false] - The read-only flag.
  28080. */
  28081. constructor( name, type, readOnly = false ) {
  28082. /**
  28083. * This flag can be used for type testing.
  28084. *
  28085. * @type {Boolean}
  28086. * @readonly
  28087. * @default true
  28088. */
  28089. this.isNodeVar = true;
  28090. /**
  28091. * The name of the variable.
  28092. *
  28093. * @type {String}
  28094. */
  28095. this.name = name;
  28096. /**
  28097. * The type of the variable.
  28098. *
  28099. * @type {String}
  28100. */
  28101. this.type = type;
  28102. /**
  28103. * The read-only flag.
  28104. *
  28105. * @type {boolean}
  28106. */
  28107. this.readOnly = readOnly;
  28108. }
  28109. }
  28110. /**
  28111. * {@link NodeBuilder} is going to create instances of this class during the build process
  28112. * of nodes. They represent the final shader varyings that are going to be generated
  28113. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  28114. * this purpose.
  28115. *
  28116. * @augments NodeVar
  28117. */
  28118. class NodeVarying extends NodeVar {
  28119. /**
  28120. * Constructs a new node varying.
  28121. *
  28122. * @param {String} name - The name of the varying.
  28123. * @param {String} type - The type of the varying.
  28124. */
  28125. constructor( name, type ) {
  28126. super( name, type );
  28127. /**
  28128. * Whether this varying requires interpolation or not. This property can be used
  28129. * to check if the varying can be optimized for a variable.
  28130. *
  28131. * @type {Boolean}
  28132. * @default false
  28133. */
  28134. this.needsInterpolation = false;
  28135. /**
  28136. * This flag can be used for type testing.
  28137. *
  28138. * @type {Boolean}
  28139. * @readonly
  28140. * @default true
  28141. */
  28142. this.isNodeVarying = true;
  28143. }
  28144. }
  28145. /**
  28146. * {@link NodeBuilder} is going to create instances of this class during the build process
  28147. * of nodes. They represent user-defined, native shader code portions that are going to be
  28148. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  28149. * for this purpose.
  28150. */
  28151. class NodeCode {
  28152. /**
  28153. * Constructs a new code node.
  28154. *
  28155. * @param {String} name - The name of the code.
  28156. * @param {String} type - The node type.
  28157. * @param {String} [code=''] - The native shader code.
  28158. */
  28159. constructor( name, type, code = '' ) {
  28160. /**
  28161. * The name of the code.
  28162. *
  28163. * @type {String}
  28164. */
  28165. this.name = name;
  28166. /**
  28167. * The node type.
  28168. *
  28169. * @type {String}
  28170. */
  28171. this.type = type;
  28172. /**
  28173. * The native shader code.
  28174. *
  28175. * @type {String}
  28176. * @default ''
  28177. */
  28178. this.code = code;
  28179. Object.defineProperty( this, 'isNodeCode', { value: true } );
  28180. }
  28181. }
  28182. let _id$5 = 0;
  28183. /**
  28184. * This utility class is used in {@link NodeBuilder} as an internal
  28185. * cache data structure for node data.
  28186. */
  28187. class NodeCache {
  28188. /**
  28189. * Constructs a new node cache.
  28190. *
  28191. * @param {NodeCache?} parent - A reference to a parent cache.
  28192. */
  28193. constructor( parent = null ) {
  28194. /**
  28195. * The id of the cache.
  28196. *
  28197. * @type {Number}
  28198. * @readonly
  28199. */
  28200. this.id = _id$5 ++;
  28201. /**
  28202. * A weak map for managing node data.
  28203. *
  28204. * @type {WeakMap<Node, Object>}
  28205. */
  28206. this.nodesData = new WeakMap();
  28207. /**
  28208. * Reference to a parent node cache.
  28209. *
  28210. * @type {NodeCache?}
  28211. * @default null
  28212. */
  28213. this.parent = parent;
  28214. }
  28215. /**
  28216. * Returns the data for the given node.
  28217. *
  28218. * @param {Node} node - The node.
  28219. * @return {Object?} The data for the node.
  28220. */
  28221. getData( node ) {
  28222. let data = this.nodesData.get( node );
  28223. if ( data === undefined && this.parent !== null ) {
  28224. data = this.parent.getData( node );
  28225. }
  28226. return data;
  28227. }
  28228. /**
  28229. * Sets the data for a given node.
  28230. *
  28231. * @param {Node} node - The node.
  28232. * @param {Object} data - The data that should be cached.
  28233. */
  28234. setData( node, data ) {
  28235. this.nodesData.set( node, data );
  28236. }
  28237. }
  28238. /**
  28239. * {@link NodeBuilder} is going to create instances of this class during the build process
  28240. * of nodes. They represent the final shader struct data that are going to be generated
  28241. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  28242. * for this purpose.
  28243. */
  28244. class StructTypeNode extends Node {
  28245. static get type() {
  28246. return 'StructTypeNode';
  28247. }
  28248. /**
  28249. * Constructs a new struct type node.
  28250. *
  28251. * @param {String} name - The name of the struct.
  28252. * @param {Array<String>} types - An array of types.
  28253. */
  28254. constructor( name, types ) {
  28255. super();
  28256. /**
  28257. * The name of the struct.
  28258. *
  28259. * @type {String}
  28260. */
  28261. this.name = name;
  28262. /**
  28263. * An array of types.
  28264. *
  28265. * @type {Array<String>}
  28266. */
  28267. this.types = types;
  28268. /**
  28269. * This flag can be used for type testing.
  28270. *
  28271. * @type {Boolean}
  28272. * @readonly
  28273. * @default true
  28274. */
  28275. this.isStructTypeNode = true;
  28276. }
  28277. /**
  28278. * Returns the member types.
  28279. *
  28280. * @return {Array<String>} The types.
  28281. */
  28282. getMemberTypes() {
  28283. return this.types;
  28284. }
  28285. }
  28286. /**
  28287. * Abstract base class for uniforms.
  28288. *
  28289. * @abstract
  28290. * @private
  28291. */
  28292. class Uniform {
  28293. /**
  28294. * Constructs a new uniform.
  28295. *
  28296. * @param {String} name - The uniform's name.
  28297. * @param {Any} value - The uniform's value.
  28298. */
  28299. constructor( name, value ) {
  28300. /**
  28301. * The uniform's name.
  28302. *
  28303. * @type {String}
  28304. */
  28305. this.name = name;
  28306. /**
  28307. * The uniform's value.
  28308. *
  28309. * @type {Any}
  28310. */
  28311. this.value = value;
  28312. /**
  28313. * Used to build the uniform buffer according to the STD140 layout.
  28314. * Derived uniforms will set this property to a data type specific
  28315. * value.
  28316. *
  28317. * @type {Number}
  28318. */
  28319. this.boundary = 0;
  28320. /**
  28321. * The item size. Derived uniforms will set this property to a data
  28322. * type specific value.
  28323. *
  28324. * @type {Number}
  28325. */
  28326. this.itemSize = 0;
  28327. /**
  28328. * This property is set by {@link UniformsGroup} and marks
  28329. * the start position in the uniform buffer.
  28330. *
  28331. * @type {Number}
  28332. */
  28333. this.offset = 0;
  28334. }
  28335. /**
  28336. * Sets the uniform's value.
  28337. *
  28338. * @param {Any} value - The value to set.
  28339. */
  28340. setValue( value ) {
  28341. this.value = value;
  28342. }
  28343. /**
  28344. * Returns the uniform's value.
  28345. *
  28346. * @return {Any} The value.
  28347. */
  28348. getValue() {
  28349. return this.value;
  28350. }
  28351. }
  28352. /**
  28353. * Represents a Number uniform.
  28354. *
  28355. * @private
  28356. * @augments Uniform
  28357. */
  28358. class NumberUniform extends Uniform {
  28359. /**
  28360. * Constructs a new Number uniform.
  28361. *
  28362. * @param {String} name - The uniform's name.
  28363. * @param {Number} value - The uniform's value.
  28364. */
  28365. constructor( name, value = 0 ) {
  28366. super( name, value );
  28367. /**
  28368. * This flag can be used for type testing.
  28369. *
  28370. * @type {Boolean}
  28371. * @readonly
  28372. * @default true
  28373. */
  28374. this.isNumberUniform = true;
  28375. this.boundary = 4;
  28376. this.itemSize = 1;
  28377. }
  28378. }
  28379. /**
  28380. * Represents a Vector2 uniform.
  28381. *
  28382. * @private
  28383. * @augments Uniform
  28384. */
  28385. class Vector2Uniform extends Uniform {
  28386. /**
  28387. * Constructs a new Number uniform.
  28388. *
  28389. * @param {String} name - The uniform's name.
  28390. * @param {Vector2} value - The uniform's value.
  28391. */
  28392. constructor( name, value = new Vector2() ) {
  28393. super( name, value );
  28394. /**
  28395. * This flag can be used for type testing.
  28396. *
  28397. * @type {Boolean}
  28398. * @readonly
  28399. * @default true
  28400. */
  28401. this.isVector2Uniform = true;
  28402. this.boundary = 8;
  28403. this.itemSize = 2;
  28404. }
  28405. }
  28406. /**
  28407. * Represents a Vector3 uniform.
  28408. *
  28409. * @private
  28410. * @augments Uniform
  28411. */
  28412. class Vector3Uniform extends Uniform {
  28413. /**
  28414. * Constructs a new Number uniform.
  28415. *
  28416. * @param {String} name - The uniform's name.
  28417. * @param {Vector3} value - The uniform's value.
  28418. */
  28419. constructor( name, value = new Vector3() ) {
  28420. super( name, value );
  28421. /**
  28422. * This flag can be used for type testing.
  28423. *
  28424. * @type {Boolean}
  28425. * @readonly
  28426. * @default true
  28427. */
  28428. this.isVector3Uniform = true;
  28429. this.boundary = 16;
  28430. this.itemSize = 3;
  28431. }
  28432. }
  28433. /**
  28434. * Represents a Vector4 uniform.
  28435. *
  28436. * @private
  28437. * @augments Uniform
  28438. */
  28439. class Vector4Uniform extends Uniform {
  28440. /**
  28441. * Constructs a new Number uniform.
  28442. *
  28443. * @param {String} name - The uniform's name.
  28444. * @param {Vector4} value - The uniform's value.
  28445. */
  28446. constructor( name, value = new Vector4() ) {
  28447. super( name, value );
  28448. /**
  28449. * This flag can be used for type testing.
  28450. *
  28451. * @type {Boolean}
  28452. * @readonly
  28453. * @default true
  28454. */
  28455. this.isVector4Uniform = true;
  28456. this.boundary = 16;
  28457. this.itemSize = 4;
  28458. }
  28459. }
  28460. /**
  28461. * Represents a Color uniform.
  28462. *
  28463. * @private
  28464. * @augments Uniform
  28465. */
  28466. class ColorUniform extends Uniform {
  28467. /**
  28468. * Constructs a new Number uniform.
  28469. *
  28470. * @param {String} name - The uniform's name.
  28471. * @param {Color} value - The uniform's value.
  28472. */
  28473. constructor( name, value = new Color() ) {
  28474. super( name, value );
  28475. /**
  28476. * This flag can be used for type testing.
  28477. *
  28478. * @type {Boolean}
  28479. * @readonly
  28480. * @default true
  28481. */
  28482. this.isColorUniform = true;
  28483. this.boundary = 16;
  28484. this.itemSize = 3;
  28485. }
  28486. }
  28487. /**
  28488. * Represents a Matrix3 uniform.
  28489. *
  28490. * @private
  28491. * @augments Uniform
  28492. */
  28493. class Matrix3Uniform extends Uniform {
  28494. /**
  28495. * Constructs a new Number uniform.
  28496. *
  28497. * @param {String} name - The uniform's name.
  28498. * @param {Matrix3} value - The uniform's value.
  28499. */
  28500. constructor( name, value = new Matrix3() ) {
  28501. super( name, value );
  28502. /**
  28503. * This flag can be used for type testing.
  28504. *
  28505. * @type {Boolean}
  28506. * @readonly
  28507. * @default true
  28508. */
  28509. this.isMatrix3Uniform = true;
  28510. this.boundary = 48;
  28511. this.itemSize = 12;
  28512. }
  28513. }
  28514. /**
  28515. * Represents a Matrix4 uniform.
  28516. *
  28517. * @private
  28518. * @augments Uniform
  28519. */
  28520. class Matrix4Uniform extends Uniform {
  28521. /**
  28522. * Constructs a new Number uniform.
  28523. *
  28524. * @param {String} name - The uniform's name.
  28525. * @param {Matrix4} value - The uniform's value.
  28526. */
  28527. constructor( name, value = new Matrix4() ) {
  28528. super( name, value );
  28529. /**
  28530. * This flag can be used for type testing.
  28531. *
  28532. * @type {Boolean}
  28533. * @readonly
  28534. * @default true
  28535. */
  28536. this.isMatrix4Uniform = true;
  28537. this.boundary = 64;
  28538. this.itemSize = 16;
  28539. }
  28540. }
  28541. /**
  28542. * A special form of Number uniform binding type.
  28543. * It's value is managed by a node object.
  28544. *
  28545. * @private
  28546. * @augments NumberUniform
  28547. */
  28548. class NumberNodeUniform extends NumberUniform {
  28549. /**
  28550. * Constructs a new node-based Number uniform.
  28551. *
  28552. * @param {NodeUniform} nodeUniform - The node uniform.
  28553. */
  28554. constructor( nodeUniform ) {
  28555. super( nodeUniform.name, nodeUniform.value );
  28556. /**
  28557. * The node uniform.
  28558. *
  28559. * @type {NodeUniform}
  28560. */
  28561. this.nodeUniform = nodeUniform;
  28562. }
  28563. /**
  28564. * Overwritten to return the value of the node uniform.
  28565. *
  28566. * @return {Number} The value.
  28567. */
  28568. getValue() {
  28569. return this.nodeUniform.value;
  28570. }
  28571. /**
  28572. * Returns the node uniform data type.
  28573. *
  28574. * @return {String} The data type.
  28575. */
  28576. getType() {
  28577. return this.nodeUniform.type;
  28578. }
  28579. }
  28580. /**
  28581. * A special form of Vector2 uniform binding type.
  28582. * It's value is managed by a node object.
  28583. *
  28584. * @private
  28585. * @augments Vector2Uniform
  28586. */
  28587. class Vector2NodeUniform extends Vector2Uniform {
  28588. /**
  28589. * Constructs a new node-based Vector2 uniform.
  28590. *
  28591. * @param {NodeUniform} nodeUniform - The node uniform.
  28592. */
  28593. constructor( nodeUniform ) {
  28594. super( nodeUniform.name, nodeUniform.value );
  28595. /**
  28596. * The node uniform.
  28597. *
  28598. * @type {NodeUniform}
  28599. */
  28600. this.nodeUniform = nodeUniform;
  28601. }
  28602. /**
  28603. * Overwritten to return the value of the node uniform.
  28604. *
  28605. * @return {Vector2} The value.
  28606. */
  28607. getValue() {
  28608. return this.nodeUniform.value;
  28609. }
  28610. /**
  28611. * Returns the node uniform data type.
  28612. *
  28613. * @return {String} The data type.
  28614. */
  28615. getType() {
  28616. return this.nodeUniform.type;
  28617. }
  28618. }
  28619. /**
  28620. * A special form of Vector3 uniform binding type.
  28621. * It's value is managed by a node object.
  28622. *
  28623. * @private
  28624. * @augments Vector3Uniform
  28625. */
  28626. class Vector3NodeUniform extends Vector3Uniform {
  28627. /**
  28628. * Constructs a new node-based Vector3 uniform.
  28629. *
  28630. * @param {NodeUniform} nodeUniform - The node uniform.
  28631. */
  28632. constructor( nodeUniform ) {
  28633. super( nodeUniform.name, nodeUniform.value );
  28634. /**
  28635. * The node uniform.
  28636. *
  28637. * @type {NodeUniform}
  28638. */
  28639. this.nodeUniform = nodeUniform;
  28640. }
  28641. /**
  28642. * Overwritten to return the value of the node uniform.
  28643. *
  28644. * @return {Vector3} The value.
  28645. */
  28646. getValue() {
  28647. return this.nodeUniform.value;
  28648. }
  28649. /**
  28650. * Returns the node uniform data type.
  28651. *
  28652. * @return {String} The data type.
  28653. */
  28654. getType() {
  28655. return this.nodeUniform.type;
  28656. }
  28657. }
  28658. /**
  28659. * A special form of Vector4 uniform binding type.
  28660. * It's value is managed by a node object.
  28661. *
  28662. * @private
  28663. * @augments Vector4Uniform
  28664. */
  28665. class Vector4NodeUniform extends Vector4Uniform {
  28666. /**
  28667. * Constructs a new node-based Vector4 uniform.
  28668. *
  28669. * @param {NodeUniform} nodeUniform - The node uniform.
  28670. */
  28671. constructor( nodeUniform ) {
  28672. super( nodeUniform.name, nodeUniform.value );
  28673. /**
  28674. * The node uniform.
  28675. *
  28676. * @type {NodeUniform}
  28677. */
  28678. this.nodeUniform = nodeUniform;
  28679. }
  28680. /**
  28681. * Overwritten to return the value of the node uniform.
  28682. *
  28683. * @return {Vector4} The value.
  28684. */
  28685. getValue() {
  28686. return this.nodeUniform.value;
  28687. }
  28688. /**
  28689. * Returns the node uniform data type.
  28690. *
  28691. * @return {String} The data type.
  28692. */
  28693. getType() {
  28694. return this.nodeUniform.type;
  28695. }
  28696. }
  28697. /**
  28698. * A special form of Color uniform binding type.
  28699. * It's value is managed by a node object.
  28700. *
  28701. * @private
  28702. * @augments ColorUniform
  28703. */
  28704. class ColorNodeUniform extends ColorUniform {
  28705. /**
  28706. * Constructs a new node-based Color uniform.
  28707. *
  28708. * @param {NodeUniform} nodeUniform - The node uniform.
  28709. */
  28710. constructor( nodeUniform ) {
  28711. super( nodeUniform.name, nodeUniform.value );
  28712. /**
  28713. * The node uniform.
  28714. *
  28715. * @type {NodeUniform}
  28716. */
  28717. this.nodeUniform = nodeUniform;
  28718. }
  28719. /**
  28720. * Overwritten to return the value of the node uniform.
  28721. *
  28722. * @return {Color} The value.
  28723. */
  28724. getValue() {
  28725. return this.nodeUniform.value;
  28726. }
  28727. /**
  28728. * Returns the node uniform data type.
  28729. *
  28730. * @return {String} The data type.
  28731. */
  28732. getType() {
  28733. return this.nodeUniform.type;
  28734. }
  28735. }
  28736. /**
  28737. * A special form of Matrix3 uniform binding type.
  28738. * It's value is managed by a node object.
  28739. *
  28740. * @private
  28741. * @augments Matrix3Uniform
  28742. */
  28743. class Matrix3NodeUniform extends Matrix3Uniform {
  28744. /**
  28745. * Constructs a new node-based Matrix3 uniform.
  28746. *
  28747. * @param {NodeUniform} nodeUniform - The node uniform.
  28748. */
  28749. constructor( nodeUniform ) {
  28750. super( nodeUniform.name, nodeUniform.value );
  28751. /**
  28752. * The node uniform.
  28753. *
  28754. * @type {NodeUniform}
  28755. */
  28756. this.nodeUniform = nodeUniform;
  28757. }
  28758. /**
  28759. * Overwritten to return the value of the node uniform.
  28760. *
  28761. * @return {Matrix3} The value.
  28762. */
  28763. getValue() {
  28764. return this.nodeUniform.value;
  28765. }
  28766. /**
  28767. * Returns the node uniform data type.
  28768. *
  28769. * @return {String} The data type.
  28770. */
  28771. getType() {
  28772. return this.nodeUniform.type;
  28773. }
  28774. }
  28775. /**
  28776. * A special form of Matrix4 uniform binding type.
  28777. * It's value is managed by a node object.
  28778. *
  28779. * @private
  28780. * @augments Matrix4Uniform
  28781. */
  28782. class Matrix4NodeUniform extends Matrix4Uniform {
  28783. /**
  28784. * Constructs a new node-based Matrix4 uniform.
  28785. *
  28786. * @param {NodeUniform} nodeUniform - The node uniform.
  28787. */
  28788. constructor( nodeUniform ) {
  28789. super( nodeUniform.name, nodeUniform.value );
  28790. /**
  28791. * The node uniform.
  28792. *
  28793. * @type {NodeUniform}
  28794. */
  28795. this.nodeUniform = nodeUniform;
  28796. }
  28797. /**
  28798. * Overwritten to return the value of the node uniform.
  28799. *
  28800. * @return {Matrix4} The value.
  28801. */
  28802. getValue() {
  28803. return this.nodeUniform.value;
  28804. }
  28805. /**
  28806. * Returns the node uniform data type.
  28807. *
  28808. * @return {String} The data type.
  28809. */
  28810. getType() {
  28811. return this.nodeUniform.type;
  28812. }
  28813. }
  28814. const LOD_MIN = 4;
  28815. // The standard deviations (radians) associated with the extra mips. These are
  28816. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28817. // geometric shadowing function. These sigma values squared must match the
  28818. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28819. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  28820. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28821. // samples and exit early, but not recompile the shader.
  28822. const MAX_SAMPLES = 20;
  28823. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  28824. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  28825. const _clearColor = /*@__PURE__*/ new Color();
  28826. let _oldTarget = null;
  28827. let _oldActiveCubeFace = 0;
  28828. let _oldActiveMipmapLevel = 0;
  28829. // Golden Ratio
  28830. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  28831. const INV_PHI = 1 / PHI;
  28832. // Vertices of a dodecahedron (except the opposites, which represent the
  28833. // same axis), used as axis directions evenly spread on a sphere.
  28834. const _axisDirections = [
  28835. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  28836. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  28837. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  28838. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  28839. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  28840. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  28841. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  28842. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  28843. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  28844. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  28845. ];
  28846. //
  28847. // WebGPU Face indices
  28848. const _faceLib = [
  28849. 3, 1, 5,
  28850. 0, 4, 2
  28851. ];
  28852. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  28853. const outputDirection = vec3( direction.x, direction.y, direction.z );
  28854. /**
  28855. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28856. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28857. * blur to be quickly accessed based on material roughness. It is packed into a
  28858. * special CubeUV format that allows us to perform custom interpolation so that
  28859. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28860. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28861. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28862. * higher roughness levels. In this way we maintain resolution to smoothly
  28863. * interpolate diffuse lighting while limiting sampling computation.
  28864. *
  28865. * Paper: Fast, Accurate Image-Based Lighting
  28866. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  28867. */
  28868. class PMREMGenerator {
  28869. constructor( renderer ) {
  28870. this._renderer = renderer;
  28871. this._pingPongRenderTarget = null;
  28872. this._lodMax = 0;
  28873. this._cubeSize = 0;
  28874. this._lodPlanes = [];
  28875. this._sizeLods = [];
  28876. this._sigmas = [];
  28877. this._lodMeshes = [];
  28878. this._blurMaterial = null;
  28879. this._cubemapMaterial = null;
  28880. this._equirectMaterial = null;
  28881. this._backgroundBox = null;
  28882. }
  28883. get _hasInitialized() {
  28884. return this._renderer.hasInitialized();
  28885. }
  28886. /**
  28887. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28888. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28889. * in radians to be applied to the scene before PMREM generation. Optional near
  28890. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28891. * is placed at the origin).
  28892. *
  28893. * @param {Scene} scene - The scene to be captured.
  28894. * @param {Number} [sigma=0] - The blur radius in radians.
  28895. * @param {Number} [near=0.1] - The near plane distance.
  28896. * @param {Number} [far=100] - The far plane distance.
  28897. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28898. * @return {RenderTarget} The resulting PMREM.
  28899. * @see fromSceneAsync
  28900. */
  28901. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  28902. this._setSize( 256 );
  28903. if ( this._hasInitialized === false ) {
  28904. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  28905. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28906. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  28907. return cubeUVRenderTarget;
  28908. }
  28909. _oldTarget = this._renderer.getRenderTarget();
  28910. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  28911. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  28912. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28913. cubeUVRenderTarget.depthBuffer = true;
  28914. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  28915. if ( sigma > 0 ) {
  28916. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  28917. }
  28918. this._applyPMREM( cubeUVRenderTarget );
  28919. this._cleanup( cubeUVRenderTarget );
  28920. return cubeUVRenderTarget;
  28921. }
  28922. /**
  28923. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28924. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28925. * in radians to be applied to the scene before PMREM generation. Optional near
  28926. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28927. * is placed at the origin).
  28928. *
  28929. * @param {Scene} scene - The scene to be captured.
  28930. * @param {Number} [sigma=0] - The blur radius in radians.
  28931. * @param {Number} [near=0.1] - The near plane distance.
  28932. * @param {Number} [far=100] - The far plane distance.
  28933. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28934. * @return {Promise<RenderTarget>} The resulting PMREM.
  28935. * @see fromScene
  28936. */
  28937. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  28938. if ( this._hasInitialized === false ) await this._renderer.init();
  28939. return this.fromScene( scene, sigma, near, far, renderTarget );
  28940. }
  28941. /**
  28942. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28943. * or HDR. The ideal input image size is 1k (1024 x 512),
  28944. * as this matches best with the 256 x 256 cubemap output.
  28945. *
  28946. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  28947. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28948. * @return {RenderTarget} The resulting PMREM.
  28949. * @see fromEquirectangularAsync
  28950. */
  28951. fromEquirectangular( equirectangular, renderTarget = null ) {
  28952. if ( this._hasInitialized === false ) {
  28953. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  28954. this._setSizeFromTexture( equirectangular );
  28955. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28956. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  28957. return cubeUVRenderTarget;
  28958. }
  28959. return this._fromTexture( equirectangular, renderTarget );
  28960. }
  28961. /**
  28962. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28963. * or HDR. The ideal input image size is 1k (1024 x 512),
  28964. * as this matches best with the 256 x 256 cubemap output.
  28965. *
  28966. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  28967. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28968. * @return {Promise<RenderTarget>} The resulting PMREM.
  28969. * @see fromEquirectangular
  28970. */
  28971. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  28972. if ( this._hasInitialized === false ) await this._renderer.init();
  28973. return this._fromTexture( equirectangular, renderTarget );
  28974. }
  28975. /**
  28976. * Generates a PMREM from an cubemap texture, which can be either LDR
  28977. * or HDR. The ideal input cube size is 256 x 256,
  28978. * as this matches best with the 256 x 256 cubemap output.
  28979. *
  28980. * @param {Texture} cubemap - The cubemap texture to be converted.
  28981. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28982. * @return {RenderTarget} The resulting PMREM.
  28983. * @see fromCubemapAsync
  28984. */
  28985. fromCubemap( cubemap, renderTarget = null ) {
  28986. if ( this._hasInitialized === false ) {
  28987. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  28988. this._setSizeFromTexture( cubemap );
  28989. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28990. this.fromCubemapAsync( cubemap, renderTarget );
  28991. return cubeUVRenderTarget;
  28992. }
  28993. return this._fromTexture( cubemap, renderTarget );
  28994. }
  28995. /**
  28996. * Generates a PMREM from an cubemap texture, which can be either LDR
  28997. * or HDR. The ideal input cube size is 256 x 256,
  28998. * with the 256 x 256 cubemap output.
  28999. *
  29000. * @param {Texture} cubemap - The cubemap texture to be converted.
  29001. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29002. * @return {Promise<RenderTarget>} The resulting PMREM.
  29003. * @see fromCubemap
  29004. */
  29005. async fromCubemapAsync( cubemap, renderTarget = null ) {
  29006. if ( this._hasInitialized === false ) await this._renderer.init();
  29007. return this._fromTexture( cubemap, renderTarget );
  29008. }
  29009. /**
  29010. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  29011. * your texture's network fetch for increased concurrency.
  29012. *
  29013. * @returns {Promise}
  29014. */
  29015. async compileCubemapShader() {
  29016. if ( this._cubemapMaterial === null ) {
  29017. this._cubemapMaterial = _getCubemapMaterial();
  29018. await this._compileMaterial( this._cubemapMaterial );
  29019. }
  29020. }
  29021. /**
  29022. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  29023. * your texture's network fetch for increased concurrency.
  29024. *
  29025. * @returns {Promise}
  29026. */
  29027. async compileEquirectangularShader() {
  29028. if ( this._equirectMaterial === null ) {
  29029. this._equirectMaterial = _getEquirectMaterial();
  29030. await this._compileMaterial( this._equirectMaterial );
  29031. }
  29032. }
  29033. /**
  29034. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  29035. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  29036. * one of them will cause any others to also become unusable.
  29037. */
  29038. dispose() {
  29039. this._dispose();
  29040. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  29041. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  29042. if ( this._backgroundBox !== null ) {
  29043. this._backgroundBox.geometry.dispose();
  29044. this._backgroundBox.material.dispose();
  29045. }
  29046. }
  29047. // private interface
  29048. _setSizeFromTexture( texture ) {
  29049. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  29050. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  29051. } else { // Equirectangular
  29052. this._setSize( texture.image.width / 4 );
  29053. }
  29054. }
  29055. _setSize( cubeSize ) {
  29056. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  29057. this._cubeSize = Math.pow( 2, this._lodMax );
  29058. }
  29059. _dispose() {
  29060. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  29061. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  29062. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  29063. this._lodPlanes[ i ].dispose();
  29064. }
  29065. }
  29066. _cleanup( outputTarget ) {
  29067. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  29068. outputTarget.scissorTest = false;
  29069. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  29070. }
  29071. _fromTexture( texture, renderTarget ) {
  29072. this._setSizeFromTexture( texture );
  29073. _oldTarget = this._renderer.getRenderTarget();
  29074. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29075. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29076. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29077. this._textureToCubeUV( texture, cubeUVRenderTarget );
  29078. this._applyPMREM( cubeUVRenderTarget );
  29079. this._cleanup( cubeUVRenderTarget );
  29080. return cubeUVRenderTarget;
  29081. }
  29082. _allocateTargets() {
  29083. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  29084. const height = 4 * this._cubeSize;
  29085. const params = {
  29086. magFilter: LinearFilter,
  29087. minFilter: LinearFilter,
  29088. generateMipmaps: false,
  29089. type: HalfFloatType,
  29090. format: RGBAFormat,
  29091. colorSpace: LinearSRGBColorSpace,
  29092. //depthBuffer: false
  29093. };
  29094. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  29095. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  29096. if ( this._pingPongRenderTarget !== null ) {
  29097. this._dispose();
  29098. }
  29099. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  29100. const { _lodMax } = this;
  29101. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  29102. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  29103. }
  29104. return cubeUVRenderTarget;
  29105. }
  29106. async _compileMaterial( material ) {
  29107. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  29108. await this._renderer.compile( tmpMesh, _flatCamera );
  29109. }
  29110. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  29111. const cubeCamera = _cubeCamera;
  29112. cubeCamera.near = near;
  29113. cubeCamera.far = far;
  29114. // px, py, pz, nx, ny, nz
  29115. const upSign = [ 1, 1, 1, 1, - 1, 1 ];
  29116. const forwardSign = [ 1, - 1, 1, - 1, 1, - 1 ];
  29117. const renderer = this._renderer;
  29118. const originalAutoClear = renderer.autoClear;
  29119. renderer.getClearColor( _clearColor );
  29120. renderer.autoClear = false;
  29121. let backgroundBox = this._backgroundBox;
  29122. if ( backgroundBox === null ) {
  29123. const backgroundMaterial = new MeshBasicMaterial( {
  29124. name: 'PMREM.Background',
  29125. side: BackSide,
  29126. depthWrite: false,
  29127. depthTest: false
  29128. } );
  29129. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  29130. }
  29131. let useSolidColor = false;
  29132. const background = scene.background;
  29133. if ( background ) {
  29134. if ( background.isColor ) {
  29135. backgroundBox.material.color.copy( background );
  29136. scene.background = null;
  29137. useSolidColor = true;
  29138. }
  29139. } else {
  29140. backgroundBox.material.color.copy( _clearColor );
  29141. useSolidColor = true;
  29142. }
  29143. renderer.setRenderTarget( cubeUVRenderTarget );
  29144. renderer.clear();
  29145. if ( useSolidColor ) {
  29146. renderer.render( backgroundBox, cubeCamera );
  29147. }
  29148. for ( let i = 0; i < 6; i ++ ) {
  29149. const col = i % 3;
  29150. if ( col === 0 ) {
  29151. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29152. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  29153. } else if ( col === 1 ) {
  29154. cubeCamera.up.set( 0, 0, upSign[ i ] );
  29155. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  29156. } else {
  29157. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29158. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  29159. }
  29160. const size = this._cubeSize;
  29161. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  29162. renderer.render( scene, cubeCamera );
  29163. }
  29164. renderer.autoClear = originalAutoClear;
  29165. scene.background = background;
  29166. }
  29167. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  29168. const renderer = this._renderer;
  29169. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  29170. if ( isCubeTexture ) {
  29171. if ( this._cubemapMaterial === null ) {
  29172. this._cubemapMaterial = _getCubemapMaterial( texture );
  29173. }
  29174. } else {
  29175. if ( this._equirectMaterial === null ) {
  29176. this._equirectMaterial = _getEquirectMaterial( texture );
  29177. }
  29178. }
  29179. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  29180. material.fragmentNode.value = texture;
  29181. const mesh = this._lodMeshes[ 0 ];
  29182. mesh.material = material;
  29183. const size = this._cubeSize;
  29184. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  29185. renderer.setRenderTarget( cubeUVRenderTarget );
  29186. renderer.render( mesh, _flatCamera );
  29187. }
  29188. _applyPMREM( cubeUVRenderTarget ) {
  29189. const renderer = this._renderer;
  29190. const autoClear = renderer.autoClear;
  29191. renderer.autoClear = false;
  29192. const n = this._lodPlanes.length;
  29193. for ( let i = 1; i < n; i ++ ) {
  29194. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  29195. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  29196. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  29197. }
  29198. renderer.autoClear = autoClear;
  29199. }
  29200. /**
  29201. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29202. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29203. * the blur latitudinally (around the poles), and then longitudinally (towards
  29204. * the poles) to approximate the orthogonally-separable blur. It is least
  29205. * accurate at the poles, but still does a decent job.
  29206. *
  29207. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  29208. * @param {Number} lodIn - The input level-of-detail.
  29209. * @param {Number} lodOut - The output level-of-detail.
  29210. * @param {Number} sigma - The blur radius in radians.
  29211. * @param {Vector3} [poleAxis] - The pole axis.
  29212. */
  29213. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  29214. const pingPongRenderTarget = this._pingPongRenderTarget;
  29215. this._halfBlur(
  29216. cubeUVRenderTarget,
  29217. pingPongRenderTarget,
  29218. lodIn,
  29219. lodOut,
  29220. sigma,
  29221. 'latitudinal',
  29222. poleAxis );
  29223. this._halfBlur(
  29224. pingPongRenderTarget,
  29225. cubeUVRenderTarget,
  29226. lodOut,
  29227. lodOut,
  29228. sigma,
  29229. 'longitudinal',
  29230. poleAxis );
  29231. }
  29232. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  29233. const renderer = this._renderer;
  29234. const blurMaterial = this._blurMaterial;
  29235. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  29236. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  29237. }
  29238. // Number of standard deviations at which to cut off the discrete approximation.
  29239. const STANDARD_DEVIATIONS = 3;
  29240. const blurMesh = this._lodMeshes[ lodOut ];
  29241. blurMesh.material = blurMaterial;
  29242. const blurUniforms = blurMaterial.uniforms;
  29243. const pixels = this._sizeLods[ lodIn ] - 1;
  29244. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  29245. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29246. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  29247. if ( samples > MAX_SAMPLES ) {
  29248. console.warn( `sigmaRadians, ${
  29249. sigmaRadians}, is too large and will clip, as it requested ${
  29250. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  29251. }
  29252. const weights = [];
  29253. let sum = 0;
  29254. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  29255. const x = i / sigmaPixels;
  29256. const weight = Math.exp( - x * x / 2 );
  29257. weights.push( weight );
  29258. if ( i === 0 ) {
  29259. sum += weight;
  29260. } else if ( i < samples ) {
  29261. sum += 2 * weight;
  29262. }
  29263. }
  29264. for ( let i = 0; i < weights.length; i ++ ) {
  29265. weights[ i ] = weights[ i ] / sum;
  29266. }
  29267. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  29268. blurUniforms.envMap.value = targetIn.texture;
  29269. blurUniforms.samples.value = samples;
  29270. blurUniforms.weights.array = weights;
  29271. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  29272. if ( poleAxis ) {
  29273. blurUniforms.poleAxis.value = poleAxis;
  29274. }
  29275. const { _lodMax } = this;
  29276. blurUniforms.dTheta.value = radiansPerPixel;
  29277. blurUniforms.mipInt.value = _lodMax - lodIn;
  29278. const outputSize = this._sizeLods[ lodOut ];
  29279. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  29280. const y = 4 * ( this._cubeSize - outputSize );
  29281. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  29282. renderer.setRenderTarget( targetOut );
  29283. renderer.render( blurMesh, _flatCamera );
  29284. }
  29285. }
  29286. function _createPlanes( lodMax ) {
  29287. const lodPlanes = [];
  29288. const sizeLods = [];
  29289. const sigmas = [];
  29290. const lodMeshes = [];
  29291. let lod = lodMax;
  29292. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29293. for ( let i = 0; i < totalLods; i ++ ) {
  29294. const sizeLod = Math.pow( 2, lod );
  29295. sizeLods.push( sizeLod );
  29296. let sigma = 1.0 / sizeLod;
  29297. if ( i > lodMax - LOD_MIN ) {
  29298. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  29299. } else if ( i === 0 ) {
  29300. sigma = 0;
  29301. }
  29302. sigmas.push( sigma );
  29303. const texelSize = 1.0 / ( sizeLod - 2 );
  29304. const min = - texelSize;
  29305. const max = 1 + texelSize;
  29306. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29307. const cubeFaces = 6;
  29308. const vertices = 6;
  29309. const positionSize = 3;
  29310. const uvSize = 2;
  29311. const faceIndexSize = 1;
  29312. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29313. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29314. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29315. for ( let face = 0; face < cubeFaces; face ++ ) {
  29316. const x = ( face % 3 ) * 2 / 3 - 1;
  29317. const y = face > 2 ? 0 : - 1;
  29318. const coordinates = [
  29319. x, y, 0,
  29320. x + 2 / 3, y, 0,
  29321. x + 2 / 3, y + 1, 0,
  29322. x, y, 0,
  29323. x + 2 / 3, y + 1, 0,
  29324. x, y + 1, 0
  29325. ];
  29326. const faceIdx = _faceLib[ face ];
  29327. position.set( coordinates, positionSize * vertices * faceIdx );
  29328. uv.set( uv1, uvSize * vertices * faceIdx );
  29329. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  29330. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  29331. }
  29332. const planes = new BufferGeometry();
  29333. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29334. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29335. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29336. lodPlanes.push( planes );
  29337. lodMeshes.push( new Mesh( planes, null ) );
  29338. if ( lod > LOD_MIN ) {
  29339. lod --;
  29340. }
  29341. }
  29342. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  29343. }
  29344. function _createRenderTarget( width, height, params ) {
  29345. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  29346. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29347. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29348. cubeUVRenderTarget.texture.isPMREMTexture = true;
  29349. cubeUVRenderTarget.scissorTest = true;
  29350. return cubeUVRenderTarget;
  29351. }
  29352. function _setViewport( target, x, y, width, height ) {
  29353. target.viewport.set( x, y, width, height );
  29354. target.scissor.set( x, y, width, height );
  29355. }
  29356. function _getMaterial( type ) {
  29357. const material = new NodeMaterial();
  29358. material.depthTest = false;
  29359. material.depthWrite = false;
  29360. material.blending = NoBlending;
  29361. material.name = `PMREM_${ type }`;
  29362. return material;
  29363. }
  29364. function _getBlurShader( lodMax, width, height ) {
  29365. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  29366. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  29367. const dTheta = uniform( 0 );
  29368. const n = float( MAX_SAMPLES );
  29369. const latitudinal = uniform( 0 ); // false, bool
  29370. const samples = uniform( 1 ); // int
  29371. const envMap = texture( null );
  29372. const mipInt = uniform( 0 ); // int
  29373. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  29374. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  29375. const CUBEUV_MAX_MIP = float( lodMax );
  29376. const materialUniforms = {
  29377. n,
  29378. latitudinal,
  29379. weights,
  29380. poleAxis,
  29381. outputDirection,
  29382. dTheta,
  29383. samples,
  29384. envMap,
  29385. mipInt,
  29386. CUBEUV_TEXEL_WIDTH,
  29387. CUBEUV_TEXEL_HEIGHT,
  29388. CUBEUV_MAX_MIP
  29389. };
  29390. const material = _getMaterial( 'blur' );
  29391. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  29392. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  29393. return material;
  29394. }
  29395. function _getCubemapMaterial( envTexture ) {
  29396. const material = _getMaterial( 'cubemap' );
  29397. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  29398. return material;
  29399. }
  29400. function _getEquirectMaterial( envTexture ) {
  29401. const material = _getMaterial( 'equirect' );
  29402. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  29403. return material;
  29404. }
  29405. const rendererCache = new WeakMap();
  29406. const typeFromArray = new Map( [
  29407. [ Int8Array, 'int' ],
  29408. [ Int16Array, 'int' ],
  29409. [ Int32Array, 'int' ],
  29410. [ Uint8Array, 'uint' ],
  29411. [ Uint16Array, 'uint' ],
  29412. [ Uint32Array, 'uint' ],
  29413. [ Float32Array, 'float' ]
  29414. ] );
  29415. const toFloat = ( value ) => {
  29416. if ( /e/g.test( value ) ) {
  29417. return String( value ).replace( /\+/g, '' );
  29418. } else {
  29419. value = Number( value );
  29420. return value + ( value % 1 ? '' : '.0' );
  29421. }
  29422. };
  29423. /**
  29424. * Base class for builders which generate a shader program based
  29425. * on a 3D object and its node material definition.
  29426. */
  29427. class NodeBuilder {
  29428. /**
  29429. * Constructs a new node builder.
  29430. *
  29431. * @param {Object3D} object - The 3D object.
  29432. * @param {Renderer} renderer - The current renderer.
  29433. * @param {NodeParser} parser - A reference to a node parser.
  29434. */
  29435. constructor( object, renderer, parser ) {
  29436. /**
  29437. * The 3D object.
  29438. *
  29439. * @type {Object3D}
  29440. */
  29441. this.object = object;
  29442. /**
  29443. * The material of the 3D object.
  29444. *
  29445. * @type {Material?}
  29446. */
  29447. this.material = ( object && object.material ) || null;
  29448. /**
  29449. * The geometry of the 3D object.
  29450. *
  29451. * @type {BufferGeometry?}
  29452. */
  29453. this.geometry = ( object && object.geometry ) || null;
  29454. /**
  29455. * The current renderer.
  29456. *
  29457. * @type {Renderer}
  29458. */
  29459. this.renderer = renderer;
  29460. /**
  29461. * A reference to a node parser.
  29462. *
  29463. * @type {NodeParser}
  29464. */
  29465. this.parser = parser;
  29466. /**
  29467. * The scene the 3D object belongs to.
  29468. *
  29469. * @type {Scene?}
  29470. * @default null
  29471. */
  29472. this.scene = null;
  29473. /**
  29474. * The camera the 3D object is rendered with.
  29475. *
  29476. * @type {Camera?}
  29477. * @default null
  29478. */
  29479. this.camera = null;
  29480. /**
  29481. * A list of all nodes the builder is processing
  29482. * for this 3D object.
  29483. *
  29484. * @type {Array<Node>}
  29485. */
  29486. this.nodes = [];
  29487. /**
  29488. * A list of all sequential nodes.
  29489. *
  29490. * @type {Array<Node>}
  29491. */
  29492. this.sequentialNodes = [];
  29493. /**
  29494. * A list of all nodes which {@link Node#update} method should be executed.
  29495. *
  29496. * @type {Array<Node>}
  29497. */
  29498. this.updateNodes = [];
  29499. /**
  29500. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  29501. *
  29502. * @type {Array<Node>}
  29503. */
  29504. this.updateBeforeNodes = [];
  29505. /**
  29506. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  29507. *
  29508. * @type {Array<Node>}
  29509. */
  29510. this.updateAfterNodes = [];
  29511. /**
  29512. * A dictionary that assigns each node to a unique hash.
  29513. *
  29514. * @type {Object<Number,Node>}
  29515. */
  29516. this.hashNodes = {};
  29517. /**
  29518. * A reference to a node material observer.
  29519. *
  29520. * @type {NodeMaterialObserver?}
  29521. * @default null
  29522. */
  29523. this.monitor = null;
  29524. /**
  29525. * A reference to the current lights node.
  29526. *
  29527. * @type {LightsNode?}
  29528. * @default null
  29529. */
  29530. this.lightsNode = null;
  29531. /**
  29532. * A reference to the current environment node.
  29533. *
  29534. * @type {Node?}
  29535. * @default null
  29536. */
  29537. this.environmentNode = null;
  29538. /**
  29539. * A reference to the current fog node.
  29540. *
  29541. * @type {FogNode?}
  29542. * @default null
  29543. */
  29544. this.fogNode = null;
  29545. /**
  29546. * The current clipping context.
  29547. *
  29548. * @type {ClippingContext?}
  29549. */
  29550. this.clippingContext = null;
  29551. /**
  29552. * The generated vertex shader.
  29553. *
  29554. * @type {String?}
  29555. */
  29556. this.vertexShader = null;
  29557. /**
  29558. * The generated fragment shader.
  29559. *
  29560. * @type {String?}
  29561. */
  29562. this.fragmentShader = null;
  29563. /**
  29564. * The generated compute shader.
  29565. *
  29566. * @type {String?}
  29567. */
  29568. this.computeShader = null;
  29569. /**
  29570. * Nodes used in the primary flow of code generation.
  29571. *
  29572. * @type {Object<String,Array<Node>>}
  29573. */
  29574. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  29575. /**
  29576. * Nodes code from `.flowNodes`.
  29577. *
  29578. * @type {Object<String,String>}
  29579. */
  29580. this.flowCode = { vertex: '', fragment: '', compute: '' };
  29581. /**
  29582. * This dictionary holds the node uniforms of the builder.
  29583. * The uniforms are maintained in an array for each shader stage.
  29584. *
  29585. * @type {Object}
  29586. */
  29587. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  29588. /**
  29589. * This dictionary holds the output structs of the builder.
  29590. * The structs are maintained in an array for each shader stage.
  29591. *
  29592. * @type {Object}
  29593. */
  29594. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  29595. /**
  29596. * This dictionary holds the bindings for each shader stage.
  29597. *
  29598. * @type {Object}
  29599. */
  29600. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  29601. /**
  29602. * This dictionary maintains the binding indices per bind group.
  29603. *
  29604. * @type {Object}
  29605. */
  29606. this.bindingsIndexes = {};
  29607. /**
  29608. * Reference to the array of bind groups.
  29609. *
  29610. * @type {Array<BindGroup>?}
  29611. */
  29612. this.bindGroups = null;
  29613. /**
  29614. * This array holds the node attributes of this builder
  29615. * created via {@link AttributeNode}.
  29616. *
  29617. * @type {Array<NodeAttribute>}
  29618. */
  29619. this.attributes = [];
  29620. /**
  29621. * This array holds the node attributes of this builder
  29622. * created via {@link BufferAttributeNode}.
  29623. *
  29624. * @type {Array<NodeAttribute>}
  29625. */
  29626. this.bufferAttributes = [];
  29627. /**
  29628. * This array holds the node varyings of this builder.
  29629. *
  29630. * @type {Array<NodeVarying>}
  29631. */
  29632. this.varyings = [];
  29633. /**
  29634. * This dictionary holds the (native) node codes of this builder.
  29635. * The codes are maintained in an array for each shader stage.
  29636. *
  29637. * @type {Object<String,Array<NodeCode>>}
  29638. */
  29639. this.codes = {};
  29640. /**
  29641. * This dictionary holds the node variables of this builder.
  29642. * The variables are maintained in an array for each shader stage.
  29643. *
  29644. * @type {Object<String,Array<NodeVar>>}
  29645. */
  29646. this.vars = {};
  29647. /**
  29648. * Current code flow.
  29649. * All code generated in this stack will be stored in `.flow`.
  29650. *
  29651. * @type {{code: String}}
  29652. */
  29653. this.flow = { code: '' };
  29654. /**
  29655. * A chain of nodes.
  29656. * Used to check recursive calls in node-graph.
  29657. *
  29658. * @type {Array<Node>}
  29659. */
  29660. this.chaining = [];
  29661. /**
  29662. * The current stack.
  29663. * This reflects the current process in the code block hierarchy,
  29664. * it is useful to know if the current process is inside a conditional for example.
  29665. *
  29666. * @type {StackNode}
  29667. */
  29668. this.stack = stack();
  29669. /**
  29670. * List of stack nodes.
  29671. * The current stack hierarchy is stored in an array.
  29672. *
  29673. * @type {Array<StackNode>}
  29674. */
  29675. this.stacks = [];
  29676. /**
  29677. * A tab value. Used for shader string generation.
  29678. *
  29679. * @type {String}
  29680. * @default '\t'
  29681. */
  29682. this.tab = '\t';
  29683. /**
  29684. * Reference to the current function node.
  29685. *
  29686. * @type {FunctionNode?}
  29687. * @default null
  29688. */
  29689. this.currentFunctionNode = null;
  29690. /**
  29691. * The builder's context.
  29692. *
  29693. * @type {Object}
  29694. */
  29695. this.context = {
  29696. material: this.material
  29697. };
  29698. /**
  29699. * The builder's cache.
  29700. *
  29701. * @type {NodeCache}
  29702. */
  29703. this.cache = new NodeCache();
  29704. /**
  29705. * Since the {@link NodeBuilder#cache} might be temporarily
  29706. * overwritten by other caches, this member retains the reference
  29707. * to the builder's own cache.
  29708. *
  29709. * @type {NodeCache}
  29710. * @default this.cache
  29711. */
  29712. this.globalCache = this.cache;
  29713. this.flowsData = new WeakMap();
  29714. /**
  29715. * The current shader stage.
  29716. *
  29717. * @type {('vertex'|'fragment'|'compute'|'any')?}
  29718. */
  29719. this.shaderStage = null;
  29720. /**
  29721. * The current build stage.
  29722. *
  29723. * @type {('setup'|'analyze'|'generate')?}
  29724. */
  29725. this.buildStage = null;
  29726. /**
  29727. * Whether comparison in shader code are generated with methods or not.
  29728. *
  29729. * @type {Boolean}
  29730. * @default false
  29731. */
  29732. this.useComparisonMethod = false;
  29733. }
  29734. /**
  29735. * Returns the bind groups of the current renderer.
  29736. *
  29737. * @return {ChainMap} The cache.
  29738. */
  29739. getBindGroupsCache() {
  29740. let bindGroupsCache = rendererCache.get( this.renderer );
  29741. if ( bindGroupsCache === undefined ) {
  29742. bindGroupsCache = new ChainMap();
  29743. rendererCache.set( this.renderer, bindGroupsCache );
  29744. }
  29745. return bindGroupsCache;
  29746. }
  29747. /**
  29748. * Factory method for creating an instance of {@link RenderTarget} with the given
  29749. * dimensions and options.
  29750. *
  29751. * @param {Number} width - The width of the render target.
  29752. * @param {Number} height - The height of the render target.
  29753. * @param {Object} options - The options of the render target.
  29754. * @return {RenderTarget} The render target.
  29755. */
  29756. createRenderTarget( width, height, options ) {
  29757. return new RenderTarget( width, height, options );
  29758. }
  29759. /**
  29760. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  29761. * dimensions and options.
  29762. *
  29763. * @param {Number} size - The size of the cube render target.
  29764. * @param {Object} options - The options of the cube render target.
  29765. * @return {CubeRenderTarget} The cube render target.
  29766. */
  29767. createCubeRenderTarget( size, options ) {
  29768. return new CubeRenderTarget( size, options );
  29769. }
  29770. /**
  29771. * Factory method for creating an instance of {@link PMREMGenerator}.
  29772. *
  29773. * @return {PMREMGenerator} The PMREM generator.
  29774. */
  29775. createPMREMGenerator() {
  29776. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  29777. return new PMREMGenerator( this.renderer );
  29778. }
  29779. /**
  29780. * Whether the given node is included in the internal array of nodes or not.
  29781. *
  29782. * @param {Node} node - The node to test.
  29783. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  29784. */
  29785. includes( node ) {
  29786. return this.nodes.includes( node );
  29787. }
  29788. /**
  29789. * Returns the output struct name which is required by
  29790. * {@link module:OutputStructNode}.
  29791. *
  29792. * @abstract
  29793. * @return {String} The name of the output struct.
  29794. */
  29795. getOutputStructName() {}
  29796. /**
  29797. * Returns a bind group for the given group name and binding.
  29798. *
  29799. * @private
  29800. * @param {String} groupName - The group name.
  29801. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  29802. * @return {BindGroup} The bind group
  29803. */
  29804. _getBindGroup( groupName, bindings ) {
  29805. const bindGroupsCache = this.getBindGroupsCache();
  29806. //
  29807. const bindingsArray = [];
  29808. let sharedGroup = true;
  29809. for ( const binding of bindings ) {
  29810. bindingsArray.push( binding );
  29811. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  29812. }
  29813. //
  29814. let bindGroup;
  29815. if ( sharedGroup ) {
  29816. bindGroup = bindGroupsCache.get( bindingsArray );
  29817. if ( bindGroup === undefined ) {
  29818. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29819. bindGroupsCache.set( bindingsArray, bindGroup );
  29820. }
  29821. } else {
  29822. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29823. }
  29824. return bindGroup;
  29825. }
  29826. /**
  29827. * Returns an array of node uniform groups for the given group name and shader stage.
  29828. *
  29829. * @param {String} groupName - The group name.
  29830. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  29831. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  29832. */
  29833. getBindGroupArray( groupName, shaderStage ) {
  29834. const bindings = this.bindings[ shaderStage ];
  29835. let bindGroup = bindings[ groupName ];
  29836. if ( bindGroup === undefined ) {
  29837. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  29838. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  29839. }
  29840. bindings[ groupName ] = bindGroup = [];
  29841. }
  29842. return bindGroup;
  29843. }
  29844. /**
  29845. * Returns a list bindings of all shader stages separated by groups.
  29846. *
  29847. * @return {Array<BindGroup>} The list of bindings.
  29848. */
  29849. getBindings() {
  29850. let bindingsGroups = this.bindGroups;
  29851. if ( bindingsGroups === null ) {
  29852. const groups = {};
  29853. const bindings = this.bindings;
  29854. for ( const shaderStage of shaderStages ) {
  29855. for ( const groupName in bindings[ shaderStage ] ) {
  29856. const uniforms = bindings[ shaderStage ][ groupName ];
  29857. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  29858. groupUniforms.push( ...uniforms );
  29859. }
  29860. }
  29861. bindingsGroups = [];
  29862. for ( const groupName in groups ) {
  29863. const group = groups[ groupName ];
  29864. const bindingsGroup = this._getBindGroup( groupName, group );
  29865. bindingsGroups.push( bindingsGroup );
  29866. }
  29867. this.bindGroups = bindingsGroups;
  29868. }
  29869. return bindingsGroups;
  29870. }
  29871. /**
  29872. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  29873. */
  29874. sortBindingGroups() {
  29875. const bindingsGroups = this.getBindings();
  29876. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  29877. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  29878. const bindingGroup = bindingsGroups[ i ];
  29879. this.bindingsIndexes[ bindingGroup.name ].group = i;
  29880. bindingGroup.index = i;
  29881. }
  29882. }
  29883. /**
  29884. * The builder maintains each node in a hash-based dictionary.
  29885. * This method sets the given node (value) with the given hash (key) into this dictionary.
  29886. *
  29887. * @param {Node} node - The node to add.
  29888. * @param {Number} hash - The hash of the node.
  29889. */
  29890. setHashNode( node, hash ) {
  29891. this.hashNodes[ hash ] = node;
  29892. }
  29893. /**
  29894. * Adds a node to this builder.
  29895. *
  29896. * @param {Node} node - The node to add.
  29897. */
  29898. addNode( node ) {
  29899. if ( this.nodes.includes( node ) === false ) {
  29900. this.nodes.push( node );
  29901. this.setHashNode( node, node.getHash( this ) );
  29902. }
  29903. }
  29904. /**
  29905. * It is used to add Nodes that will be used as FRAME and RENDER events,
  29906. * and need to follow a certain sequence in the calls to work correctly.
  29907. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  29908. *
  29909. * @param {Node} node - The node to add.
  29910. */
  29911. addSequentialNode( node ) {
  29912. if ( this.sequentialNodes.includes( node ) === false ) {
  29913. this.sequentialNodes.push( node );
  29914. }
  29915. }
  29916. /**
  29917. * Checks the update types of nodes
  29918. */
  29919. buildUpdateNodes() {
  29920. for ( const node of this.nodes ) {
  29921. const updateType = node.getUpdateType();
  29922. if ( updateType !== NodeUpdateType.NONE ) {
  29923. this.updateNodes.push( node.getSelf() );
  29924. }
  29925. }
  29926. for ( const node of this.sequentialNodes ) {
  29927. const updateBeforeType = node.getUpdateBeforeType();
  29928. const updateAfterType = node.getUpdateAfterType();
  29929. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  29930. this.updateBeforeNodes.push( node.getSelf() );
  29931. }
  29932. if ( updateAfterType !== NodeUpdateType.NONE ) {
  29933. this.updateAfterNodes.push( node.getSelf() );
  29934. }
  29935. }
  29936. }
  29937. /**
  29938. * A reference the current node which is the
  29939. * last node in the chain of nodes.
  29940. *
  29941. * @type {Node}
  29942. */
  29943. get currentNode() {
  29944. return this.chaining[ this.chaining.length - 1 ];
  29945. }
  29946. /**
  29947. * Whether the given texture is filtered or not.
  29948. *
  29949. * @param {Texture} texture - The texture to check.
  29950. * @return {Boolean} Whether the given texture is filtered or not.
  29951. */
  29952. isFilteredTexture( texture ) {
  29953. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  29954. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  29955. }
  29956. /**
  29957. * Adds the given node to the internal node chain.
  29958. * This is used to check recursive calls in node-graph.
  29959. *
  29960. * @param {Node} node - The node to add.
  29961. */
  29962. addChain( node ) {
  29963. /*
  29964. if ( this.chaining.indexOf( node ) !== - 1 ) {
  29965. console.warn( 'Recursive node: ', node );
  29966. }
  29967. */
  29968. this.chaining.push( node );
  29969. }
  29970. /**
  29971. * Removes the given node from the internal node chain.
  29972. *
  29973. * @param {Node} node - The node to remove.
  29974. */
  29975. removeChain( node ) {
  29976. const lastChain = this.chaining.pop();
  29977. if ( lastChain !== node ) {
  29978. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  29979. }
  29980. }
  29981. /**
  29982. * Returns the native shader method name for a given generic name. E.g.
  29983. * the method name `textureDimensions` matches the WGSL name but must be
  29984. * resolved to `textureSize` in GLSL.
  29985. *
  29986. * @abstract
  29987. * @param {String} method - The method name to resolve.
  29988. * @return {String} The resolved method name.
  29989. */
  29990. getMethod( method ) {
  29991. return method;
  29992. }
  29993. /**
  29994. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  29995. *
  29996. * @param {Number} hash - The hash of the node.
  29997. * @return {Node} The found node.
  29998. */
  29999. getNodeFromHash( hash ) {
  30000. return this.hashNodes[ hash ];
  30001. }
  30002. /**
  30003. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  30004. *
  30005. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  30006. * @param {Node} node - The node to add.
  30007. * @return {Node} The node.
  30008. */
  30009. addFlow( shaderStage, node ) {
  30010. this.flowNodes[ shaderStage ].push( node );
  30011. return node;
  30012. }
  30013. /**
  30014. * Sets builder's context.
  30015. *
  30016. * @param {Object} context - The context to set.
  30017. */
  30018. setContext( context ) {
  30019. this.context = context;
  30020. }
  30021. /**
  30022. * Returns the builder's current context.
  30023. *
  30024. * @return {Object} The builder's current context.
  30025. */
  30026. getContext() {
  30027. return this.context;
  30028. }
  30029. /**
  30030. * Gets a context used in shader construction that can be shared across different materials.
  30031. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  30032. *
  30033. * @return {Object} The builder's current context without material.
  30034. */
  30035. getSharedContext() {
  30036. ({ ...this.context });
  30037. return this.context;
  30038. }
  30039. /**
  30040. * Sets builder's cache.
  30041. *
  30042. * @param {NodeCache} cache - The cache to set.
  30043. */
  30044. setCache( cache ) {
  30045. this.cache = cache;
  30046. }
  30047. /**
  30048. * Returns the builder's current cache.
  30049. *
  30050. * @return {NodeCache} The builder's current cache.
  30051. */
  30052. getCache() {
  30053. return this.cache;
  30054. }
  30055. /**
  30056. * Returns a cache for the given node.
  30057. *
  30058. * @param {Node} node - The node.
  30059. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  30060. * @return {NodeCache} The cache.
  30061. */
  30062. getCacheFromNode( node, parent = true ) {
  30063. const data = this.getDataFromNode( node );
  30064. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  30065. return data.cache;
  30066. }
  30067. /**
  30068. * Whether the requested feature is available or not.
  30069. *
  30070. * @abstract
  30071. * @param {String} name - The requested feature.
  30072. * @return {Boolean} Whether the requested feature is supported or not.
  30073. */
  30074. isAvailable( /*name*/ ) {
  30075. return false;
  30076. }
  30077. /**
  30078. * Returns the vertexIndex input variable as a native shader string.
  30079. *
  30080. * @abstract
  30081. * @return {String} The instanceIndex shader string.
  30082. */
  30083. getVertexIndex() {
  30084. console.warn( 'Abstract function.' );
  30085. }
  30086. /**
  30087. * Returns the instanceIndex input variable as a native shader string.
  30088. *
  30089. * @abstract
  30090. * @return {String} The instanceIndex shader string.
  30091. */
  30092. getInstanceIndex() {
  30093. console.warn( 'Abstract function.' );
  30094. }
  30095. /**
  30096. * Returns the drawIndex input variable as a native shader string.
  30097. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  30098. *
  30099. * @abstract
  30100. * @return {String} The drawIndex shader string.
  30101. */
  30102. getDrawIndex() {
  30103. console.warn( 'Abstract function.' );
  30104. }
  30105. /**
  30106. * Returns the frontFacing input variable as a native shader string.
  30107. *
  30108. * @abstract
  30109. * @return {String} The frontFacing shader string.
  30110. */
  30111. getFrontFacing() {
  30112. console.warn( 'Abstract function.' );
  30113. }
  30114. /**
  30115. * Returns the fragCoord input variable as a native shader string.
  30116. *
  30117. * @abstract
  30118. * @return {String} The fragCoord shader string.
  30119. */
  30120. getFragCoord() {
  30121. console.warn( 'Abstract function.' );
  30122. }
  30123. /**
  30124. * Whether to flip texture data along its vertical axis or not. WebGL needs
  30125. * this method evaluate to `true`, WebGPU to `false`.
  30126. *
  30127. * @abstract
  30128. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  30129. */
  30130. isFlipY() {
  30131. return false;
  30132. }
  30133. /**
  30134. * Calling this method increases the usage count for the given node by one.
  30135. *
  30136. * @param {Node} node - The node to increase the usage count for.
  30137. * @return {Number} The updated usage count.
  30138. */
  30139. increaseUsage( node ) {
  30140. const nodeData = this.getDataFromNode( node );
  30141. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  30142. return nodeData.usageCount;
  30143. }
  30144. /**
  30145. * Generates a texture sample shader string for the given texture data.
  30146. *
  30147. * @abstract
  30148. * @param {Texture} texture - The texture.
  30149. * @param {String} textureProperty - The texture property name.
  30150. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30151. * @return {String} The generated shader string.
  30152. */
  30153. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  30154. console.warn( 'Abstract function.' );
  30155. }
  30156. /**
  30157. * Generates a texture LOD shader string for the given texture data.
  30158. *
  30159. * @abstract
  30160. * @param {Texture} texture - The texture.
  30161. * @param {String} textureProperty - The texture property name.
  30162. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30163. * @param {String?} depthSnippet - Snippet defining the 0-based texture array index to sample.
  30164. * @param {String} levelSnippet - Snippet defining the mip level.
  30165. * @return {String} The generated shader string.
  30166. */
  30167. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  30168. console.warn( 'Abstract function.' );
  30169. }
  30170. /**
  30171. * Generates the shader string for the given type and value.
  30172. *
  30173. * @param {String} type - The type.
  30174. * @param {Any?} [value=null] - The value.
  30175. * @return {String} The generated value as a shader string.
  30176. */
  30177. generateConst( type, value = null ) {
  30178. if ( value === null ) {
  30179. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  30180. else if ( type === 'bool' ) value = false;
  30181. else if ( type === 'color' ) value = new Color();
  30182. else if ( type === 'vec2' ) value = new Vector2();
  30183. else if ( type === 'vec3' ) value = new Vector3();
  30184. else if ( type === 'vec4' ) value = new Vector4();
  30185. }
  30186. if ( type === 'float' ) return toFloat( value );
  30187. if ( type === 'int' ) return `${ Math.round( value ) }`;
  30188. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  30189. if ( type === 'bool' ) return value ? 'true' : 'false';
  30190. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  30191. const typeLength = this.getTypeLength( type );
  30192. const componentType = this.getComponentType( type );
  30193. const generateConst = value => this.generateConst( componentType, value );
  30194. if ( typeLength === 2 ) {
  30195. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  30196. } else if ( typeLength === 3 ) {
  30197. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  30198. } else if ( typeLength === 4 ) {
  30199. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  30200. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  30201. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  30202. } else if ( typeLength > 4 ) {
  30203. return `${ this.getType( type ) }()`;
  30204. }
  30205. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  30206. }
  30207. /**
  30208. * It might be necessary to convert certain data types to different ones
  30209. * so this method can be used to hide the conversion.
  30210. *
  30211. * @param {String} type - The type.
  30212. * @return {String} The updated type.
  30213. */
  30214. getType( type ) {
  30215. if ( type === 'color' ) return 'vec3';
  30216. return type;
  30217. }
  30218. /**
  30219. * Whether the given attribute name is defined in the geometry or not.
  30220. *
  30221. * @param {String} name - The attribute name.
  30222. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  30223. */
  30224. hasGeometryAttribute( name ) {
  30225. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  30226. }
  30227. /**
  30228. * Returns a node attribute for the given name and type.
  30229. *
  30230. * @param {String} name - The attribute's name.
  30231. * @param {String} type - The attribute's type.
  30232. * @return {NodeAttribute} The node attribute.
  30233. */
  30234. getAttribute( name, type ) {
  30235. const attributes = this.attributes;
  30236. // find attribute
  30237. for ( const attribute of attributes ) {
  30238. if ( attribute.name === name ) {
  30239. return attribute;
  30240. }
  30241. }
  30242. // create a new if no exist
  30243. const attribute = new NodeAttribute( name, type );
  30244. attributes.push( attribute );
  30245. return attribute;
  30246. }
  30247. /**
  30248. * Returns for the given node and shader stage the property name for the shader.
  30249. *
  30250. * @param {Node} node - The node.
  30251. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30252. * @return {String} The property name.
  30253. */
  30254. getPropertyName( node/*, shaderStage*/ ) {
  30255. return node.name;
  30256. }
  30257. /**
  30258. * Whether the given type is a vector type or not.
  30259. *
  30260. * @param {String} type - The type to check.
  30261. * @return {Boolean} Whether the given type is a vector type or not.
  30262. */
  30263. isVector( type ) {
  30264. return /vec\d/.test( type );
  30265. }
  30266. /**
  30267. * Whether the given type is a matrix type or not.
  30268. *
  30269. * @param {String} type - The type to check.
  30270. * @return {Boolean} Whether the given type is a matrix type or not.
  30271. */
  30272. isMatrix( type ) {
  30273. return /mat\d/.test( type );
  30274. }
  30275. /**
  30276. * Whether the given type is a reference type or not.
  30277. *
  30278. * @param {String} type - The type to check.
  30279. * @return {Boolean} Whether the given type is a reference type or not.
  30280. */
  30281. isReference( type ) {
  30282. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  30283. }
  30284. /**
  30285. * Checks if the given texture requires a manual conversion to the working color space.
  30286. *
  30287. * @abstract
  30288. * @param {Texture} texture - The texture to check.
  30289. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  30290. */
  30291. needsToWorkingColorSpace( /*texture*/ ) {
  30292. return false;
  30293. }
  30294. /**
  30295. * Returns the component type of a given texture.
  30296. *
  30297. * @param {Texture} texture - The texture.
  30298. * @return {String} The component type.
  30299. */
  30300. getComponentTypeFromTexture( texture ) {
  30301. const type = texture.type;
  30302. if ( texture.isDataTexture ) {
  30303. if ( type === IntType ) return 'int';
  30304. if ( type === UnsignedIntType ) return 'uint';
  30305. }
  30306. return 'float';
  30307. }
  30308. /**
  30309. * Returns the element type for a given type.
  30310. *
  30311. * @param {String} type - The type.
  30312. * @return {String} The element type.
  30313. */
  30314. getElementType( type ) {
  30315. if ( type === 'mat2' ) return 'vec2';
  30316. if ( type === 'mat3' ) return 'vec3';
  30317. if ( type === 'mat4' ) return 'vec4';
  30318. return this.getComponentType( type );
  30319. }
  30320. /**
  30321. * Returns the component type for a given type.
  30322. *
  30323. * @param {String} type - The type.
  30324. * @return {String} The component type.
  30325. */
  30326. getComponentType( type ) {
  30327. type = this.getVectorType( type );
  30328. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  30329. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  30330. if ( componentType === null ) return null;
  30331. if ( componentType[ 1 ] === 'b' ) return 'bool';
  30332. if ( componentType[ 1 ] === 'i' ) return 'int';
  30333. if ( componentType[ 1 ] === 'u' ) return 'uint';
  30334. return 'float';
  30335. }
  30336. /**
  30337. * Returns the vector type for a given type.
  30338. *
  30339. * @param {String} type - The type.
  30340. * @return {String} The vector type.
  30341. */
  30342. getVectorType( type ) {
  30343. if ( type === 'color' ) return 'vec3';
  30344. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  30345. return type;
  30346. }
  30347. /**
  30348. * Returns the data type for the given the length and component type.
  30349. *
  30350. * @param {Number} length - The length.
  30351. * @param {String} [componentType='float'] - The component type.
  30352. * @return {String} The type.
  30353. */
  30354. getTypeFromLength( length, componentType = 'float' ) {
  30355. if ( length === 1 ) return componentType;
  30356. const baseType = getTypeFromLength( length );
  30357. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  30358. return prefix + baseType;
  30359. }
  30360. /**
  30361. * Returns the type for a given typed array.
  30362. *
  30363. * @param {TypedArray} array - The typed array.
  30364. * @return {String} The type.
  30365. */
  30366. getTypeFromArray( array ) {
  30367. return typeFromArray.get( array.constructor );
  30368. }
  30369. /**
  30370. * Returns the type for a given buffer attribute.
  30371. *
  30372. * @param {BufferAttribute} attribute - The buffer attribute.
  30373. * @return {String} The type.
  30374. */
  30375. getTypeFromAttribute( attribute ) {
  30376. let dataAttribute = attribute;
  30377. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  30378. const array = dataAttribute.array;
  30379. const itemSize = attribute.itemSize;
  30380. const normalized = attribute.normalized;
  30381. let arrayType;
  30382. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  30383. arrayType = this.getTypeFromArray( array );
  30384. }
  30385. return this.getTypeFromLength( itemSize, arrayType );
  30386. }
  30387. /**
  30388. * Returns the length for the given data type.
  30389. *
  30390. * @param {String} type - The data type.
  30391. * @return {Number} The length.
  30392. */
  30393. getTypeLength( type ) {
  30394. const vecType = this.getVectorType( type );
  30395. const vecNum = /vec([2-4])/.exec( vecType );
  30396. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  30397. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  30398. if ( /mat2/.test( type ) === true ) return 4;
  30399. if ( /mat3/.test( type ) === true ) return 9;
  30400. if ( /mat4/.test( type ) === true ) return 16;
  30401. return 0;
  30402. }
  30403. /**
  30404. * Returns the vector type for a given matrix type.
  30405. *
  30406. * @param {String} type - The matrix type.
  30407. * @return {String} The vector type.
  30408. */
  30409. getVectorFromMatrix( type ) {
  30410. return type.replace( 'mat', 'vec' );
  30411. }
  30412. /**
  30413. * For a given type this method changes the component type to the
  30414. * given value. E.g. `vec4` should be changed to the new component type
  30415. * `uint` which results in `uvec4`.
  30416. *
  30417. * @param {String} type - The type.
  30418. * @param {String} newComponentType - The new component type.
  30419. * @return {String} The new type.
  30420. */
  30421. changeComponentType( type, newComponentType ) {
  30422. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  30423. }
  30424. /**
  30425. * Returns the integer type pendant for the given type.
  30426. *
  30427. * @param {String} type - The type.
  30428. * @return {String} The integer type.
  30429. */
  30430. getIntegerType( type ) {
  30431. const componentType = this.getComponentType( type );
  30432. if ( componentType === 'int' || componentType === 'uint' ) return type;
  30433. return this.changeComponentType( type, 'int' );
  30434. }
  30435. /**
  30436. * Adds a stack node to the internal stack.
  30437. *
  30438. * @return {StackNode} The added stack node.
  30439. */
  30440. addStack() {
  30441. this.stack = stack( this.stack );
  30442. this.stacks.push( getCurrentStack() || this.stack );
  30443. setCurrentStack( this.stack );
  30444. return this.stack;
  30445. }
  30446. /**
  30447. * Removes the last stack node from the internal stack.
  30448. *
  30449. * @return {StackNode} The removed stack node.
  30450. */
  30451. removeStack() {
  30452. const lastStack = this.stack;
  30453. this.stack = lastStack.parent;
  30454. setCurrentStack( this.stacks.pop() );
  30455. return lastStack;
  30456. }
  30457. /**
  30458. * The builder maintains (cached) data for each node during the building process. This method
  30459. * can be used to get these data for a specific shader stage and cache.
  30460. *
  30461. * @param {Node} node - The node to get the data for.
  30462. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30463. * @param {NodeCache?} cache - An optional cache.
  30464. * @return {Object} The node data.
  30465. */
  30466. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  30467. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  30468. let nodeData = cache.getData( node );
  30469. if ( nodeData === undefined ) {
  30470. nodeData = {};
  30471. cache.setData( node, nodeData );
  30472. }
  30473. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  30474. return nodeData[ shaderStage ];
  30475. }
  30476. /**
  30477. * Returns the properties for the given node and shader stage.
  30478. *
  30479. * @param {Node} node - The node to get the properties for.
  30480. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  30481. * @return {Object} The node properties.
  30482. */
  30483. getNodeProperties( node, shaderStage = 'any' ) {
  30484. const nodeData = this.getDataFromNode( node, shaderStage );
  30485. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  30486. }
  30487. /**
  30488. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  30489. *
  30490. * @param {BufferAttributeNode} node - The buffer attribute node.
  30491. * @param {String} type - The node type.
  30492. * @return {NodeAttribute} The node attribute.
  30493. */
  30494. getBufferAttributeFromNode( node, type ) {
  30495. const nodeData = this.getDataFromNode( node );
  30496. let bufferAttribute = nodeData.bufferAttribute;
  30497. if ( bufferAttribute === undefined ) {
  30498. const index = this.uniforms.index ++;
  30499. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  30500. this.bufferAttributes.push( bufferAttribute );
  30501. nodeData.bufferAttribute = bufferAttribute;
  30502. }
  30503. return bufferAttribute;
  30504. }
  30505. /**
  30506. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  30507. *
  30508. * @param {OutputStructNode} node - The output struct node.
  30509. * @param {Array<String>} types - The output struct types.
  30510. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30511. * @return {StructTypeNode} The struct type attribute.
  30512. */
  30513. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  30514. const nodeData = this.getDataFromNode( node, shaderStage );
  30515. let structType = nodeData.structType;
  30516. if ( structType === undefined ) {
  30517. const index = this.structs.index ++;
  30518. structType = new StructTypeNode( 'StructType' + index, types );
  30519. this.structs[ shaderStage ].push( structType );
  30520. nodeData.structType = structType;
  30521. }
  30522. return structType;
  30523. }
  30524. /**
  30525. * Returns an instance of {@link NodeUniform} for the given uniform node.
  30526. *
  30527. * @param {UniformNode} node - The uniform node.
  30528. * @param {String} type - The uniform type.
  30529. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30530. * @param {String?} name - The name of the uniform.
  30531. * @return {NodeUniform} The node uniform.
  30532. */
  30533. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  30534. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  30535. let nodeUniform = nodeData.uniform;
  30536. if ( nodeUniform === undefined ) {
  30537. const index = this.uniforms.index ++;
  30538. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  30539. this.uniforms[ shaderStage ].push( nodeUniform );
  30540. nodeData.uniform = nodeUniform;
  30541. }
  30542. return nodeUniform;
  30543. }
  30544. /**
  30545. * Returns an instance of {@link NodeVar} for the given variable node.
  30546. *
  30547. * @param {VarNode} node - The variable node.
  30548. * @param {String?} name - The variable's name.
  30549. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  30550. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30551. * @param {Boolean} [readOnly=false] - Whether the variable is read-only or not.
  30552. *
  30553. * @return {NodeVar} The node variable.
  30554. */
  30555. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  30556. const nodeData = this.getDataFromNode( node, shaderStage );
  30557. let nodeVar = nodeData.variable;
  30558. if ( nodeVar === undefined ) {
  30559. const idNS = readOnly ? '_const' : '_var';
  30560. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  30561. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  30562. if ( name === null ) {
  30563. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  30564. this.vars[ idNS ] ++;
  30565. }
  30566. nodeVar = new NodeVar( name, type, readOnly );
  30567. if ( ! readOnly ) {
  30568. vars.push( nodeVar );
  30569. }
  30570. nodeData.variable = nodeVar;
  30571. }
  30572. return nodeVar;
  30573. }
  30574. /**
  30575. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  30576. *
  30577. * @param {Node} node - The varying node.
  30578. * @return {Boolean} Returns true if deterministic.
  30579. */
  30580. isDeterministic( node ) {
  30581. if ( node.isMathNode ) {
  30582. return this.isDeterministic( node.aNode ) &&
  30583. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  30584. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  30585. } else if ( node.isOperatorNode ) {
  30586. return this.isDeterministic( node.aNode ) &&
  30587. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  30588. } else if ( node.isConstNode ) {
  30589. return true;
  30590. }
  30591. return false;
  30592. }
  30593. /**
  30594. * Returns an instance of {@link NodeVarying} for the given varying node.
  30595. *
  30596. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  30597. * @param {String?} name - The varying's name.
  30598. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  30599. * @return {NodeVar} The node varying.
  30600. */
  30601. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  30602. const nodeData = this.getDataFromNode( node, 'any' );
  30603. let nodeVarying = nodeData.varying;
  30604. if ( nodeVarying === undefined ) {
  30605. const varyings = this.varyings;
  30606. const index = varyings.length;
  30607. if ( name === null ) name = 'nodeVarying' + index;
  30608. nodeVarying = new NodeVarying( name, type );
  30609. varyings.push( nodeVarying );
  30610. nodeData.varying = nodeVarying;
  30611. }
  30612. return nodeVarying;
  30613. }
  30614. /**
  30615. * Returns an instance of {@link NodeCode} for the given code node.
  30616. *
  30617. * @param {CodeNode} node - The code node.
  30618. * @param {String} type - The node type.
  30619. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30620. * @return {NodeCode} The node code.
  30621. */
  30622. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  30623. const nodeData = this.getDataFromNode( node );
  30624. let nodeCode = nodeData.code;
  30625. if ( nodeCode === undefined ) {
  30626. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  30627. const index = codes.length;
  30628. nodeCode = new NodeCode( 'nodeCode' + index, type );
  30629. codes.push( nodeCode );
  30630. nodeData.code = nodeCode;
  30631. }
  30632. return nodeCode;
  30633. }
  30634. /**
  30635. * Adds a code flow based on the code-block hierarchy.
  30636. * This is used so that code-blocks like If,Else create their variables locally if the Node
  30637. * is only used inside one of these conditionals in the current shader stage.
  30638. *
  30639. * @param {Node} node - The node to add.
  30640. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  30641. */
  30642. addFlowCodeHierarchy( node, nodeBlock ) {
  30643. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  30644. let needsFlowCode = true;
  30645. let nodeBlockHierarchy = nodeBlock;
  30646. while ( nodeBlockHierarchy ) {
  30647. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  30648. needsFlowCode = false;
  30649. break;
  30650. }
  30651. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  30652. }
  30653. if ( needsFlowCode ) {
  30654. for ( const flowCode of flowCodes ) {
  30655. this.addLineFlowCode( flowCode );
  30656. }
  30657. }
  30658. }
  30659. /**
  30660. * Add a inline-code to the current flow code-block.
  30661. *
  30662. * @param {Node} node - The node to add.
  30663. * @param {String} code - The code to add.
  30664. * @param {Node} nodeBlock - Current ConditionalNode
  30665. */
  30666. addLineFlowCodeBlock( node, code, nodeBlock ) {
  30667. const nodeData = this.getDataFromNode( node );
  30668. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  30669. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  30670. flowCodes.push( code );
  30671. codeBlock.set( nodeBlock, true );
  30672. }
  30673. /**
  30674. * Add a inline-code to the current flow.
  30675. *
  30676. * @param {String} code - The code to add.
  30677. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  30678. * @return {NodeBuilder} A reference to this node builder.
  30679. */
  30680. addLineFlowCode( code, node = null ) {
  30681. if ( code === '' ) return this;
  30682. if ( node !== null && this.context.nodeBlock ) {
  30683. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  30684. }
  30685. code = this.tab + code;
  30686. if ( ! /;\s*$/.test( code ) ) {
  30687. code = code + ';\n';
  30688. }
  30689. this.flow.code += code;
  30690. return this;
  30691. }
  30692. /**
  30693. * Adds a code to the current code flow.
  30694. *
  30695. * @param {String} code - Shader code.
  30696. * @return {NodeBuilder} A reference to this node builder.
  30697. */
  30698. addFlowCode( code ) {
  30699. this.flow.code += code;
  30700. return this;
  30701. }
  30702. /**
  30703. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  30704. * Typically used in codes with If,Else.
  30705. *
  30706. * @return {NodeBuilder} A reference to this node builder.
  30707. */
  30708. addFlowTab() {
  30709. this.tab += '\t';
  30710. return this;
  30711. }
  30712. /**
  30713. * Removes a tab.
  30714. *
  30715. * @return {NodeBuilder} A reference to this node builder.
  30716. */
  30717. removeFlowTab() {
  30718. this.tab = this.tab.slice( 0, - 1 );
  30719. return this;
  30720. }
  30721. /**
  30722. * Gets the current flow data based on a Node.
  30723. *
  30724. * @param {Node} node - Node that the flow was started.
  30725. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30726. * @return {Object} The flow data.
  30727. */
  30728. getFlowData( node/*, shaderStage*/ ) {
  30729. return this.flowsData.get( node );
  30730. }
  30731. /**
  30732. * Executes the node flow based on a root node to generate the final shader code.
  30733. *
  30734. * @param {Node} node - The node to execute.
  30735. * @return {Object} The code flow.
  30736. */
  30737. flowNode( node ) {
  30738. const output = node.getNodeType( this );
  30739. const flowData = this.flowChildNode( node, output );
  30740. this.flowsData.set( node, flowData );
  30741. return flowData;
  30742. }
  30743. /**
  30744. * Returns the native shader operator name for a given generic name.
  30745. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30746. *
  30747. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  30748. * @return {FunctionNode} The build function node.
  30749. */
  30750. buildFunctionNode( shaderNode ) {
  30751. const fn = new FunctionNode();
  30752. const previous = this.currentFunctionNode;
  30753. this.currentFunctionNode = fn;
  30754. fn.code = this.buildFunctionCode( shaderNode );
  30755. this.currentFunctionNode = previous;
  30756. return fn;
  30757. }
  30758. /**
  30759. * Generates a code flow based on a TSL function: Fn().
  30760. *
  30761. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  30762. * @return {Object}
  30763. */
  30764. flowShaderNode( shaderNode ) {
  30765. const layout = shaderNode.layout;
  30766. const inputs = {
  30767. [ Symbol.iterator ]() {
  30768. let index = 0;
  30769. const values = Object.values( this );
  30770. return {
  30771. next: () => ( {
  30772. value: values[ index ],
  30773. done: index ++ >= values.length
  30774. } )
  30775. };
  30776. }
  30777. };
  30778. for ( const input of layout.inputs ) {
  30779. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  30780. }
  30781. //
  30782. shaderNode.layout = null;
  30783. const callNode = shaderNode.call( inputs );
  30784. const flowData = this.flowStagesNode( callNode, layout.type );
  30785. shaderNode.layout = layout;
  30786. return flowData;
  30787. }
  30788. /**
  30789. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  30790. *
  30791. * @param {Node} node - The node to execute.
  30792. * @param {String?} output - Expected output type. For example 'vec3'.
  30793. * @return {Object}
  30794. */
  30795. flowStagesNode( node, output = null ) {
  30796. const previousFlow = this.flow;
  30797. const previousVars = this.vars;
  30798. const previousCache = this.cache;
  30799. const previousBuildStage = this.buildStage;
  30800. const previousStack = this.stack;
  30801. const flow = {
  30802. code: ''
  30803. };
  30804. this.flow = flow;
  30805. this.vars = {};
  30806. this.cache = new NodeCache();
  30807. this.stack = stack();
  30808. for ( const buildStage of defaultBuildStages ) {
  30809. this.setBuildStage( buildStage );
  30810. flow.result = node.build( this, output );
  30811. }
  30812. flow.vars = this.getVars( this.shaderStage );
  30813. this.flow = previousFlow;
  30814. this.vars = previousVars;
  30815. this.cache = previousCache;
  30816. this.stack = previousStack;
  30817. this.setBuildStage( previousBuildStage );
  30818. return flow;
  30819. }
  30820. /**
  30821. * Returns the native shader operator name for a given generic name.
  30822. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30823. *
  30824. * @abstract
  30825. * @param {String} op - The operator name to resolve.
  30826. * @return {String} The resolved operator name.
  30827. */
  30828. getFunctionOperator( /* op */ ) {
  30829. return null;
  30830. }
  30831. /**
  30832. * Generates a code flow based on a child Node.
  30833. *
  30834. * @param {Node} node - The node to execute.
  30835. * @param {String?} output - Expected output type. For example 'vec3'.
  30836. * @return {Object} The code flow.
  30837. */
  30838. flowChildNode( node, output = null ) {
  30839. const previousFlow = this.flow;
  30840. const flow = {
  30841. code: ''
  30842. };
  30843. this.flow = flow;
  30844. flow.result = node.build( this, output );
  30845. this.flow = previousFlow;
  30846. return flow;
  30847. }
  30848. /**
  30849. * Executes a flow of code in a different stage.
  30850. *
  30851. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  30852. * return the value in fragment-stage even if it is being executed in an input fragment.
  30853. *
  30854. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30855. * @param {Node} node - The node to execute.
  30856. * @param {String?} output - Expected output type. For example 'vec3'.
  30857. * @param {String?} propertyName - The property name to assign the result.
  30858. * @return {Object}
  30859. */
  30860. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  30861. const previousShaderStage = this.shaderStage;
  30862. this.setShaderStage( shaderStage );
  30863. const flowData = this.flowChildNode( node, output );
  30864. if ( propertyName !== null ) {
  30865. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  30866. }
  30867. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  30868. this.setShaderStage( previousShaderStage );
  30869. return flowData;
  30870. }
  30871. /**
  30872. * Returns an array holding all node attributes of this node builder.
  30873. *
  30874. * @return {Array<NodeAttribute>} The node attributes of this builder.
  30875. */
  30876. getAttributesArray() {
  30877. return this.attributes.concat( this.bufferAttributes );
  30878. }
  30879. /**
  30880. * Returns the attribute definitions as a shader string for the given shader stage.
  30881. *
  30882. * @abstract
  30883. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30884. * @return {String} The attribute code section.
  30885. */
  30886. getAttributes( /*shaderStage*/ ) {
  30887. console.warn( 'Abstract function.' );
  30888. }
  30889. /**
  30890. * Returns the varying definitions as a shader string for the given shader stage.
  30891. *
  30892. * @abstract
  30893. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30894. * @return {String} The varying code section.
  30895. */
  30896. getVaryings( /*shaderStage*/ ) {
  30897. console.warn( 'Abstract function.' );
  30898. }
  30899. /**
  30900. * Returns a single variable definition as a shader string for the given variable type and name.
  30901. *
  30902. * @param {String} type - The variable's type.
  30903. * @param {String} name - The variable's name.
  30904. * @return {String} The shader string.
  30905. */
  30906. getVar( type, name ) {
  30907. return `${ this.getType( type ) } ${ name }`;
  30908. }
  30909. /**
  30910. * Returns the variable definitions as a shader string for the given shader stage.
  30911. *
  30912. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30913. * @return {String} The variable code section.
  30914. */
  30915. getVars( shaderStage ) {
  30916. let snippet = '';
  30917. const vars = this.vars[ shaderStage ];
  30918. if ( vars !== undefined ) {
  30919. for ( const variable of vars ) {
  30920. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  30921. }
  30922. }
  30923. return snippet;
  30924. }
  30925. /**
  30926. * Returns the uniform definitions as a shader string for the given shader stage.
  30927. *
  30928. * @abstract
  30929. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30930. * @return {String} The uniform code section.
  30931. */
  30932. getUniforms( /*shaderStage*/ ) {
  30933. console.warn( 'Abstract function.' );
  30934. }
  30935. /**
  30936. * Returns the native code definitions as a shader string for the given shader stage.
  30937. *
  30938. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30939. * @return {String} The native code section.
  30940. */
  30941. getCodes( shaderStage ) {
  30942. const codes = this.codes[ shaderStage ];
  30943. let code = '';
  30944. if ( codes !== undefined ) {
  30945. for ( const nodeCode of codes ) {
  30946. code += nodeCode.code + '\n';
  30947. }
  30948. }
  30949. return code;
  30950. }
  30951. /**
  30952. * Returns the hash of this node builder.
  30953. *
  30954. * @return {String} The hash.
  30955. */
  30956. getHash() {
  30957. return this.vertexShader + this.fragmentShader + this.computeShader;
  30958. }
  30959. /**
  30960. * Sets the current shader stage.
  30961. *
  30962. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  30963. */
  30964. setShaderStage( shaderStage ) {
  30965. this.shaderStage = shaderStage;
  30966. }
  30967. /**
  30968. * Returns the current shader stage.
  30969. *
  30970. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  30971. */
  30972. getShaderStage() {
  30973. return this.shaderStage;
  30974. }
  30975. /**
  30976. * Sets the current build stage.
  30977. *
  30978. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  30979. */
  30980. setBuildStage( buildStage ) {
  30981. this.buildStage = buildStage;
  30982. }
  30983. /**
  30984. * Returns the current build stage.
  30985. *
  30986. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  30987. */
  30988. getBuildStage() {
  30989. return this.buildStage;
  30990. }
  30991. /**
  30992. * Controls the code build of the shader stages.
  30993. *
  30994. * @abstract
  30995. */
  30996. buildCode() {
  30997. console.warn( 'Abstract function.' );
  30998. }
  30999. /**
  31000. * Central build method which controls the build for the given object.
  31001. *
  31002. * @return {NodeBuilder} A reference to this node builder.
  31003. */
  31004. build() {
  31005. const { object, material, renderer } = this;
  31006. if ( material !== null ) {
  31007. let nodeMaterial = renderer.library.fromMaterial( material );
  31008. if ( nodeMaterial === null ) {
  31009. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  31010. nodeMaterial = new NodeMaterial();
  31011. }
  31012. nodeMaterial.build( this );
  31013. } else {
  31014. this.addFlow( 'compute', object );
  31015. }
  31016. // setup() -> stage 1: create possible new nodes and returns an output reference node
  31017. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  31018. // generate() -> stage 3: generate shader
  31019. for ( const buildStage of defaultBuildStages ) {
  31020. this.setBuildStage( buildStage );
  31021. if ( this.context.vertex && this.context.vertex.isNode ) {
  31022. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  31023. }
  31024. for ( const shaderStage of shaderStages ) {
  31025. this.setShaderStage( shaderStage );
  31026. const flowNodes = this.flowNodes[ shaderStage ];
  31027. for ( const node of flowNodes ) {
  31028. if ( buildStage === 'generate' ) {
  31029. this.flowNode( node );
  31030. } else {
  31031. node.build( this );
  31032. }
  31033. }
  31034. }
  31035. }
  31036. this.setBuildStage( null );
  31037. this.setShaderStage( null );
  31038. // stage 4: build code for a specific output
  31039. this.buildCode();
  31040. this.buildUpdateNodes();
  31041. return this;
  31042. }
  31043. /**
  31044. * Returns a uniform representation which is later used for UBO generation and rendering.
  31045. *
  31046. * @param {NodeUniform} uniformNode - The uniform node.
  31047. * @param {String} type - The requested type.
  31048. * @return {Uniform} The uniform.
  31049. */
  31050. getNodeUniform( uniformNode, type ) {
  31051. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  31052. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  31053. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  31054. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  31055. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  31056. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  31057. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  31058. throw new Error( `Uniform "${type}" not declared.` );
  31059. }
  31060. /**
  31061. * Formats the given shader snippet from a given type into another one. E.g.
  31062. * this method might be used to convert a simple float string `"1.0"` into a
  31063. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  31064. *
  31065. * @param {String} snippet - The shader snippet.
  31066. * @param {String} fromType - The source type.
  31067. * @param {String} toType - The target type.
  31068. * @return {String} The updated shader string.
  31069. */
  31070. format( snippet, fromType, toType ) {
  31071. fromType = this.getVectorType( fromType );
  31072. toType = this.getVectorType( toType );
  31073. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  31074. return snippet;
  31075. }
  31076. const fromTypeLength = this.getTypeLength( fromType );
  31077. const toTypeLength = this.getTypeLength( toType );
  31078. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  31079. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  31080. }
  31081. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  31082. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  31083. }
  31084. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  31085. // @TODO: ignore for now
  31086. return snippet;
  31087. }
  31088. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  31089. // @TODO: ignore for now
  31090. return snippet;
  31091. }
  31092. if ( fromTypeLength === toTypeLength ) {
  31093. return `${ this.getType( toType ) }( ${ snippet } )`;
  31094. }
  31095. if ( fromTypeLength > toTypeLength ) {
  31096. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  31097. }
  31098. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  31099. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  31100. }
  31101. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  31102. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  31103. }
  31104. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  31105. // convert a number value to vector type, e.g:
  31106. // vec3( 1u ) -> vec3( float( 1u ) )
  31107. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  31108. }
  31109. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  31110. }
  31111. /**
  31112. * Returns a signature with the engine's current revision.
  31113. *
  31114. * @return {String} The signature.
  31115. */
  31116. getSignature() {
  31117. return `// Three.js r${ REVISION } - Node System\n`;
  31118. }
  31119. // deprecated
  31120. /**
  31121. * @function
  31122. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  31123. *
  31124. * @param {String} [type='NodeMaterial'] - The node material type.
  31125. * @throws {Error}
  31126. */
  31127. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  31128. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  31129. }
  31130. }
  31131. /**
  31132. * Management class for updating nodes. The module tracks metrics like
  31133. * the elapsed time, delta time, the render and frame ID to correctly
  31134. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  31135. * and {@link Node#updateAfter} depending on the node's configuration.
  31136. */
  31137. class NodeFrame {
  31138. /**
  31139. * Constructs a new node fame.
  31140. */
  31141. constructor() {
  31142. /**
  31143. * The elapsed time in seconds.
  31144. *
  31145. * @type {Number}
  31146. * @default 0
  31147. */
  31148. this.time = 0;
  31149. /**
  31150. * The delta time in seconds.
  31151. *
  31152. * @type {Number}
  31153. * @default 0
  31154. */
  31155. this.deltaTime = 0;
  31156. /**
  31157. * The frame ID.
  31158. *
  31159. * @type {Number}
  31160. * @default 0
  31161. */
  31162. this.frameId = 0;
  31163. /**
  31164. * The render ID.
  31165. *
  31166. * @type {Number}
  31167. * @default 0
  31168. */
  31169. this.renderId = 0;
  31170. /**
  31171. * Used to control the {@link Node#update} call.
  31172. *
  31173. * @type {WeakMap<Node, Object>}
  31174. */
  31175. this.updateMap = new WeakMap();
  31176. /**
  31177. * Used to control the {@link Node#updateBefore} call.
  31178. *
  31179. * @type {WeakMap<Node, Object>}
  31180. */
  31181. this.updateBeforeMap = new WeakMap();
  31182. /**
  31183. * Used to control the {@link Node#updateAfter} call.
  31184. *
  31185. * @type {WeakMap<Node, Object>}
  31186. */
  31187. this.updateAfterMap = new WeakMap();
  31188. /**
  31189. * A reference to the current renderer.
  31190. *
  31191. * @type {Renderer?}
  31192. * @default null
  31193. */
  31194. this.renderer = null;
  31195. /**
  31196. * A reference to the current material.
  31197. *
  31198. * @type {Material?}
  31199. * @default null
  31200. */
  31201. this.material = null;
  31202. /**
  31203. * A reference to the current camera.
  31204. *
  31205. * @type {Camera?}
  31206. * @default null
  31207. */
  31208. this.camera = null;
  31209. /**
  31210. * A reference to the current 3D object.
  31211. *
  31212. * @type {Object3D?}
  31213. * @default null
  31214. */
  31215. this.object = null;
  31216. /**
  31217. * A reference to the current scene.
  31218. *
  31219. * @type {Scene?}
  31220. * @default null
  31221. */
  31222. this.scene = null;
  31223. }
  31224. /**
  31225. * Returns a dictionary for a given node and update map which
  31226. * is used to correctly call node update methods per frame or render.
  31227. *
  31228. * @private
  31229. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  31230. * @param {Node} nodeRef - The reference to the current node.
  31231. * @return {Object<String,WeakMap>} The dictionary.
  31232. */
  31233. _getMaps( referenceMap, nodeRef ) {
  31234. let maps = referenceMap.get( nodeRef );
  31235. if ( maps === undefined ) {
  31236. maps = {
  31237. renderMap: new WeakMap(),
  31238. frameMap: new WeakMap()
  31239. };
  31240. referenceMap.set( nodeRef, maps );
  31241. }
  31242. return maps;
  31243. }
  31244. /**
  31245. * This method executes the {@link Node#updateBefore} for the given node.
  31246. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  31247. * is only executed once per frame, render or object depending on the update
  31248. * type.
  31249. *
  31250. * @param {Node} node - The node that should be updated.
  31251. */
  31252. updateBeforeNode( node ) {
  31253. const updateType = node.getUpdateBeforeType();
  31254. const reference = node.updateReference( this );
  31255. if ( updateType === NodeUpdateType.FRAME ) {
  31256. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  31257. if ( frameMap.get( reference ) !== this.frameId ) {
  31258. if ( node.updateBefore( this ) !== false ) {
  31259. frameMap.set( reference, this.frameId );
  31260. }
  31261. }
  31262. } else if ( updateType === NodeUpdateType.RENDER ) {
  31263. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  31264. if ( renderMap.get( reference ) !== this.renderId ) {
  31265. if ( node.updateBefore( this ) !== false ) {
  31266. renderMap.set( reference, this.renderId );
  31267. }
  31268. }
  31269. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31270. node.updateBefore( this );
  31271. }
  31272. }
  31273. /**
  31274. * This method executes the {@link Node#updateAfter} for the given node.
  31275. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  31276. * is only executed once per frame, render or object depending on the update
  31277. * type.
  31278. *
  31279. * @param {Node} node - The node that should be updated.
  31280. */
  31281. updateAfterNode( node ) {
  31282. const updateType = node.getUpdateAfterType();
  31283. const reference = node.updateReference( this );
  31284. if ( updateType === NodeUpdateType.FRAME ) {
  31285. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  31286. if ( frameMap.get( reference ) !== this.frameId ) {
  31287. if ( node.updateAfter( this ) !== false ) {
  31288. frameMap.set( reference, this.frameId );
  31289. }
  31290. }
  31291. } else if ( updateType === NodeUpdateType.RENDER ) {
  31292. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  31293. if ( renderMap.get( reference ) !== this.renderId ) {
  31294. if ( node.updateAfter( this ) !== false ) {
  31295. renderMap.set( reference, this.renderId );
  31296. }
  31297. }
  31298. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31299. node.updateAfter( this );
  31300. }
  31301. }
  31302. /**
  31303. * This method executes the {@link Node#update} for the given node.
  31304. * It makes sure {@link Node#updateType} is honored meaning the update
  31305. * is only executed once per frame, render or object depending on the update
  31306. * type.
  31307. *
  31308. * @param {Node} node - The node that should be updated.
  31309. */
  31310. updateNode( node ) {
  31311. const updateType = node.getUpdateType();
  31312. const reference = node.updateReference( this );
  31313. if ( updateType === NodeUpdateType.FRAME ) {
  31314. const { frameMap } = this._getMaps( this.updateMap, reference );
  31315. if ( frameMap.get( reference ) !== this.frameId ) {
  31316. if ( node.update( this ) !== false ) {
  31317. frameMap.set( reference, this.frameId );
  31318. }
  31319. }
  31320. } else if ( updateType === NodeUpdateType.RENDER ) {
  31321. const { renderMap } = this._getMaps( this.updateMap, reference );
  31322. if ( renderMap.get( reference ) !== this.renderId ) {
  31323. if ( node.update( this ) !== false ) {
  31324. renderMap.set( reference, this.renderId );
  31325. }
  31326. }
  31327. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31328. node.update( this );
  31329. }
  31330. }
  31331. /**
  31332. * Updates the internal state of the node frame. This method is
  31333. * called by the renderer in its internal animation loop.
  31334. */
  31335. update() {
  31336. this.frameId ++;
  31337. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31338. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31339. this.lastTime = performance.now();
  31340. this.time += this.deltaTime;
  31341. }
  31342. }
  31343. /**
  31344. * Describes the input of a {@link NodeFunction}.
  31345. */
  31346. class NodeFunctionInput {
  31347. /**
  31348. * Constructs a new node function input.
  31349. *
  31350. * @param {String} type - The input type.
  31351. * @param {String} name - The input name.
  31352. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  31353. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  31354. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  31355. */
  31356. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31357. /**
  31358. * The input type.
  31359. *
  31360. * @type {String}
  31361. */
  31362. this.type = type;
  31363. /**
  31364. * The input name.
  31365. *
  31366. * @type {String}
  31367. */
  31368. this.name = name;
  31369. /**
  31370. * If the input is an Array, count will be the length.
  31371. *
  31372. * @type {Number?}
  31373. * @default null
  31374. */
  31375. this.count = count;
  31376. /**
  31377. *The parameter qualifier (only relevant for GLSL).
  31378. *
  31379. * @type {('in'|'out'|'inout')}
  31380. * @default ''
  31381. */
  31382. this.qualifier = qualifier;
  31383. /**
  31384. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  31385. *
  31386. * @type {Boolean}
  31387. * @default false
  31388. */
  31389. this.isConst = isConst;
  31390. }
  31391. }
  31392. NodeFunctionInput.isNodeFunctionInput = true;
  31393. /**
  31394. * Module for representing directional lights as nodes.
  31395. *
  31396. * @augments AnalyticLightNode
  31397. */
  31398. class DirectionalLightNode extends AnalyticLightNode {
  31399. static get type() {
  31400. return 'DirectionalLightNode';
  31401. }
  31402. /**
  31403. * Constructs a new directional light node.
  31404. *
  31405. * @param {DirectionalLight?} [light=null] - The directional light source.
  31406. */
  31407. constructor( light = null ) {
  31408. super( light );
  31409. }
  31410. setup( builder ) {
  31411. super.setup( builder );
  31412. const lightingModel = builder.context.lightingModel;
  31413. const lightColor = this.colorNode;
  31414. const lightDirection = lightTargetDirection( this.light );
  31415. const reflectedLight = builder.context.reflectedLight;
  31416. lightingModel.direct( {
  31417. lightDirection,
  31418. lightColor,
  31419. reflectedLight
  31420. }, builder.stack, builder );
  31421. }
  31422. }
  31423. const _matrix41 = /*@__PURE__*/ new Matrix4();
  31424. const _matrix42 = /*@__PURE__*/ new Matrix4();
  31425. let _ltcLib = null;
  31426. /**
  31427. * Module for representing rect area lights as nodes.
  31428. *
  31429. * @augments AnalyticLightNode
  31430. */
  31431. class RectAreaLightNode extends AnalyticLightNode {
  31432. static get type() {
  31433. return 'RectAreaLightNode';
  31434. }
  31435. /**
  31436. * Constructs a new rect area light node.
  31437. *
  31438. * @param {RectAreaLight?} [light=null] - The rect area light source.
  31439. */
  31440. constructor( light = null ) {
  31441. super( light );
  31442. /**
  31443. * Uniform node representing the half height of the are light.
  31444. *
  31445. * @type {UniformNode<vec3>}
  31446. */
  31447. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  31448. /**
  31449. * Uniform node representing the half width of the are light.
  31450. *
  31451. * @type {UniformNode<vec3>}
  31452. */
  31453. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  31454. /**
  31455. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  31456. * relies on `viewMatrix` which might vary per render call.
  31457. *
  31458. * @type {String}
  31459. * @default 'render'
  31460. */
  31461. this.updateType = NodeUpdateType.RENDER;
  31462. }
  31463. /**
  31464. * Overwritten to updated rect area light specific uniforms.
  31465. *
  31466. * @param {NodeFrame} frame - A reference to the current node frame.
  31467. */
  31468. update( frame ) {
  31469. super.update( frame );
  31470. const { light } = this;
  31471. const viewMatrix = frame.camera.matrixWorldInverse;
  31472. _matrix42.identity();
  31473. _matrix41.copy( light.matrixWorld );
  31474. _matrix41.premultiply( viewMatrix );
  31475. _matrix42.extractRotation( _matrix41 );
  31476. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31477. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31478. this.halfWidth.value.applyMatrix4( _matrix42 );
  31479. this.halfHeight.value.applyMatrix4( _matrix42 );
  31480. }
  31481. setup( builder ) {
  31482. super.setup( builder );
  31483. let ltc_1, ltc_2;
  31484. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31485. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  31486. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  31487. } else {
  31488. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  31489. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  31490. }
  31491. const { colorNode, light } = this;
  31492. const lightingModel = builder.context.lightingModel;
  31493. const lightPosition = lightViewPosition( light );
  31494. const reflectedLight = builder.context.reflectedLight;
  31495. lightingModel.directRectArea( {
  31496. lightColor: colorNode,
  31497. lightPosition,
  31498. halfWidth: this.halfWidth,
  31499. halfHeight: this.halfHeight,
  31500. reflectedLight,
  31501. ltc_1,
  31502. ltc_2
  31503. }, builder.stack, builder );
  31504. }
  31505. /**
  31506. * Used to configure the internal BRDF approximation texture data.
  31507. *
  31508. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  31509. */
  31510. static setLTC( ltc ) {
  31511. _ltcLib = ltc;
  31512. }
  31513. }
  31514. /**
  31515. * Module for representing spot lights as nodes.
  31516. *
  31517. * @augments AnalyticLightNode
  31518. */
  31519. class SpotLightNode extends AnalyticLightNode {
  31520. static get type() {
  31521. return 'SpotLightNode';
  31522. }
  31523. /**
  31524. * Constructs a new spot light node.
  31525. *
  31526. * @param {SpotLight?} [light=null] - The spot light source.
  31527. */
  31528. constructor( light = null ) {
  31529. super( light );
  31530. /**
  31531. * Uniform node representing the cone cosine.
  31532. *
  31533. * @type {UniformNode<float>}
  31534. */
  31535. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  31536. /**
  31537. * Uniform node representing the penumbra cosine.
  31538. *
  31539. * @type {UniformNode<float>}
  31540. */
  31541. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  31542. /**
  31543. * Uniform node representing the cutoff distance.
  31544. *
  31545. * @type {UniformNode<float>}
  31546. */
  31547. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31548. /**
  31549. * Uniform node representing the decay exponent.
  31550. *
  31551. * @type {UniformNode<float>}
  31552. */
  31553. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  31554. }
  31555. /**
  31556. * Overwritten to updated spot light specific uniforms.
  31557. *
  31558. * @param {NodeFrame} frame - A reference to the current node frame.
  31559. */
  31560. update( frame ) {
  31561. super.update( frame );
  31562. const { light } = this;
  31563. this.coneCosNode.value = Math.cos( light.angle );
  31564. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31565. this.cutoffDistanceNode.value = light.distance;
  31566. this.decayExponentNode.value = light.decay;
  31567. }
  31568. /**
  31569. * Computes the spot attenuation for the given angle.
  31570. *
  31571. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31572. * @return {Node<float>} The spot attenuation.
  31573. */
  31574. getSpotAttenuation( angleCosine ) {
  31575. const { coneCosNode, penumbraCosNode } = this;
  31576. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31577. }
  31578. setup( builder ) {
  31579. super.setup( builder );
  31580. const lightingModel = builder.context.lightingModel;
  31581. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31582. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31583. const lightDirection = lVector.normalize();
  31584. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31585. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31586. const lightDistance = lVector.length();
  31587. const lightAttenuation = getDistanceAttenuation( {
  31588. lightDistance,
  31589. cutoffDistance: cutoffDistanceNode,
  31590. decayExponent: decayExponentNode
  31591. } );
  31592. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31593. if ( light.map ) {
  31594. const spotLightCoord = lightProjectionUV( light );
  31595. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  31596. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  31597. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  31598. }
  31599. const reflectedLight = builder.context.reflectedLight;
  31600. lightingModel.direct( {
  31601. lightDirection,
  31602. lightColor,
  31603. reflectedLight
  31604. }, builder.stack, builder );
  31605. }
  31606. }
  31607. /**
  31608. * An IES version of the default spot light node.
  31609. *
  31610. * @augments SpotLightNode
  31611. */
  31612. class IESSpotLightNode extends SpotLightNode {
  31613. static get type() {
  31614. return 'IESSpotLightNode';
  31615. }
  31616. /**
  31617. * Overwrites the default implementation to compute an IES conform spot attenuation.
  31618. *
  31619. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31620. * @return {Node<float>} The spot attenuation.
  31621. */
  31622. getSpotAttenuation( angleCosine ) {
  31623. const iesMap = this.light.iesMap;
  31624. let spotAttenuation = null;
  31625. if ( iesMap && iesMap.isTexture === true ) {
  31626. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  31627. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  31628. } else {
  31629. spotAttenuation = super.getSpotAttenuation( angleCosine );
  31630. }
  31631. return spotAttenuation;
  31632. }
  31633. }
  31634. /**
  31635. * Module for representing ambient lights as nodes.
  31636. *
  31637. * @augments AnalyticLightNode
  31638. */
  31639. class AmbientLightNode extends AnalyticLightNode {
  31640. static get type() {
  31641. return 'AmbientLightNode';
  31642. }
  31643. /**
  31644. * Constructs a new ambient light node.
  31645. *
  31646. * @param {AmbientLight?} [light=null] - The ambient light source.
  31647. */
  31648. constructor( light = null ) {
  31649. super( light );
  31650. }
  31651. setup( { context } ) {
  31652. context.irradiance.addAssign( this.colorNode );
  31653. }
  31654. }
  31655. /**
  31656. * Module for representing hemisphere lights as nodes.
  31657. *
  31658. * @augments AnalyticLightNode
  31659. */
  31660. class HemisphereLightNode extends AnalyticLightNode {
  31661. static get type() {
  31662. return 'HemisphereLightNode';
  31663. }
  31664. /**
  31665. * Constructs a new hemisphere light node.
  31666. *
  31667. * @param {HemisphereLight?} [light=null] - The hemisphere light source.
  31668. */
  31669. constructor( light = null ) {
  31670. super( light );
  31671. /**
  31672. * Uniform node representing the light's position.
  31673. *
  31674. * @type {UniformNode<vec3>}
  31675. */
  31676. this.lightPositionNode = lightPosition( light );
  31677. /**
  31678. * A node representing the light's direction.
  31679. *
  31680. * @type {Node<vec3>}
  31681. */
  31682. this.lightDirectionNode = this.lightPositionNode.normalize();
  31683. /**
  31684. * Uniform node representing the light's ground color.
  31685. *
  31686. * @type {UniformNode<vec3>}
  31687. */
  31688. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  31689. }
  31690. /**
  31691. * Overwritten to updated hemisphere light specific uniforms.
  31692. *
  31693. * @param {NodeFrame} frame - A reference to the current node frame.
  31694. */
  31695. update( frame ) {
  31696. const { light } = this;
  31697. super.update( frame );
  31698. this.lightPositionNode.object3d = light;
  31699. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  31700. }
  31701. setup( builder ) {
  31702. const { colorNode, groundColorNode, lightDirectionNode } = this;
  31703. const dotNL = normalView.dot( lightDirectionNode );
  31704. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  31705. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  31706. builder.context.irradiance.addAssign( irradiance );
  31707. }
  31708. }
  31709. /**
  31710. * Module for representing light probes as nodes.
  31711. *
  31712. * @augments AnalyticLightNode
  31713. */
  31714. class LightProbeNode extends AnalyticLightNode {
  31715. static get type() {
  31716. return 'LightProbeNode';
  31717. }
  31718. /**
  31719. * Constructs a new light probe node.
  31720. *
  31721. * @param {LightProbe?} [light=null] - The light probe.
  31722. */
  31723. constructor( light = null ) {
  31724. super( light );
  31725. const array = [];
  31726. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  31727. /**
  31728. * Light probe represented as a uniform of spherical harmonics.
  31729. *
  31730. * @type {UniformArrayNode}
  31731. */
  31732. this.lightProbe = uniformArray( array );
  31733. }
  31734. /**
  31735. * Overwritten to updated light probe specific uniforms.
  31736. *
  31737. * @param {NodeFrame} frame - A reference to the current node frame.
  31738. */
  31739. update( frame ) {
  31740. const { light } = this;
  31741. super.update( frame );
  31742. //
  31743. for ( let i = 0; i < 9; i ++ ) {
  31744. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  31745. }
  31746. }
  31747. setup( builder ) {
  31748. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  31749. builder.context.irradiance.addAssign( irradiance );
  31750. }
  31751. }
  31752. /**
  31753. * Base class for node parsers. A derived parser must be implemented
  31754. * for each supported native shader language.
  31755. */
  31756. class NodeParser {
  31757. /**
  31758. * The method parses the given native code an returns a node function.
  31759. *
  31760. * @abstract
  31761. * @param {String} source - The native shader code.
  31762. * @return {NodeFunction} A node function.
  31763. */
  31764. parseFunction( /*source*/ ) {
  31765. console.warn( 'Abstract function.' );
  31766. }
  31767. }
  31768. /**
  31769. * Base class for node functions. A derived module must be implemented
  31770. * for each supported native shader language. Similar to other `Node*` modules,
  31771. * this class is only relevant during the building process and not used
  31772. * in user-level code.
  31773. */
  31774. class NodeFunction {
  31775. /**
  31776. * Constructs a new node function.
  31777. *
  31778. * @param {String} type - The node type. This type is the return type of the node function.
  31779. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  31780. * @param {String} [name=''] - The function's name.
  31781. * @param {String} [precision=''] - The precision qualifier.
  31782. */
  31783. constructor( type, inputs, name = '', precision = '' ) {
  31784. /**
  31785. * The node type. This type is the return type of the node function.
  31786. *
  31787. * @type {String}
  31788. */
  31789. this.type = type;
  31790. /**
  31791. * The function's inputs.
  31792. *
  31793. * @type {Array<NodeFunctionInput>}
  31794. */
  31795. this.inputs = inputs;
  31796. /**
  31797. * The name of the uniform.
  31798. *
  31799. * @type {String}
  31800. * @default ''
  31801. */
  31802. this.name = name;
  31803. /**
  31804. * The precision qualifier.
  31805. *
  31806. * @type {String}
  31807. * @default ''
  31808. */
  31809. this.precision = precision;
  31810. }
  31811. /**
  31812. * This method returns the native code of the node function.
  31813. *
  31814. * @abstract
  31815. * @param {String} name - The function's name.
  31816. * @return {String} A shader code.
  31817. */
  31818. getCode( /*name = this.name*/ ) {
  31819. console.warn( 'Abstract function.' );
  31820. }
  31821. }
  31822. NodeFunction.isNodeFunction = true;
  31823. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  31824. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  31825. const pragmaMain = '#pragma main';
  31826. const parse$1 = ( source ) => {
  31827. source = source.trim();
  31828. const pragmaMainIndex = source.indexOf( pragmaMain );
  31829. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  31830. const declaration = mainCode.match( declarationRegexp$1 );
  31831. if ( declaration !== null && declaration.length === 5 ) {
  31832. // tokenizer
  31833. const inputsCode = declaration[ 4 ];
  31834. const propsMatches = [];
  31835. let nameMatch = null;
  31836. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  31837. propsMatches.push( nameMatch );
  31838. }
  31839. // parser
  31840. const inputs = [];
  31841. let i = 0;
  31842. while ( i < propsMatches.length ) {
  31843. const isConst = propsMatches[ i ][ 0 ] === 'const';
  31844. if ( isConst === true ) {
  31845. i ++;
  31846. }
  31847. let qualifier = propsMatches[ i ][ 0 ];
  31848. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  31849. i ++;
  31850. } else {
  31851. qualifier = '';
  31852. }
  31853. const type = propsMatches[ i ++ ][ 0 ];
  31854. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  31855. if ( Number.isNaN( count ) === false ) i ++;
  31856. else count = null;
  31857. const name = propsMatches[ i ++ ][ 0 ];
  31858. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  31859. }
  31860. //
  31861. const blockCode = mainCode.substring( declaration[ 0 ].length );
  31862. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  31863. const type = declaration[ 2 ];
  31864. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  31865. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  31866. return {
  31867. type,
  31868. inputs,
  31869. name,
  31870. precision,
  31871. inputsCode,
  31872. blockCode,
  31873. headerCode
  31874. };
  31875. } else {
  31876. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  31877. }
  31878. };
  31879. /**
  31880. * This class represents a GLSL node function.
  31881. *
  31882. * @augments NodeFunction
  31883. */
  31884. class GLSLNodeFunction extends NodeFunction {
  31885. /**
  31886. * Constructs a new GLSL node function.
  31887. *
  31888. * @param {String} source - The GLSL source.
  31889. */
  31890. constructor( source ) {
  31891. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  31892. super( type, inputs, name, precision );
  31893. this.inputsCode = inputsCode;
  31894. this.blockCode = blockCode;
  31895. this.headerCode = headerCode;
  31896. }
  31897. /**
  31898. * This method returns the GLSL code of the node function.
  31899. *
  31900. * @param {String} [name=this.name] - The function's name.
  31901. * @return {String} The shader code.
  31902. */
  31903. getCode( name = this.name ) {
  31904. let code;
  31905. const blockCode = this.blockCode;
  31906. if ( blockCode !== '' ) {
  31907. const { type, inputsCode, headerCode, precision } = this;
  31908. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  31909. if ( precision !== '' ) {
  31910. declarationCode = `${ precision } ${ declarationCode }`;
  31911. }
  31912. code = headerCode + declarationCode + blockCode;
  31913. } else {
  31914. // interface function
  31915. code = '';
  31916. }
  31917. return code;
  31918. }
  31919. }
  31920. /**
  31921. * A GLSL node parser.
  31922. *
  31923. * @augments NodeParser
  31924. */
  31925. class GLSLNodeParser extends NodeParser {
  31926. /**
  31927. * The method parses the given GLSL code an returns a node function.
  31928. *
  31929. * @param {String} source - The GLSL code.
  31930. * @return {GLSLNodeFunction} A node function.
  31931. */
  31932. parseFunction( source ) {
  31933. return new GLSLNodeFunction( source );
  31934. }
  31935. }
  31936. const _outputNodeMap = new WeakMap();
  31937. const _chainKeys$2 = [];
  31938. const _cacheKeyValues = [];
  31939. /**
  31940. * This renderer module manages node-related objects and is the
  31941. * primary interface between the renderer and the node system.
  31942. *
  31943. * @private
  31944. * @augments DataMap
  31945. */
  31946. class Nodes extends DataMap {
  31947. /**
  31948. * Constructs a new nodes management component.
  31949. *
  31950. * @param {Renderer} renderer - The renderer.
  31951. * @param {Backend} backend - The renderer's backend.
  31952. */
  31953. constructor( renderer, backend ) {
  31954. super();
  31955. /**
  31956. * The renderer.
  31957. *
  31958. * @type {Renderer}
  31959. */
  31960. this.renderer = renderer;
  31961. /**
  31962. * The renderer's backend.
  31963. *
  31964. * @type {Backend}
  31965. */
  31966. this.backend = backend;
  31967. /**
  31968. * The node frame.
  31969. *
  31970. * @type {Renderer}
  31971. */
  31972. this.nodeFrame = new NodeFrame();
  31973. /**
  31974. * A cache for managing node builder states.
  31975. *
  31976. * @type {Map<Number,NodeBuilderState>}
  31977. */
  31978. this.nodeBuilderCache = new Map();
  31979. /**
  31980. * A cache for managing data cache key data.
  31981. *
  31982. * @type {ChainMap}
  31983. */
  31984. this.callHashCache = new ChainMap();
  31985. /**
  31986. * A cache for managing node uniforms group data.
  31987. *
  31988. * @type {ChainMap}
  31989. */
  31990. this.groupsData = new ChainMap();
  31991. /**
  31992. * A cache for managing node objects of
  31993. * scene properties like fog or environments.
  31994. *
  31995. * @type {Object<String,WeakMap>}
  31996. */
  31997. this.cacheLib = {};
  31998. }
  31999. /**
  32000. * Returns `true` if the given node uniforms group must be updated or not.
  32001. *
  32002. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  32003. * @return {Boolean} Whether the node uniforms group requires an update or not.
  32004. */
  32005. updateGroup( nodeUniformsGroup ) {
  32006. const groupNode = nodeUniformsGroup.groupNode;
  32007. const name = groupNode.name;
  32008. // objectGroup is always updated
  32009. if ( name === objectGroup.name ) return true;
  32010. // renderGroup is updated once per render/compute call
  32011. if ( name === renderGroup.name ) {
  32012. const uniformsGroupData = this.get( nodeUniformsGroup );
  32013. const renderId = this.nodeFrame.renderId;
  32014. if ( uniformsGroupData.renderId !== renderId ) {
  32015. uniformsGroupData.renderId = renderId;
  32016. return true;
  32017. }
  32018. return false;
  32019. }
  32020. // frameGroup is updated once per frame
  32021. if ( name === frameGroup.name ) {
  32022. const uniformsGroupData = this.get( nodeUniformsGroup );
  32023. const frameId = this.nodeFrame.frameId;
  32024. if ( uniformsGroupData.frameId !== frameId ) {
  32025. uniformsGroupData.frameId = frameId;
  32026. return true;
  32027. }
  32028. return false;
  32029. }
  32030. // other groups are updated just when groupNode.needsUpdate is true
  32031. _chainKeys$2[ 0 ] = groupNode;
  32032. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  32033. let groupData = this.groupsData.get( _chainKeys$2 );
  32034. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  32035. _chainKeys$2.length = 0;
  32036. if ( groupData.version !== groupNode.version ) {
  32037. groupData.version = groupNode.version;
  32038. return true;
  32039. }
  32040. return false;
  32041. }
  32042. /**
  32043. * Returns the cache key for the given render object.
  32044. *
  32045. * @param {RenderObject} renderObject - The render object.
  32046. * @return {Number} The cache key.
  32047. */
  32048. getForRenderCacheKey( renderObject ) {
  32049. return renderObject.initialCacheKey;
  32050. }
  32051. /**
  32052. * Returns a node builder state for the given render object.
  32053. *
  32054. * @param {RenderObject} renderObject - The render object.
  32055. * @return {NodeBuilderState} The node builder state.
  32056. */
  32057. getForRender( renderObject ) {
  32058. const renderObjectData = this.get( renderObject );
  32059. let nodeBuilderState = renderObjectData.nodeBuilderState;
  32060. if ( nodeBuilderState === undefined ) {
  32061. const { nodeBuilderCache } = this;
  32062. const cacheKey = this.getForRenderCacheKey( renderObject );
  32063. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  32064. if ( nodeBuilderState === undefined ) {
  32065. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  32066. nodeBuilder.scene = renderObject.scene;
  32067. nodeBuilder.material = renderObject.material;
  32068. nodeBuilder.camera = renderObject.camera;
  32069. nodeBuilder.context.material = renderObject.material;
  32070. nodeBuilder.lightsNode = renderObject.lightsNode;
  32071. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  32072. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  32073. nodeBuilder.clippingContext = renderObject.clippingContext;
  32074. nodeBuilder.build();
  32075. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32076. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  32077. }
  32078. nodeBuilderState.usedTimes ++;
  32079. renderObjectData.nodeBuilderState = nodeBuilderState;
  32080. }
  32081. return nodeBuilderState;
  32082. }
  32083. /**
  32084. * Deletes the given object from the internal data map
  32085. *
  32086. * @param {Any} object - The object to delete.
  32087. * @return {Object?} The deleted dictionary.
  32088. */
  32089. delete( object ) {
  32090. if ( object.isRenderObject ) {
  32091. const nodeBuilderState = this.get( object ).nodeBuilderState;
  32092. nodeBuilderState.usedTimes --;
  32093. if ( nodeBuilderState.usedTimes === 0 ) {
  32094. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  32095. }
  32096. }
  32097. return super.delete( object );
  32098. }
  32099. /**
  32100. * Returns a node builder state for the given compute node.
  32101. *
  32102. * @param {Node} computeNode - The compute node.
  32103. * @return {NodeBuilderState} The node builder state.
  32104. */
  32105. getForCompute( computeNode ) {
  32106. const computeData = this.get( computeNode );
  32107. let nodeBuilderState = computeData.nodeBuilderState;
  32108. if ( nodeBuilderState === undefined ) {
  32109. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  32110. nodeBuilder.build();
  32111. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32112. computeData.nodeBuilderState = nodeBuilderState;
  32113. }
  32114. return nodeBuilderState;
  32115. }
  32116. /**
  32117. * Creates a node builder state for the given node builder.
  32118. *
  32119. * @private
  32120. * @param {NodeBuilder} nodeBuilder - The node builder.
  32121. * @return {NodeBuilderState} The node builder state.
  32122. */
  32123. _createNodeBuilderState( nodeBuilder ) {
  32124. return new NodeBuilderState(
  32125. nodeBuilder.vertexShader,
  32126. nodeBuilder.fragmentShader,
  32127. nodeBuilder.computeShader,
  32128. nodeBuilder.getAttributesArray(),
  32129. nodeBuilder.getBindings(),
  32130. nodeBuilder.updateNodes,
  32131. nodeBuilder.updateBeforeNodes,
  32132. nodeBuilder.updateAfterNodes,
  32133. nodeBuilder.monitor,
  32134. nodeBuilder.transforms
  32135. );
  32136. }
  32137. /**
  32138. * Returns an environment node for the current configured
  32139. * scene environment.
  32140. *
  32141. * @param {Scene} scene - The scene.
  32142. * @return {Node} A node representing the current scene environment.
  32143. */
  32144. getEnvironmentNode( scene ) {
  32145. this.updateEnvironment( scene );
  32146. let environmentNode = null;
  32147. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  32148. environmentNode = scene.environmentNode;
  32149. } else {
  32150. const sceneData = this.get( scene );
  32151. if ( sceneData.environmentNode ) {
  32152. environmentNode = sceneData.environmentNode;
  32153. }
  32154. }
  32155. return environmentNode;
  32156. }
  32157. /**
  32158. * Returns a background node for the current configured
  32159. * scene background.
  32160. *
  32161. * @param {Scene} scene - The scene.
  32162. * @return {Node} A node representing the current scene background.
  32163. */
  32164. getBackgroundNode( scene ) {
  32165. this.updateBackground( scene );
  32166. let backgroundNode = null;
  32167. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  32168. backgroundNode = scene.backgroundNode;
  32169. } else {
  32170. const sceneData = this.get( scene );
  32171. if ( sceneData.backgroundNode ) {
  32172. backgroundNode = sceneData.backgroundNode;
  32173. }
  32174. }
  32175. return backgroundNode;
  32176. }
  32177. /**
  32178. * Returns a fog node for the current configured scene fog.
  32179. *
  32180. * @param {Scene} scene - The scene.
  32181. * @return {Node} A node representing the current scene fog.
  32182. */
  32183. getFogNode( scene ) {
  32184. this.updateFog( scene );
  32185. return scene.fogNode || this.get( scene ).fogNode || null;
  32186. }
  32187. /**
  32188. * Returns a cache key for the given scene and lights node.
  32189. * This key is used by `RenderObject` as a part of the dynamic
  32190. * cache key (a key that must be checked every time the render
  32191. * objects is drawn).
  32192. *
  32193. * @param {Scene} scene - The scene.
  32194. * @param {LightsNode} lightsNode - The lights node.
  32195. * @return {Number} The cache key.
  32196. */
  32197. getCacheKey( scene, lightsNode ) {
  32198. _chainKeys$2[ 0 ] = scene;
  32199. _chainKeys$2[ 1 ] = lightsNode;
  32200. const callId = this.renderer.info.calls;
  32201. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  32202. if ( cacheKeyData.callId !== callId ) {
  32203. const environmentNode = this.getEnvironmentNode( scene );
  32204. const fogNode = this.getFogNode( scene );
  32205. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  32206. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  32207. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  32208. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  32209. cacheKeyData.callId = callId;
  32210. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  32211. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  32212. _cacheKeyValues.length = 0;
  32213. }
  32214. _chainKeys$2.length = 0;
  32215. return cacheKeyData.cacheKey;
  32216. }
  32217. /**
  32218. * A boolean that indicates whether tone mapping should be enabled
  32219. * or not.
  32220. *
  32221. * @type {Boolean}
  32222. */
  32223. get isToneMappingState() {
  32224. return this.renderer.getRenderTarget() ? false : true;
  32225. }
  32226. /**
  32227. * If a scene background is configured, this method makes sure to
  32228. * represent the background with a corresponding node-based implementation.
  32229. *
  32230. * @param {Scene} scene - The scene.
  32231. */
  32232. updateBackground( scene ) {
  32233. const sceneData = this.get( scene );
  32234. const background = scene.background;
  32235. if ( background ) {
  32236. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  32237. if ( sceneData.background !== background || forceUpdate ) {
  32238. const backgroundNode = this.getCacheNode( 'background', background, () => {
  32239. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  32240. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  32241. return pmremTexture( background );
  32242. } else {
  32243. let envMap;
  32244. if ( background.isCubeTexture === true ) {
  32245. envMap = cubeTexture( background );
  32246. } else {
  32247. envMap = texture( background );
  32248. }
  32249. return cubeMapNode( envMap );
  32250. }
  32251. } else if ( background.isTexture === true ) {
  32252. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  32253. } else if ( background.isColor !== true ) {
  32254. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  32255. }
  32256. }, forceUpdate );
  32257. sceneData.backgroundNode = backgroundNode;
  32258. sceneData.background = background;
  32259. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  32260. }
  32261. } else if ( sceneData.backgroundNode ) {
  32262. delete sceneData.backgroundNode;
  32263. delete sceneData.background;
  32264. }
  32265. }
  32266. /**
  32267. * This method is part of the caching of nodes which are used to represents the
  32268. * scene's background, fog or environment.
  32269. *
  32270. * @param {String} type - The type of object to cache.
  32271. * @param {Object} object - The object.
  32272. * @param {Function} callback - A callback that produces a node representation for the given object.
  32273. * @param {Boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  32274. * @return {Node} The node representation.
  32275. */
  32276. getCacheNode( type, object, callback, forceUpdate = false ) {
  32277. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  32278. let node = nodeCache.get( object );
  32279. if ( node === undefined || forceUpdate ) {
  32280. node = callback();
  32281. nodeCache.set( object, node );
  32282. }
  32283. return node;
  32284. }
  32285. /**
  32286. * If a scene fog is configured, this method makes sure to
  32287. * represent the fog with a corresponding node-based implementation.
  32288. *
  32289. * @param {Scene} scene - The scene.
  32290. */
  32291. updateFog( scene ) {
  32292. const sceneData = this.get( scene );
  32293. const sceneFog = scene.fog;
  32294. if ( sceneFog ) {
  32295. if ( sceneData.fog !== sceneFog ) {
  32296. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  32297. if ( sceneFog.isFogExp2 ) {
  32298. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32299. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  32300. return fog( color, densityFogFactor( density ) );
  32301. } else if ( sceneFog.isFog ) {
  32302. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32303. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  32304. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  32305. return fog( color, rangeFogFactor( near, far ) );
  32306. } else {
  32307. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  32308. }
  32309. } );
  32310. sceneData.fogNode = fogNode;
  32311. sceneData.fog = sceneFog;
  32312. }
  32313. } else {
  32314. delete sceneData.fogNode;
  32315. delete sceneData.fog;
  32316. }
  32317. }
  32318. /**
  32319. * If a scene environment is configured, this method makes sure to
  32320. * represent the environment with a corresponding node-based implementation.
  32321. *
  32322. * @param {Scene} scene - The scene.
  32323. */
  32324. updateEnvironment( scene ) {
  32325. const sceneData = this.get( scene );
  32326. const environment = scene.environment;
  32327. if ( environment ) {
  32328. if ( sceneData.environment !== environment ) {
  32329. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  32330. if ( environment.isCubeTexture === true ) {
  32331. return cubeTexture( environment );
  32332. } else if ( environment.isTexture === true ) {
  32333. return texture( environment );
  32334. } else {
  32335. console.error( 'Nodes: Unsupported environment configuration.', environment );
  32336. }
  32337. } );
  32338. sceneData.environmentNode = environmentNode;
  32339. sceneData.environment = environment;
  32340. }
  32341. } else if ( sceneData.environmentNode ) {
  32342. delete sceneData.environmentNode;
  32343. delete sceneData.environment;
  32344. }
  32345. }
  32346. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  32347. const nodeFrame = this.nodeFrame;
  32348. nodeFrame.renderer = renderer;
  32349. nodeFrame.scene = scene;
  32350. nodeFrame.object = object;
  32351. nodeFrame.camera = camera;
  32352. nodeFrame.material = material;
  32353. return nodeFrame;
  32354. }
  32355. getNodeFrameForRender( renderObject ) {
  32356. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  32357. }
  32358. /**
  32359. * Returns the current output cache key.
  32360. *
  32361. * @return {String} The output cache key.
  32362. */
  32363. getOutputCacheKey() {
  32364. const renderer = this.renderer;
  32365. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  32366. }
  32367. /**
  32368. * Checks if the output configuration (tone mapping and color space) for
  32369. * the given target has changed.
  32370. *
  32371. * @param {Texture} outputTarget - The output target.
  32372. * @return {Boolean} Whether the output configuration has changed or not.
  32373. */
  32374. hasOutputChange( outputTarget ) {
  32375. const cacheKey = _outputNodeMap.get( outputTarget );
  32376. return cacheKey !== this.getOutputCacheKey();
  32377. }
  32378. /**
  32379. * Returns a node that represents the output configuration (tone mapping and
  32380. * color space) for the current target.
  32381. *
  32382. * @param {Texture} outputTarget - The output target.
  32383. * @return {Node} The output node.
  32384. */
  32385. getOutputNode( outputTarget ) {
  32386. const renderer = this.renderer;
  32387. const cacheKey = this.getOutputCacheKey();
  32388. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  32389. _outputNodeMap.set( outputTarget, cacheKey );
  32390. return output;
  32391. }
  32392. /**
  32393. * Triggers the call of `updateBefore()` methods
  32394. * for all nodes of the given render object.
  32395. *
  32396. * @param {RenderObject} renderObject - The render object.
  32397. */
  32398. updateBefore( renderObject ) {
  32399. const nodeBuilder = renderObject.getNodeBuilderState();
  32400. for ( const node of nodeBuilder.updateBeforeNodes ) {
  32401. // update frame state for each node
  32402. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  32403. }
  32404. }
  32405. /**
  32406. * Triggers the call of `updateAfter()` methods
  32407. * for all nodes of the given render object.
  32408. *
  32409. * @param {RenderObject} renderObject - The render object.
  32410. */
  32411. updateAfter( renderObject ) {
  32412. const nodeBuilder = renderObject.getNodeBuilderState();
  32413. for ( const node of nodeBuilder.updateAfterNodes ) {
  32414. // update frame state for each node
  32415. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  32416. }
  32417. }
  32418. /**
  32419. * Triggers the call of `update()` methods
  32420. * for all nodes of the given compute node.
  32421. *
  32422. * @param {Node} computeNode - The compute node.
  32423. */
  32424. updateForCompute( computeNode ) {
  32425. const nodeFrame = this.getNodeFrame();
  32426. const nodeBuilder = this.getForCompute( computeNode );
  32427. for ( const node of nodeBuilder.updateNodes ) {
  32428. nodeFrame.updateNode( node );
  32429. }
  32430. }
  32431. /**
  32432. * Triggers the call of `update()` methods
  32433. * for all nodes of the given compute node.
  32434. *
  32435. * @param {RenderObject} renderObject - The render object.
  32436. */
  32437. updateForRender( renderObject ) {
  32438. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32439. const nodeBuilder = renderObject.getNodeBuilderState();
  32440. for ( const node of nodeBuilder.updateNodes ) {
  32441. nodeFrame.updateNode( node );
  32442. }
  32443. }
  32444. /**
  32445. * Returns `true` if the given render object requires a refresh.
  32446. *
  32447. * @param {RenderObject} renderObject - The render object.
  32448. * @return {Boolean} Whether the given render object requires a refresh or not.
  32449. */
  32450. needsRefresh( renderObject ) {
  32451. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32452. const monitor = renderObject.getMonitor();
  32453. return monitor.needsRefresh( renderObject, nodeFrame );
  32454. }
  32455. /**
  32456. * Frees the internal resources.
  32457. */
  32458. dispose() {
  32459. super.dispose();
  32460. this.nodeFrame = new NodeFrame();
  32461. this.nodeBuilderCache = new Map();
  32462. this.cacheLib = {};
  32463. }
  32464. }
  32465. const _plane = /*@__PURE__*/ new Plane();
  32466. /**
  32467. * Represents the state that is used to perform clipping via clipping planes.
  32468. * There is a default clipping context for each render context. When the
  32469. * scene holds instances of `ClippingGroup`, there will be a context for each
  32470. * group.
  32471. *
  32472. * @private
  32473. */
  32474. class ClippingContext {
  32475. /**
  32476. * Constructs a new clipping context.
  32477. *
  32478. * @param {ClippingContext?} [parentContext=null] - A reference to the parent clipping context.
  32479. */
  32480. constructor( parentContext = null ) {
  32481. /**
  32482. * The clipping context's version.
  32483. *
  32484. * @type {Number}
  32485. * @readonly
  32486. */
  32487. this.version = 0;
  32488. /**
  32489. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  32490. *
  32491. * @type {Boolean?}
  32492. * @default null
  32493. */
  32494. this.clipIntersection = null;
  32495. /**
  32496. * The clipping context's cache key.
  32497. *
  32498. * @type {String}
  32499. */
  32500. this.cacheKey = '';
  32501. /**
  32502. * Whether the shadow pass is active or not.
  32503. *
  32504. * @type {Boolean}
  32505. * @default false
  32506. */
  32507. this.shadowPass = false;
  32508. /**
  32509. * The view normal matrix.
  32510. *
  32511. * @type {Matrix3}
  32512. */
  32513. this.viewNormalMatrix = new Matrix3();
  32514. /**
  32515. * Internal cache for maintaining clipping contexts.
  32516. *
  32517. * @type {WeakMap<ClippingGroup,ClippingContext>}
  32518. */
  32519. this.clippingGroupContexts = new WeakMap();
  32520. /**
  32521. * The intersection planes.
  32522. *
  32523. * @type {Array<Vector4>}
  32524. */
  32525. this.intersectionPlanes = [];
  32526. /**
  32527. * The intersection planes.
  32528. *
  32529. * @type {Array<Vector4>}
  32530. */
  32531. this.unionPlanes = [];
  32532. /**
  32533. * The version of the clipping context's parent context.
  32534. *
  32535. * @type {Number?}
  32536. * @readonly
  32537. */
  32538. this.parentVersion = null;
  32539. if ( parentContext !== null ) {
  32540. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  32541. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  32542. this.shadowPass = parentContext.shadowPass;
  32543. this.viewMatrix = parentContext.viewMatrix;
  32544. }
  32545. }
  32546. /**
  32547. * Projects the given source clipping planes and writes the result into the
  32548. * destination array.
  32549. *
  32550. * @param {Array<Plane>} source - The source clipping planes.
  32551. * @param {Array<Vector4>} destination - The destination.
  32552. * @param {Number} offset - The offset.
  32553. */
  32554. projectPlanes( source, destination, offset ) {
  32555. const l = source.length;
  32556. for ( let i = 0; i < l; i ++ ) {
  32557. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  32558. const v = destination[ offset + i ];
  32559. const normal = _plane.normal;
  32560. v.x = - normal.x;
  32561. v.y = - normal.y;
  32562. v.z = - normal.z;
  32563. v.w = _plane.constant;
  32564. }
  32565. }
  32566. /**
  32567. * Updates the root clipping context of a scene.
  32568. *
  32569. * @param {Scene} scene - The scene.
  32570. * @param {Camera} camera - The camera that is used to render the scene.
  32571. */
  32572. updateGlobal( scene, camera ) {
  32573. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  32574. this.viewMatrix = camera.matrixWorldInverse;
  32575. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  32576. }
  32577. /**
  32578. * Updates the clipping context.
  32579. *
  32580. * @param {ClippingContext} parentContext - The parent context.
  32581. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  32582. */
  32583. update( parentContext, clippingGroup ) {
  32584. let update = false;
  32585. if ( parentContext.version !== this.parentVersion ) {
  32586. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  32587. this.unionPlanes = Array.from( parentContext.unionPlanes );
  32588. this.parentVersion = parentContext.version;
  32589. }
  32590. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  32591. this.clipIntersection = clippingGroup.clipIntersection;
  32592. if ( this.clipIntersection ) {
  32593. this.unionPlanes.length = parentContext.unionPlanes.length;
  32594. } else {
  32595. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  32596. }
  32597. }
  32598. const srcClippingPlanes = clippingGroup.clippingPlanes;
  32599. const l = srcClippingPlanes.length;
  32600. let dstClippingPlanes;
  32601. let offset;
  32602. if ( this.clipIntersection ) {
  32603. dstClippingPlanes = this.intersectionPlanes;
  32604. offset = parentContext.intersectionPlanes.length;
  32605. } else {
  32606. dstClippingPlanes = this.unionPlanes;
  32607. offset = parentContext.unionPlanes.length;
  32608. }
  32609. if ( dstClippingPlanes.length !== offset + l ) {
  32610. dstClippingPlanes.length = offset + l;
  32611. for ( let i = 0; i < l; i ++ ) {
  32612. dstClippingPlanes[ offset + i ] = new Vector4();
  32613. }
  32614. update = true;
  32615. }
  32616. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  32617. if ( update ) {
  32618. this.version ++;
  32619. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  32620. }
  32621. }
  32622. /**
  32623. * Returns a clipping context for the given clipping group.
  32624. *
  32625. * @param {ClippingGroup} clippingGroup - The clipping group.
  32626. * @return {ClippingContext} The clipping context.
  32627. */
  32628. getGroupContext( clippingGroup ) {
  32629. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  32630. let context = this.clippingGroupContexts.get( clippingGroup );
  32631. if ( context === undefined ) {
  32632. context = new ClippingContext( this );
  32633. this.clippingGroupContexts.set( clippingGroup, context );
  32634. }
  32635. context.update( this, clippingGroup );
  32636. return context;
  32637. }
  32638. /**
  32639. * The count of union clipping planes.
  32640. *
  32641. * @type {Number}
  32642. * @readonly
  32643. */
  32644. get unionClippingCount() {
  32645. return this.unionPlanes.length;
  32646. }
  32647. }
  32648. /**
  32649. * This module is used to represent render bundles inside the renderer
  32650. * for further processing.
  32651. *
  32652. * @private
  32653. */
  32654. class RenderBundle {
  32655. /**
  32656. * Constructs a new bundle group.
  32657. *
  32658. * @param {BundleGroup} bundleGroup - The bundle group.
  32659. * @param {Camera} camera - The camera the bundle group is rendered with.
  32660. */
  32661. constructor( bundleGroup, camera ) {
  32662. this.bundleGroup = bundleGroup;
  32663. this.camera = camera;
  32664. }
  32665. }
  32666. const _chainKeys$1 = [];
  32667. /**
  32668. * This renderer module manages render bundles.
  32669. *
  32670. * @private
  32671. */
  32672. class RenderBundles {
  32673. /**
  32674. * Constructs a new render bundle management component.
  32675. */
  32676. constructor() {
  32677. /**
  32678. * A chain map for maintaining the render bundles.
  32679. *
  32680. * @type {ChainMap}
  32681. */
  32682. this.bundles = new ChainMap();
  32683. }
  32684. /**
  32685. * Returns a render bundle for the given bundle group and camera.
  32686. *
  32687. * @param {BundleGroup} bundleGroup - The bundle group.
  32688. * @param {Camera} camera - The camera the bundle group is rendered with.
  32689. * @return {RenderBundle} The render bundle.
  32690. */
  32691. get( bundleGroup, camera ) {
  32692. const bundles = this.bundles;
  32693. _chainKeys$1[ 0 ] = bundleGroup;
  32694. _chainKeys$1[ 1 ] = camera;
  32695. let bundle = bundles.get( _chainKeys$1 );
  32696. if ( bundle === undefined ) {
  32697. bundle = new RenderBundle( bundleGroup, camera );
  32698. bundles.set( _chainKeys$1, bundle );
  32699. }
  32700. _chainKeys$1.length = 0;
  32701. return bundle;
  32702. }
  32703. /**
  32704. * Frees all internal resources.
  32705. */
  32706. dispose() {
  32707. this.bundles = new ChainMap();
  32708. }
  32709. }
  32710. /**
  32711. * The purpose of a node library is to assign node implementations
  32712. * to existing library features. In `WebGPURenderer` lights, materials
  32713. * which are not based on `NodeMaterial` as well as tone mapping techniques
  32714. * are implemented with node-based modules.
  32715. *
  32716. * @private
  32717. */
  32718. class NodeLibrary {
  32719. /**
  32720. * Constructs a new node library.
  32721. */
  32722. constructor() {
  32723. /**
  32724. * A weak map that maps lights to light nodes.
  32725. *
  32726. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  32727. */
  32728. this.lightNodes = new WeakMap();
  32729. /**
  32730. * A map that maps materials to node materials.
  32731. *
  32732. * @type {WeakMap<String,NodeMaterial.constructor>}
  32733. */
  32734. this.materialNodes = new Map();
  32735. /**
  32736. * A map that maps tone mapping techniques (constants)
  32737. * to tone mapping node functions.
  32738. *
  32739. * @type {WeakMap<Number,Function>}
  32740. */
  32741. this.toneMappingNodes = new Map();
  32742. }
  32743. /**
  32744. * Returns a matching node material instance for the given material object.
  32745. *
  32746. * This method also assigns/copies the properties of the given material object
  32747. * to the node material. This is done to make sure the current material
  32748. * configuration carries over to the node version.
  32749. *
  32750. * @param {Material} material - A material.
  32751. * @return {NodeMaterial} The corresponding node material.
  32752. */
  32753. fromMaterial( material ) {
  32754. if ( material.isNodeMaterial ) return material;
  32755. let nodeMaterial = null;
  32756. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  32757. if ( nodeMaterialClass !== null ) {
  32758. nodeMaterial = new nodeMaterialClass();
  32759. for ( const key in material ) {
  32760. nodeMaterial[ key ] = material[ key ];
  32761. }
  32762. }
  32763. return nodeMaterial;
  32764. }
  32765. /**
  32766. * Adds a tone mapping node function for a tone mapping technique (constant).
  32767. *
  32768. * @param {Function} toneMappingNode - The tone mapping node function.
  32769. * @param {Number} toneMapping - The tone mapping.
  32770. */
  32771. addToneMapping( toneMappingNode, toneMapping ) {
  32772. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  32773. }
  32774. /**
  32775. * Returns a tone mapping node function for a tone mapping technique (constant).
  32776. *
  32777. * @param {Number} toneMapping - The tone mapping.
  32778. * @return {Function?} The tone mapping node function. Returns `null` if no node function is found.
  32779. */
  32780. getToneMappingFunction( toneMapping ) {
  32781. return this.toneMappingNodes.get( toneMapping ) || null;
  32782. }
  32783. /**
  32784. * Returns a node material class definition for a material type.
  32785. *
  32786. * @param {String} materialType - The material type.
  32787. * @return {NodeMaterial.constructor?} The node material class definition. Returns `null` if no node material is found.
  32788. */
  32789. getMaterialNodeClass( materialType ) {
  32790. return this.materialNodes.get( materialType ) || null;
  32791. }
  32792. /**
  32793. * Adds a node material class definition for a given material type.
  32794. *
  32795. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  32796. * @param {String} materialClassType - The material type.
  32797. */
  32798. addMaterial( materialNodeClass, materialClassType ) {
  32799. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  32800. }
  32801. /**
  32802. * Returns a light node class definition for a light class definition.
  32803. *
  32804. * @param {Light.constructor} light - The light class definition.
  32805. * @return {AnalyticLightNode.constructor?} The light node class definition. Returns `null` if no light node is found.
  32806. */
  32807. getLightNodeClass( light ) {
  32808. return this.lightNodes.get( light ) || null;
  32809. }
  32810. /**
  32811. * Adds a light node class definition for a given light class definition.
  32812. *
  32813. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  32814. * @param {Light.constructor} lightClass - The light class definition.
  32815. */
  32816. addLight( lightNodeClass, lightClass ) {
  32817. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  32818. }
  32819. /**
  32820. * Adds a node class definition for the given type to the provided type library.
  32821. *
  32822. * @param {Any} nodeClass - The node class definition.
  32823. * @param {String} type - The object type.
  32824. * @param {Map} library - The type library.
  32825. */
  32826. addType( nodeClass, type, library ) {
  32827. if ( library.has( type ) ) {
  32828. console.warn( `Redefinition of node ${ type }` );
  32829. return;
  32830. }
  32831. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32832. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  32833. library.set( type, nodeClass );
  32834. }
  32835. /**
  32836. * Adds a node class definition for the given class definition to the provided type library.
  32837. *
  32838. * @param {Any} nodeClass - The node class definition.
  32839. * @param {Any} baseClass - The class definition.
  32840. * @param {WeakMap} library - The type library.
  32841. */
  32842. addClass( nodeClass, baseClass, library ) {
  32843. if ( library.has( baseClass ) ) {
  32844. console.warn( `Redefinition of node ${ baseClass.name }` );
  32845. return;
  32846. }
  32847. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32848. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  32849. library.set( baseClass, nodeClass );
  32850. }
  32851. }
  32852. const _defaultLights = /*@__PURE__*/ new LightsNode();
  32853. const _chainKeys = [];
  32854. /**
  32855. * This renderer module manages the lights nodes which are unique
  32856. * per scene and camera combination.
  32857. *
  32858. * The lights node itself is later configured in the render list
  32859. * with the actual lights from the scene.
  32860. *
  32861. * @private
  32862. * @augments ChainMap
  32863. */
  32864. class Lighting extends ChainMap {
  32865. /**
  32866. * Constructs a lighting management component.
  32867. */
  32868. constructor() {
  32869. super();
  32870. }
  32871. /**
  32872. * Creates a new lights node for the given array of lights.
  32873. *
  32874. * @param {Array<Light>} lights - The render object.
  32875. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  32876. */
  32877. createNode( lights = [] ) {
  32878. return new LightsNode().setLights( lights );
  32879. }
  32880. /**
  32881. * Returns a lights node for the given scene and camera.
  32882. *
  32883. * @param {Scene} scene - The scene.
  32884. * @param {Camera} camera - The camera.
  32885. * @return {LightsNode} The lights node.
  32886. */
  32887. getNode( scene, camera ) {
  32888. // ignore post-processing
  32889. if ( scene.isQuadMesh ) return _defaultLights;
  32890. _chainKeys[ 0 ] = scene;
  32891. _chainKeys[ 1 ] = camera;
  32892. let node = this.get( _chainKeys );
  32893. if ( node === undefined ) {
  32894. node = this.createNode();
  32895. this.set( _chainKeys, node );
  32896. }
  32897. _chainKeys.length = 0;
  32898. return node;
  32899. }
  32900. }
  32901. /** @module Renderer **/
  32902. const _scene = /*@__PURE__*/ new Scene();
  32903. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  32904. const _screen = /*@__PURE__*/ new Vector4();
  32905. const _frustum = /*@__PURE__*/ new Frustum();
  32906. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  32907. const _vector4 = /*@__PURE__*/ new Vector4();
  32908. /**
  32909. * Base class for renderers.
  32910. */
  32911. class Renderer {
  32912. /**
  32913. * Constructs a new renderer.
  32914. *
  32915. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  32916. * @param {Object} parameters - The configuration parameter.
  32917. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  32918. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  32919. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  32920. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  32921. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  32922. * @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
  32923. * to overwrite the default.
  32924. * @param {Function?} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  32925. */
  32926. constructor( backend, parameters = {} ) {
  32927. /**
  32928. * This flag can be used for type testing.
  32929. *
  32930. * @type {Boolean}
  32931. * @readonly
  32932. * @default true
  32933. */
  32934. this.isRenderer = true;
  32935. //
  32936. const {
  32937. logarithmicDepthBuffer = false,
  32938. alpha = true,
  32939. depth = true,
  32940. stencil = false,
  32941. antialias = false,
  32942. samples = 0,
  32943. getFallback = null
  32944. } = parameters;
  32945. /**
  32946. * A reference to the canvas element the renderer is drawing to.
  32947. * This value of this property will automatically be created by
  32948. * the renderer.
  32949. *
  32950. * @type {HTMLCanvasElement|OffscreenCanvas}
  32951. */
  32952. this.domElement = backend.getDomElement();
  32953. /**
  32954. * A reference to the current backend.
  32955. *
  32956. * @type {Backend}
  32957. */
  32958. this.backend = backend;
  32959. /**
  32960. * The number of MSAA samples.
  32961. *
  32962. * @type {Number}
  32963. * @default 0
  32964. */
  32965. this.samples = samples || ( antialias === true ) ? 4 : 0;
  32966. /**
  32967. * Whether the renderer should automatically clear the current rendering target
  32968. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  32969. * or the current bound render target (custom framebuffer).
  32970. *
  32971. * @type {Boolean}
  32972. * @default true
  32973. */
  32974. this.autoClear = true;
  32975. /**
  32976. * When `autoClear` is set to `true`, this property defines whether the renderer
  32977. * should clear the color buffer.
  32978. *
  32979. * @type {Boolean}
  32980. * @default true
  32981. */
  32982. this.autoClearColor = true;
  32983. /**
  32984. * When `autoClear` is set to `true`, this property defines whether the renderer
  32985. * should clear the depth buffer.
  32986. *
  32987. * @type {Boolean}
  32988. * @default true
  32989. */
  32990. this.autoClearDepth = true;
  32991. /**
  32992. * When `autoClear` is set to `true`, this property defines whether the renderer
  32993. * should clear the stencil buffer.
  32994. *
  32995. * @type {Boolean}
  32996. * @default true
  32997. */
  32998. this.autoClearStencil = true;
  32999. /**
  33000. * Whether the default framebuffer should be transparent or opaque.
  33001. *
  33002. * @type {Boolean}
  33003. * @default true
  33004. */
  33005. this.alpha = alpha;
  33006. /**
  33007. * Whether logarithmic depth buffer is enabled or not.
  33008. *
  33009. * @type {Boolean}
  33010. * @default false
  33011. */
  33012. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  33013. /**
  33014. * Defines the output color space of the renderer.
  33015. *
  33016. * @type {String}
  33017. * @default SRGBColorSpace
  33018. */
  33019. this.outputColorSpace = SRGBColorSpace;
  33020. /**
  33021. * Defines the tone mapping of the renderer.
  33022. *
  33023. * @type {Number}
  33024. * @default NoToneMapping
  33025. */
  33026. this.toneMapping = NoToneMapping;
  33027. /**
  33028. * Defines the tone mapping exposure.
  33029. *
  33030. * @type {Number}
  33031. * @default 1
  33032. */
  33033. this.toneMappingExposure = 1.0;
  33034. /**
  33035. * Whether the renderer should sort its render lists or not.
  33036. *
  33037. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  33038. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  33039. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  33040. * e.g. manually determining each object's rendering order.
  33041. *
  33042. * @type {Boolean}
  33043. * @default true
  33044. */
  33045. this.sortObjects = true;
  33046. /**
  33047. * Whether the default framebuffer should have a depth buffer or not.
  33048. *
  33049. * @type {Boolean}
  33050. * @default true
  33051. */
  33052. this.depth = depth;
  33053. /**
  33054. * Whether the default framebuffer should have a stencil buffer or not.
  33055. *
  33056. * @type {Boolean}
  33057. * @default false
  33058. */
  33059. this.stencil = stencil;
  33060. /**
  33061. * Holds a series of statistical information about the GPU memory
  33062. * and the rendering process. Useful for debugging and monitoring.
  33063. *
  33064. * @type {Info}
  33065. */
  33066. this.info = new Info();
  33067. this.nodes = {
  33068. modelViewMatrix: null,
  33069. modelNormalViewMatrix: null
  33070. };
  33071. /**
  33072. * The node library defines how certain library objects like materials, lights
  33073. * or tone mapping functions are mapped to node types. This is required since
  33074. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  33075. * be part of the scene graph, they are internally represented as nodes for
  33076. * further processing.
  33077. *
  33078. * @type {NodeLibrary}
  33079. */
  33080. this.library = new NodeLibrary();
  33081. /**
  33082. * A map-like data structure for managing lights.
  33083. *
  33084. * @type {Lighting}
  33085. */
  33086. this.lighting = new Lighting();
  33087. // internals
  33088. /**
  33089. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  33090. *
  33091. * @private
  33092. * @type {Function}
  33093. */
  33094. this._getFallback = getFallback;
  33095. /**
  33096. * The renderer's pixel ration.
  33097. *
  33098. * @private
  33099. * @type {Number}
  33100. * @default 1
  33101. */
  33102. this._pixelRatio = 1;
  33103. /**
  33104. * The width of the renderer's default framebuffer in logical pixel unit.
  33105. *
  33106. * @private
  33107. * @type {Number}
  33108. */
  33109. this._width = this.domElement.width;
  33110. /**
  33111. * The height of the renderer's default framebuffer in logical pixel unit.
  33112. *
  33113. * @private
  33114. * @type {Number}
  33115. */
  33116. this._height = this.domElement.height;
  33117. /**
  33118. * The viewport of the renderer in logical pixel unit.
  33119. *
  33120. * @private
  33121. * @type {Vector4}
  33122. */
  33123. this._viewport = new Vector4( 0, 0, this._width, this._height );
  33124. /**
  33125. * The scissor rectangle of the renderer in logical pixel unit.
  33126. *
  33127. * @private
  33128. * @type {Vector4}
  33129. */
  33130. this._scissor = new Vector4( 0, 0, this._width, this._height );
  33131. /**
  33132. * Whether the scissor test should be enabled or not.
  33133. *
  33134. * @private
  33135. * @type {Boolean}
  33136. */
  33137. this._scissorTest = false;
  33138. /**
  33139. * A reference to a renderer module for managing shader attributes.
  33140. *
  33141. * @private
  33142. * @type {Attributes?}
  33143. * @default null
  33144. */
  33145. this._attributes = null;
  33146. /**
  33147. * A reference to a renderer module for managing geometries.
  33148. *
  33149. * @private
  33150. * @type {Geometries?}
  33151. * @default null
  33152. */
  33153. this._geometries = null;
  33154. /**
  33155. * A reference to a renderer module for managing node related logic.
  33156. *
  33157. * @private
  33158. * @type {Nodes?}
  33159. * @default null
  33160. */
  33161. this._nodes = null;
  33162. /**
  33163. * A reference to a renderer module for managing the internal animation loop.
  33164. *
  33165. * @private
  33166. * @type {Animation?}
  33167. * @default null
  33168. */
  33169. this._animation = null;
  33170. /**
  33171. * A reference to a renderer module for managing shader program bindings.
  33172. *
  33173. * @private
  33174. * @type {Bindings?}
  33175. * @default null
  33176. */
  33177. this._bindings = null;
  33178. /**
  33179. * A reference to a renderer module for managing render objects.
  33180. *
  33181. * @private
  33182. * @type {RenderObjects?}
  33183. * @default null
  33184. */
  33185. this._objects = null;
  33186. /**
  33187. * A reference to a renderer module for managing render and compute pipelines.
  33188. *
  33189. * @private
  33190. * @type {Pipelines?}
  33191. * @default null
  33192. */
  33193. this._pipelines = null;
  33194. /**
  33195. * A reference to a renderer module for managing render bundles.
  33196. *
  33197. * @private
  33198. * @type {RenderBundles?}
  33199. * @default null
  33200. */
  33201. this._bundles = null;
  33202. /**
  33203. * A reference to a renderer module for managing render lists.
  33204. *
  33205. * @private
  33206. * @type {RenderLists?}
  33207. * @default null
  33208. */
  33209. this._renderLists = null;
  33210. /**
  33211. * A reference to a renderer module for managing render contexts.
  33212. *
  33213. * @private
  33214. * @type {RenderContexts?}
  33215. * @default null
  33216. */
  33217. this._renderContexts = null;
  33218. /**
  33219. * A reference to a renderer module for managing textures.
  33220. *
  33221. * @private
  33222. * @type {Textures?}
  33223. * @default null
  33224. */
  33225. this._textures = null;
  33226. /**
  33227. * A reference to a renderer module for backgrounds.
  33228. *
  33229. * @private
  33230. * @type {Background?}
  33231. * @default null
  33232. */
  33233. this._background = null;
  33234. /**
  33235. * This fullscreen quad is used for internal render passes
  33236. * like the tone mapping and color space output pass.
  33237. *
  33238. * @private
  33239. * @type {QuadMesh}
  33240. */
  33241. this._quad = new QuadMesh( new NodeMaterial() );
  33242. this._quad.material.name = 'Renderer_output';
  33243. /**
  33244. * A reference to the current render context.
  33245. *
  33246. * @private
  33247. * @type {RenderContext?}
  33248. * @default null
  33249. */
  33250. this._currentRenderContext = null;
  33251. /**
  33252. * A custom sort function for the opaque render list.
  33253. *
  33254. * @private
  33255. * @type {Function?}
  33256. * @default null
  33257. */
  33258. this._opaqueSort = null;
  33259. /**
  33260. * A custom sort function for the transparent render list.
  33261. *
  33262. * @private
  33263. * @type {Function?}
  33264. * @default null
  33265. */
  33266. this._transparentSort = null;
  33267. /**
  33268. * The framebuffer target.
  33269. *
  33270. * @private
  33271. * @type {RenderTarget?}
  33272. * @default null
  33273. */
  33274. this._frameBufferTarget = null;
  33275. const alphaClear = this.alpha === true ? 0 : 1;
  33276. /**
  33277. * The clear color value.
  33278. *
  33279. * @private
  33280. * @type {Color4}
  33281. */
  33282. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  33283. /**
  33284. * The clear depth value.
  33285. *
  33286. * @private
  33287. * @type {Number}
  33288. * @default 1
  33289. */
  33290. this._clearDepth = 1;
  33291. /**
  33292. * The clear stencil value.
  33293. *
  33294. * @private
  33295. * @type {Number}
  33296. * @default 0
  33297. */
  33298. this._clearStencil = 0;
  33299. /**
  33300. * The current render target.
  33301. *
  33302. * @private
  33303. * @type {RenderTarget?}
  33304. * @default null
  33305. */
  33306. this._renderTarget = null;
  33307. /**
  33308. * The active cube face.
  33309. *
  33310. * @private
  33311. * @type {Number}
  33312. * @default 0
  33313. */
  33314. this._activeCubeFace = 0;
  33315. /**
  33316. * The active mipmap level.
  33317. *
  33318. * @private
  33319. * @type {Number}
  33320. * @default 0
  33321. */
  33322. this._activeMipmapLevel = 0;
  33323. /**
  33324. * The MRT setting.
  33325. *
  33326. * @private
  33327. * @type {MRTNode?}
  33328. * @default null
  33329. */
  33330. this._mrt = null;
  33331. /**
  33332. * This function defines how a render object is going
  33333. * to be rendered.
  33334. *
  33335. * @private
  33336. * @type {Function?}
  33337. * @default null
  33338. */
  33339. this._renderObjectFunction = null;
  33340. /**
  33341. * Used to keep track of the current render object function.
  33342. *
  33343. * @private
  33344. * @type {Function?}
  33345. * @default null
  33346. */
  33347. this._currentRenderObjectFunction = null;
  33348. /**
  33349. * Used to keep track of the current render bundle.
  33350. *
  33351. * @private
  33352. * @type {RenderBundle?}
  33353. * @default null
  33354. */
  33355. this._currentRenderBundle = null;
  33356. /**
  33357. * Next to `_renderObjectFunction()`, this function provides another hook
  33358. * for influencing the render process of a render object. It is meant for internal
  33359. * use and only relevant for `compileAsync()` right now. Instead of using
  33360. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  33361. * a different function might be used which performs no draw but just the node
  33362. * and pipeline updates.
  33363. *
  33364. * @private
  33365. * @type {Function?}
  33366. * @default null
  33367. */
  33368. this._handleObjectFunction = this._renderObjectDirect;
  33369. /**
  33370. * Indicates whether the device has been lost or not. In WebGL terms, the device
  33371. * lost is considered as a context lost. When this is set to `true`, rendering
  33372. * isn't possible anymore.
  33373. *
  33374. * @private
  33375. * @type {Boolean}
  33376. * @default false
  33377. */
  33378. this._isDeviceLost = false;
  33379. /**
  33380. * A callback function that defines what should happen when a device/context lost occurs.
  33381. *
  33382. * @type {Function}
  33383. */
  33384. this.onDeviceLost = this._onDeviceLost;
  33385. /**
  33386. * Whether the renderer has been initialized or not.
  33387. *
  33388. * @private
  33389. * @type {Boolean}
  33390. * @default false
  33391. */
  33392. this._initialized = false;
  33393. /**
  33394. * A reference to the promise which initializes the renderer.
  33395. *
  33396. * @private
  33397. * @type {Promise?}
  33398. * @default null
  33399. */
  33400. this._initPromise = null;
  33401. /**
  33402. * An array of compilation promises which are used in `compileAsync()`.
  33403. *
  33404. * @private
  33405. * @type {Array<Promise>?}
  33406. * @default null
  33407. */
  33408. this._compilationPromises = null;
  33409. /**
  33410. * Whether the renderer should render transparent render objects or not.
  33411. *
  33412. * @type {Boolean}
  33413. * @default true
  33414. */
  33415. this.transparent = true;
  33416. /**
  33417. * Whether the renderer should render opaque render objects or not.
  33418. *
  33419. * @type {Boolean}
  33420. * @default true
  33421. */
  33422. this.opaque = true;
  33423. /**
  33424. * Shadow map configuration
  33425. * @typedef {Object} ShadowMapConfig
  33426. * @property {Boolean} enabled - Whether to globally enable shadows or not.
  33427. * @property {Number} type - The shadow map type.
  33428. */
  33429. /**
  33430. * The renderer's shadow configuration.
  33431. *
  33432. * @type {module:Renderer~ShadowMapConfig}
  33433. */
  33434. this.shadowMap = {
  33435. enabled: false,
  33436. type: PCFShadowMap
  33437. };
  33438. /**
  33439. * XR configuration.
  33440. * @typedef {Object} XRConfig
  33441. * @property {Boolean} enabled - Whether to globally enable XR or not.
  33442. */
  33443. /**
  33444. * The renderer's XR configuration.
  33445. *
  33446. * @type {module:Renderer~XRConfig}
  33447. */
  33448. this.xr = {
  33449. enabled: false
  33450. };
  33451. /**
  33452. * Debug configuration.
  33453. * @typedef {Object} DebugConfig
  33454. * @property {Boolean} checkShaderErrors - Whether shader errors should be checked or not.
  33455. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  33456. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  33457. */
  33458. /**
  33459. * The renderer's debug configuration.
  33460. *
  33461. * @type {module:Renderer~DebugConfig}
  33462. */
  33463. this.debug = {
  33464. checkShaderErrors: true,
  33465. onShaderError: null,
  33466. getShaderAsync: async ( scene, camera, object ) => {
  33467. await this.compileAsync( scene, camera );
  33468. const renderList = this._renderLists.get( scene, camera );
  33469. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  33470. const material = scene.overrideMaterial || object.material;
  33471. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  33472. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  33473. return { fragmentShader, vertexShader };
  33474. }
  33475. };
  33476. }
  33477. /**
  33478. * Initializes the renderer so it is ready for usage.
  33479. *
  33480. * @async
  33481. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  33482. */
  33483. async init() {
  33484. if ( this._initialized ) {
  33485. throw new Error( 'Renderer: Backend has already been initialized.' );
  33486. }
  33487. if ( this._initPromise !== null ) {
  33488. return this._initPromise;
  33489. }
  33490. this._initPromise = new Promise( async ( resolve, reject ) => {
  33491. let backend = this.backend;
  33492. try {
  33493. await backend.init( this );
  33494. } catch ( error ) {
  33495. if ( this._getFallback !== null ) {
  33496. // try the fallback
  33497. try {
  33498. this.backend = backend = this._getFallback( error );
  33499. await backend.init( this );
  33500. } catch ( error ) {
  33501. reject( error );
  33502. return;
  33503. }
  33504. } else {
  33505. reject( error );
  33506. return;
  33507. }
  33508. }
  33509. this._nodes = new Nodes( this, backend );
  33510. this._animation = new Animation( this._nodes, this.info );
  33511. this._attributes = new Attributes( backend );
  33512. this._background = new Background( this, this._nodes );
  33513. this._geometries = new Geometries( this._attributes, this.info );
  33514. this._textures = new Textures( this, backend, this.info );
  33515. this._pipelines = new Pipelines( backend, this._nodes );
  33516. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  33517. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  33518. this._renderLists = new RenderLists( this.lighting );
  33519. this._bundles = new RenderBundles();
  33520. this._renderContexts = new RenderContexts();
  33521. //
  33522. this._animation.start();
  33523. this._initialized = true;
  33524. resolve();
  33525. } );
  33526. return this._initPromise;
  33527. }
  33528. /**
  33529. * The coordinate system of the renderer. The value of this property
  33530. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  33531. * `THREE.WebGPUCoordinateSystem`.
  33532. *
  33533. * @readonly
  33534. * @type {Number}
  33535. */
  33536. get coordinateSystem() {
  33537. return this.backend.coordinateSystem;
  33538. }
  33539. /**
  33540. * Compiles all materials in the given scene. This can be useful to avoid a
  33541. * phenomenon which is called "shader compilation stutter", which occurs when
  33542. * rendering an object with a new shader for the first time.
  33543. *
  33544. * If you want to add a 3D object to an existing scene, use the third optional
  33545. * parameter for applying the target scene. Note that the (target) scene's lighting
  33546. * and environment must be configured before calling this method.
  33547. *
  33548. * @async
  33549. * @param {Object3D} scene - The scene or 3D object to precompile.
  33550. * @param {Camera} camera - The camera that is used to render the scene.
  33551. * @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.
  33552. * @return {Promise<Array>} A Promise that resolves when the compile has been finished.
  33553. */
  33554. async compileAsync( scene, camera, targetScene = null ) {
  33555. if ( this._isDeviceLost === true ) return;
  33556. if ( this._initialized === false ) await this.init();
  33557. // preserve render tree
  33558. const nodeFrame = this._nodes.nodeFrame;
  33559. const previousRenderId = nodeFrame.renderId;
  33560. const previousRenderContext = this._currentRenderContext;
  33561. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  33562. const previousCompilationPromises = this._compilationPromises;
  33563. //
  33564. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  33565. if ( targetScene === null ) targetScene = scene;
  33566. const renderTarget = this._renderTarget;
  33567. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  33568. const activeMipmapLevel = this._activeMipmapLevel;
  33569. const compilationPromises = [];
  33570. this._currentRenderContext = renderContext;
  33571. this._currentRenderObjectFunction = this.renderObject;
  33572. this._handleObjectFunction = this._createObjectPipeline;
  33573. this._compilationPromises = compilationPromises;
  33574. nodeFrame.renderId ++;
  33575. //
  33576. nodeFrame.update();
  33577. //
  33578. renderContext.depth = this.depth;
  33579. renderContext.stencil = this.stencil;
  33580. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  33581. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  33582. //
  33583. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  33584. //
  33585. const renderList = this._renderLists.get( scene, camera );
  33586. renderList.begin();
  33587. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  33588. // include lights from target scene
  33589. if ( targetScene !== scene ) {
  33590. targetScene.traverseVisible( function ( object ) {
  33591. if ( object.isLight && object.layers.test( camera.layers ) ) {
  33592. renderList.pushLight( object );
  33593. }
  33594. } );
  33595. }
  33596. renderList.finish();
  33597. //
  33598. if ( renderTarget !== null ) {
  33599. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  33600. const renderTargetData = this._textures.get( renderTarget );
  33601. renderContext.textures = renderTargetData.textures;
  33602. renderContext.depthTexture = renderTargetData.depthTexture;
  33603. } else {
  33604. renderContext.textures = null;
  33605. renderContext.depthTexture = null;
  33606. }
  33607. //
  33608. this._background.update( sceneRef, renderList, renderContext );
  33609. // process render lists
  33610. const opaqueObjects = renderList.opaque;
  33611. const transparentObjects = renderList.transparent;
  33612. const transparentDoublePassObjects = renderList.transparentDoublePass;
  33613. const lightsNode = renderList.lightsNode;
  33614. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  33615. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  33616. // restore render tree
  33617. nodeFrame.renderId = previousRenderId;
  33618. this._currentRenderContext = previousRenderContext;
  33619. this._currentRenderObjectFunction = previousRenderObjectFunction;
  33620. this._compilationPromises = previousCompilationPromises;
  33621. this._handleObjectFunction = this._renderObjectDirect;
  33622. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  33623. await Promise.all( compilationPromises );
  33624. }
  33625. /**
  33626. * Renders the scene in an async fashion.
  33627. *
  33628. * @async
  33629. * @param {Object3D} scene - The scene or 3D object to render.
  33630. * @param {Camera} camera - The camera.
  33631. * @return {Promise} A Promise that resolves when the render has been finished.
  33632. */
  33633. async renderAsync( scene, camera ) {
  33634. if ( this._initialized === false ) await this.init();
  33635. const renderContext = this._renderScene( scene, camera );
  33636. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  33637. }
  33638. /**
  33639. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  33640. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  33641. *
  33642. * @async
  33643. * @return {Promise} A Promise that resolves when synchronization has been finished.
  33644. */
  33645. async waitForGPU() {
  33646. await this.backend.waitForGPU();
  33647. }
  33648. /**
  33649. * Sets the given MRT configuration.
  33650. *
  33651. * @param {MRTNode} mrt - The MRT node to set.
  33652. * @return {Renderer} A reference to this renderer.
  33653. */
  33654. setMRT( mrt ) {
  33655. this._mrt = mrt;
  33656. return this;
  33657. }
  33658. /**
  33659. * Returns the MRT configuration.
  33660. *
  33661. * @return {MRTNode} The MRT configuration.
  33662. */
  33663. getMRT() {
  33664. return this._mrt;
  33665. }
  33666. /**
  33667. * Default implementation of the device lost callback.
  33668. *
  33669. * @private
  33670. * @param {Object} info - Information about the context lost.
  33671. */
  33672. _onDeviceLost( info ) {
  33673. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  33674. if ( info.reason ) {
  33675. errorMessage += `\nReason: ${info.reason}`;
  33676. }
  33677. console.error( errorMessage );
  33678. this._isDeviceLost = true;
  33679. }
  33680. /**
  33681. * Renders the given render bundle.
  33682. *
  33683. * @private
  33684. * @param {Object} bundle - Render bundle data.
  33685. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  33686. * @param {LightsNode} lightsNode - The current lights node.
  33687. */
  33688. _renderBundle( bundle, sceneRef, lightsNode ) {
  33689. const { bundleGroup, camera, renderList } = bundle;
  33690. const renderContext = this._currentRenderContext;
  33691. //
  33692. const renderBundle = this._bundles.get( bundleGroup, camera );
  33693. const renderBundleData = this.backend.get( renderBundle );
  33694. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  33695. //
  33696. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  33697. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  33698. renderBundleData.renderContexts.add( renderContext );
  33699. if ( renderBundleNeedsUpdate ) {
  33700. this.backend.beginBundle( renderContext );
  33701. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  33702. renderBundleData.renderObjects = [];
  33703. }
  33704. this._currentRenderBundle = renderBundle;
  33705. const opaqueObjects = renderList.opaque;
  33706. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  33707. this._currentRenderBundle = null;
  33708. //
  33709. this.backend.finishBundle( renderContext, renderBundle );
  33710. renderBundleData.version = bundleGroup.version;
  33711. } else {
  33712. const { renderObjects } = renderBundleData;
  33713. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  33714. const renderObject = renderObjects[ i ];
  33715. if ( this._nodes.needsRefresh( renderObject ) ) {
  33716. this._nodes.updateBefore( renderObject );
  33717. this._nodes.updateForRender( renderObject );
  33718. this._bindings.updateForRender( renderObject );
  33719. this._nodes.updateAfter( renderObject );
  33720. }
  33721. }
  33722. }
  33723. this.backend.addBundle( renderContext, renderBundle );
  33724. }
  33725. /**
  33726. * Renders the scene or 3D object with the given camera. This method can only be called
  33727. * if the renderer has been initialized.
  33728. *
  33729. * The target of the method is the default framebuffer (meaning the canvas)
  33730. * or alternatively a render target when specified via `setRenderTarget()`.
  33731. *
  33732. * @param {Object3D} scene - The scene or 3D object to render.
  33733. * @param {Camera} camera - The camera to render the scene with.
  33734. * @return {Promise?} A Promise that resolve when the scene has been rendered.
  33735. * Only returned when the renderer has not been initialized.
  33736. */
  33737. render( scene, camera ) {
  33738. if ( this._initialized === false ) {
  33739. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  33740. return this.renderAsync( scene, camera );
  33741. }
  33742. this._renderScene( scene, camera );
  33743. }
  33744. /**
  33745. * Returns an internal render target which is used when computing the output tone mapping
  33746. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  33747. * pass and not inline to achieve more correct results.
  33748. *
  33749. * @private
  33750. * @return {RenderTarget?} The render target. The method returns `null` if no output conversion should be applied.
  33751. */
  33752. _getFrameBufferTarget() {
  33753. const { currentToneMapping, currentColorSpace } = this;
  33754. const useToneMapping = currentToneMapping !== NoToneMapping;
  33755. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  33756. if ( useToneMapping === false && useColorSpace === false ) return null;
  33757. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  33758. const { depth, stencil } = this;
  33759. let frameBufferTarget = this._frameBufferTarget;
  33760. if ( frameBufferTarget === null ) {
  33761. frameBufferTarget = new RenderTarget( width, height, {
  33762. depthBuffer: depth,
  33763. stencilBuffer: stencil,
  33764. type: HalfFloatType, // FloatType
  33765. format: RGBAFormat,
  33766. colorSpace: LinearSRGBColorSpace,
  33767. generateMipmaps: false,
  33768. minFilter: LinearFilter,
  33769. magFilter: LinearFilter,
  33770. samples: this.samples
  33771. } );
  33772. frameBufferTarget.isPostProcessingRenderTarget = true;
  33773. this._frameBufferTarget = frameBufferTarget;
  33774. }
  33775. frameBufferTarget.depthBuffer = depth;
  33776. frameBufferTarget.stencilBuffer = stencil;
  33777. frameBufferTarget.setSize( width, height );
  33778. frameBufferTarget.viewport.copy( this._viewport );
  33779. frameBufferTarget.scissor.copy( this._scissor );
  33780. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  33781. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  33782. frameBufferTarget.scissorTest = this._scissorTest;
  33783. return frameBufferTarget;
  33784. }
  33785. /**
  33786. * Renders the scene or 3D object with the given camera.
  33787. *
  33788. * @private
  33789. * @param {Object3D} scene - The scene or 3D object to render.
  33790. * @param {Camera} camera - The camera to render the scene with.
  33791. * @param {Boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  33792. * @return {RenderContext} The current render context.
  33793. */
  33794. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  33795. if ( this._isDeviceLost === true ) return;
  33796. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  33797. // preserve render tree
  33798. const nodeFrame = this._nodes.nodeFrame;
  33799. const previousRenderId = nodeFrame.renderId;
  33800. const previousRenderContext = this._currentRenderContext;
  33801. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  33802. //
  33803. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  33804. const outputRenderTarget = this._renderTarget;
  33805. const activeCubeFace = this._activeCubeFace;
  33806. const activeMipmapLevel = this._activeMipmapLevel;
  33807. //
  33808. let renderTarget;
  33809. if ( frameBufferTarget !== null ) {
  33810. renderTarget = frameBufferTarget;
  33811. this.setRenderTarget( renderTarget );
  33812. } else {
  33813. renderTarget = outputRenderTarget;
  33814. }
  33815. //
  33816. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  33817. this._currentRenderContext = renderContext;
  33818. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  33819. //
  33820. this.info.calls ++;
  33821. this.info.render.calls ++;
  33822. this.info.render.frameCalls ++;
  33823. nodeFrame.renderId = this.info.calls;
  33824. //
  33825. const coordinateSystem = this.coordinateSystem;
  33826. if ( camera.coordinateSystem !== coordinateSystem ) {
  33827. camera.coordinateSystem = coordinateSystem;
  33828. camera.updateProjectionMatrix();
  33829. }
  33830. //
  33831. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  33832. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  33833. //
  33834. let viewport = this._viewport;
  33835. let scissor = this._scissor;
  33836. let pixelRatio = this._pixelRatio;
  33837. if ( renderTarget !== null ) {
  33838. viewport = renderTarget.viewport;
  33839. scissor = renderTarget.scissor;
  33840. pixelRatio = 1;
  33841. }
  33842. this.getDrawingBufferSize( _drawingBufferSize );
  33843. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  33844. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  33845. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  33846. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  33847. renderContext.viewportValue.width >>= activeMipmapLevel;
  33848. renderContext.viewportValue.height >>= activeMipmapLevel;
  33849. renderContext.viewportValue.minDepth = minDepth;
  33850. renderContext.viewportValue.maxDepth = maxDepth;
  33851. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  33852. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  33853. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  33854. renderContext.scissorValue.width >>= activeMipmapLevel;
  33855. renderContext.scissorValue.height >>= activeMipmapLevel;
  33856. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  33857. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  33858. //
  33859. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  33860. //
  33861. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33862. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  33863. const renderList = this._renderLists.get( scene, camera );
  33864. renderList.begin();
  33865. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  33866. renderList.finish();
  33867. if ( this.sortObjects === true ) {
  33868. renderList.sort( this._opaqueSort, this._transparentSort );
  33869. }
  33870. //
  33871. if ( renderTarget !== null ) {
  33872. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  33873. const renderTargetData = this._textures.get( renderTarget );
  33874. renderContext.textures = renderTargetData.textures;
  33875. renderContext.depthTexture = renderTargetData.depthTexture;
  33876. renderContext.width = renderTargetData.width;
  33877. renderContext.height = renderTargetData.height;
  33878. renderContext.renderTarget = renderTarget;
  33879. renderContext.depth = renderTarget.depthBuffer;
  33880. renderContext.stencil = renderTarget.stencilBuffer;
  33881. } else {
  33882. renderContext.textures = null;
  33883. renderContext.depthTexture = null;
  33884. renderContext.width = this.domElement.width;
  33885. renderContext.height = this.domElement.height;
  33886. renderContext.depth = this.depth;
  33887. renderContext.stencil = this.stencil;
  33888. }
  33889. renderContext.width >>= activeMipmapLevel;
  33890. renderContext.height >>= activeMipmapLevel;
  33891. renderContext.activeCubeFace = activeCubeFace;
  33892. renderContext.activeMipmapLevel = activeMipmapLevel;
  33893. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  33894. //
  33895. this._background.update( sceneRef, renderList, renderContext );
  33896. //
  33897. this.backend.beginRender( renderContext );
  33898. // process render lists
  33899. const {
  33900. bundles,
  33901. lightsNode,
  33902. transparentDoublePass: transparentDoublePassObjects,
  33903. transparent: transparentObjects,
  33904. opaque: opaqueObjects
  33905. } = renderList;
  33906. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  33907. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  33908. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  33909. // finish render pass
  33910. this.backend.finishRender( renderContext );
  33911. // restore render tree
  33912. nodeFrame.renderId = previousRenderId;
  33913. this._currentRenderContext = previousRenderContext;
  33914. this._currentRenderObjectFunction = previousRenderObjectFunction;
  33915. //
  33916. if ( frameBufferTarget !== null ) {
  33917. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  33918. const quad = this._quad;
  33919. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  33920. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  33921. quad.material.needsUpdate = true;
  33922. }
  33923. this._renderScene( quad, quad.camera, false );
  33924. }
  33925. //
  33926. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  33927. //
  33928. return renderContext;
  33929. }
  33930. /**
  33931. * Returns the maximum available anisotropy for texture filtering.
  33932. *
  33933. * @return {Number} The maximum available anisotropy.
  33934. */
  33935. getMaxAnisotropy() {
  33936. return this.backend.getMaxAnisotropy();
  33937. }
  33938. /**
  33939. * Returns the active cube face.
  33940. *
  33941. * @return {Number} The active cube face.
  33942. */
  33943. getActiveCubeFace() {
  33944. return this._activeCubeFace;
  33945. }
  33946. /**
  33947. * Returns the active mipmap level.
  33948. *
  33949. * @return {Number} The active mipmap level.
  33950. */
  33951. getActiveMipmapLevel() {
  33952. return this._activeMipmapLevel;
  33953. }
  33954. /**
  33955. * Applications are advised to always define the animation loop
  33956. * with this method and not manually with `requestAnimationFrame()`
  33957. * for best compatibility.
  33958. *
  33959. * @async
  33960. * @param {Function} callback - The application's animation loop.
  33961. * @return {Promise} A Promise that resolves when the set has been executed.
  33962. */
  33963. async setAnimationLoop( callback ) {
  33964. if ( this._initialized === false ) await this.init();
  33965. this._animation.setAnimationLoop( callback );
  33966. }
  33967. /**
  33968. * Can be used to transfer buffer data from a storage buffer attribute
  33969. * from the GPU to the CPU in context of compute shaders.
  33970. *
  33971. * @async
  33972. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  33973. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  33974. */
  33975. async getArrayBufferAsync( attribute ) {
  33976. return await this.backend.getArrayBufferAsync( attribute );
  33977. }
  33978. /**
  33979. * Returns the rendering context.
  33980. *
  33981. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  33982. */
  33983. getContext() {
  33984. return this.backend.getContext();
  33985. }
  33986. /**
  33987. * Returns the pixel ratio.
  33988. *
  33989. * @return {Number} The pixel ratio.
  33990. */
  33991. getPixelRatio() {
  33992. return this._pixelRatio;
  33993. }
  33994. /**
  33995. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  33996. *
  33997. * @param {Vector2} target - The method writes the result in this target object.
  33998. * @return {Vector2} The drawing buffer size.
  33999. */
  34000. getDrawingBufferSize( target ) {
  34001. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  34002. }
  34003. /**
  34004. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  34005. *
  34006. * @param {Vector2} target - The method writes the result in this target object.
  34007. * @return {Vector2} The drawing buffer size.
  34008. */
  34009. getSize( target ) {
  34010. return target.set( this._width, this._height );
  34011. }
  34012. /**
  34013. * Sets the given pixel ration and resizes the canvas if necessary.
  34014. *
  34015. * @param {Number} [value=1] - The pixel ratio.
  34016. */
  34017. setPixelRatio( value = 1 ) {
  34018. if ( this._pixelRatio === value ) return;
  34019. this._pixelRatio = value;
  34020. this.setSize( this._width, this._height, false );
  34021. }
  34022. /**
  34023. * This method allows to define the drawing buffer size by specifying
  34024. * width, height and pixel ratio all at once. The size of the drawing
  34025. * buffer is computed with this formula:
  34026. * ````
  34027. * size.x = width * pixelRatio;
  34028. * size.y = height * pixelRatio;
  34029. *```
  34030. *
  34031. * @param {Number} width - The width in logical pixels.
  34032. * @param {Number} height - The height in logical pixels.
  34033. * @param {Number} pixelRatio - The pixel ratio.
  34034. */
  34035. setDrawingBufferSize( width, height, pixelRatio ) {
  34036. this._width = width;
  34037. this._height = height;
  34038. this._pixelRatio = pixelRatio;
  34039. this.domElement.width = Math.floor( width * pixelRatio );
  34040. this.domElement.height = Math.floor( height * pixelRatio );
  34041. this.setViewport( 0, 0, width, height );
  34042. if ( this._initialized ) this.backend.updateSize();
  34043. }
  34044. /**
  34045. * Sets the size of the renderer.
  34046. *
  34047. * @param {Number} width - The width in logical pixels.
  34048. * @param {Number} height - The height in logical pixels.
  34049. * @param {Boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  34050. */
  34051. setSize( width, height, updateStyle = true ) {
  34052. this._width = width;
  34053. this._height = height;
  34054. this.domElement.width = Math.floor( width * this._pixelRatio );
  34055. this.domElement.height = Math.floor( height * this._pixelRatio );
  34056. if ( updateStyle === true ) {
  34057. this.domElement.style.width = width + 'px';
  34058. this.domElement.style.height = height + 'px';
  34059. }
  34060. this.setViewport( 0, 0, width, height );
  34061. if ( this._initialized ) this.backend.updateSize();
  34062. }
  34063. /**
  34064. * Defines a manual sort function for the opaque render list.
  34065. * Pass `null` to use the default sort.
  34066. *
  34067. * @param {Function} method - The sort function.
  34068. */
  34069. setOpaqueSort( method ) {
  34070. this._opaqueSort = method;
  34071. }
  34072. /**
  34073. * Defines a manual sort function for the transparent render list.
  34074. * Pass `null` to use the default sort.
  34075. *
  34076. * @param {Function} method - The sort function.
  34077. */
  34078. setTransparentSort( method ) {
  34079. this._transparentSort = method;
  34080. }
  34081. /**
  34082. * Returns the scissor rectangle.
  34083. *
  34084. * @param {Vector4} target - The method writes the result in this target object.
  34085. * @return {Vector4} The scissor rectangle.
  34086. */
  34087. getScissor( target ) {
  34088. const scissor = this._scissor;
  34089. target.x = scissor.x;
  34090. target.y = scissor.y;
  34091. target.width = scissor.width;
  34092. target.height = scissor.height;
  34093. return target;
  34094. }
  34095. /**
  34096. * Defines the scissor rectangle.
  34097. *
  34098. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  34099. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  34100. * @param {Number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  34101. * @param {Number} width - The width of the scissor box in logical pixel unit.
  34102. * @param {Number} height - The height of the scissor box in logical pixel unit.
  34103. */
  34104. setScissor( x, y, width, height ) {
  34105. const scissor = this._scissor;
  34106. if ( x.isVector4 ) {
  34107. scissor.copy( x );
  34108. } else {
  34109. scissor.set( x, y, width, height );
  34110. }
  34111. }
  34112. /**
  34113. * Returns the scissor test value.
  34114. *
  34115. * @return {Boolean} Whether the scissor test should be enabled or not.
  34116. */
  34117. getScissorTest() {
  34118. return this._scissorTest;
  34119. }
  34120. /**
  34121. * Defines the scissor test.
  34122. *
  34123. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  34124. */
  34125. setScissorTest( boolean ) {
  34126. this._scissorTest = boolean;
  34127. this.backend.setScissorTest( boolean );
  34128. }
  34129. /**
  34130. * Returns the viewport definition.
  34131. *
  34132. * @param {Vector4} target - The method writes the result in this target object.
  34133. * @return {Vector4} The viewport definition.
  34134. */
  34135. getViewport( target ) {
  34136. return target.copy( this._viewport );
  34137. }
  34138. /**
  34139. * Defines the viewport.
  34140. *
  34141. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  34142. * @param {Number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  34143. * @param {Number} width - The width of the viewport in logical pixel unit.
  34144. * @param {Number} height - The height of the viewport in logical pixel unit.
  34145. * @param {Number} minDepth - The minimum depth value of the viewport. WebGPU only.
  34146. * @param {Number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  34147. */
  34148. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  34149. const viewport = this._viewport;
  34150. if ( x.isVector4 ) {
  34151. viewport.copy( x );
  34152. } else {
  34153. viewport.set( x, y, width, height );
  34154. }
  34155. viewport.minDepth = minDepth;
  34156. viewport.maxDepth = maxDepth;
  34157. }
  34158. /**
  34159. * Returns the clear color.
  34160. *
  34161. * @param {Color} target - The method writes the result in this target object.
  34162. * @return {Color} The clear color.
  34163. */
  34164. getClearColor( target ) {
  34165. return target.copy( this._clearColor );
  34166. }
  34167. /**
  34168. * Defines the clear color and optionally the clear alpha.
  34169. *
  34170. * @param {Color} color - The clear color.
  34171. * @param {Number} [alpha=1] - The clear alpha.
  34172. */
  34173. setClearColor( color, alpha = 1 ) {
  34174. this._clearColor.set( color );
  34175. this._clearColor.a = alpha;
  34176. }
  34177. /**
  34178. * Returns the clear alpha.
  34179. *
  34180. * @return {Number} The clear alpha.
  34181. */
  34182. getClearAlpha() {
  34183. return this._clearColor.a;
  34184. }
  34185. /**
  34186. * Defines the clear alpha.
  34187. *
  34188. * @param {Number} alpha - The clear alpha.
  34189. */
  34190. setClearAlpha( alpha ) {
  34191. this._clearColor.a = alpha;
  34192. }
  34193. /**
  34194. * Returns the clear depth.
  34195. *
  34196. * @return {Number} The clear depth.
  34197. */
  34198. getClearDepth() {
  34199. return this._clearDepth;
  34200. }
  34201. /**
  34202. * Defines the clear depth.
  34203. *
  34204. * @param {Number} depth - The clear depth.
  34205. */
  34206. setClearDepth( depth ) {
  34207. this._clearDepth = depth;
  34208. }
  34209. /**
  34210. * Returns the clear stencil.
  34211. *
  34212. * @return {Number} The clear stencil.
  34213. */
  34214. getClearStencil() {
  34215. return this._clearStencil;
  34216. }
  34217. /**
  34218. * Defines the clear stencil.
  34219. *
  34220. * @param {Number} stencil - The clear stencil.
  34221. */
  34222. setClearStencil( stencil ) {
  34223. this._clearStencil = stencil;
  34224. }
  34225. /**
  34226. * This method performs an occlusion query for the given 3D object.
  34227. * It returns `true` if the given 3D object is fully occluded by other
  34228. * 3D objects in the scene.
  34229. *
  34230. * @param {Object3D} object - The 3D object to test.
  34231. * @return {Boolean} Whether the 3D object is fully occluded or not.
  34232. */
  34233. isOccluded( object ) {
  34234. const renderContext = this._currentRenderContext;
  34235. return renderContext && this.backend.isOccluded( renderContext, object );
  34236. }
  34237. /**
  34238. * Performs a manual clear operation. This method ignores `autoClear` properties.
  34239. *
  34240. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  34241. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  34242. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  34243. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  34244. * Only returned when the renderer has not been initialized.
  34245. */
  34246. clear( color = true, depth = true, stencil = true ) {
  34247. if ( this._initialized === false ) {
  34248. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  34249. return this.clearAsync( color, depth, stencil );
  34250. }
  34251. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  34252. let renderContext = null;
  34253. if ( renderTarget !== null ) {
  34254. this._textures.updateRenderTarget( renderTarget );
  34255. const renderTargetData = this._textures.get( renderTarget );
  34256. renderContext = this._renderContexts.getForClear( renderTarget );
  34257. renderContext.textures = renderTargetData.textures;
  34258. renderContext.depthTexture = renderTargetData.depthTexture;
  34259. renderContext.width = renderTargetData.width;
  34260. renderContext.height = renderTargetData.height;
  34261. renderContext.renderTarget = renderTarget;
  34262. renderContext.depth = renderTarget.depthBuffer;
  34263. renderContext.stencil = renderTarget.stencilBuffer;
  34264. }
  34265. this.backend.clear( color, depth, stencil, renderContext );
  34266. if ( renderTarget !== null && this._renderTarget === null ) {
  34267. // If a color space transform or tone mapping is required,
  34268. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  34269. const quad = this._quad;
  34270. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  34271. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  34272. quad.material.needsUpdate = true;
  34273. }
  34274. this._renderScene( quad, quad.camera, false );
  34275. }
  34276. }
  34277. /**
  34278. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  34279. *
  34280. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  34281. * Only returned when the renderer has not been initialized.
  34282. */
  34283. clearColor() {
  34284. return this.clear( true, false, false );
  34285. }
  34286. /**
  34287. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  34288. *
  34289. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  34290. * Only returned when the renderer has not been initialized.
  34291. */
  34292. clearDepth() {
  34293. return this.clear( false, true, false );
  34294. }
  34295. /**
  34296. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  34297. *
  34298. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  34299. * Only returned when the renderer has not been initialized.
  34300. */
  34301. clearStencil() {
  34302. return this.clear( false, false, true );
  34303. }
  34304. /**
  34305. * Async version of {@link module:Renderer~Renderer#clear}.
  34306. *
  34307. * @async
  34308. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  34309. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  34310. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  34311. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  34312. */
  34313. async clearAsync( color = true, depth = true, stencil = true ) {
  34314. if ( this._initialized === false ) await this.init();
  34315. this.clear( color, depth, stencil );
  34316. }
  34317. /**
  34318. * Async version of {@link module:Renderer~Renderer#clearColor}.
  34319. *
  34320. * @async
  34321. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  34322. */
  34323. async clearColorAsync() {
  34324. this.clearAsync( true, false, false );
  34325. }
  34326. /**
  34327. * Async version of {@link module:Renderer~Renderer#clearDepth}.
  34328. *
  34329. * @async
  34330. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  34331. */
  34332. async clearDepthAsync() {
  34333. this.clearAsync( false, true, false );
  34334. }
  34335. /**
  34336. * Async version of {@link module:Renderer~Renderer#clearStencil}.
  34337. *
  34338. * @async
  34339. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  34340. */
  34341. async clearStencilAsync() {
  34342. this.clearAsync( false, false, true );
  34343. }
  34344. /**
  34345. * The current output tone mapping of the renderer. When a render target is set,
  34346. * the output tone mapping is always `NoToneMapping`.
  34347. *
  34348. * @type {Number}
  34349. */
  34350. get currentToneMapping() {
  34351. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  34352. }
  34353. /**
  34354. * The current output color space of the renderer. When a render target is set,
  34355. * the output color space is always `LinearSRGBColorSpace`.
  34356. *
  34357. * @type {String}
  34358. */
  34359. get currentColorSpace() {
  34360. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  34361. }
  34362. /**
  34363. * Frees all internal resources of the renderer. Call this method if the renderer
  34364. * is no longer in use by your app.
  34365. */
  34366. dispose() {
  34367. this.info.dispose();
  34368. this.backend.dispose();
  34369. this._animation.dispose();
  34370. this._objects.dispose();
  34371. this._pipelines.dispose();
  34372. this._nodes.dispose();
  34373. this._bindings.dispose();
  34374. this._renderLists.dispose();
  34375. this._renderContexts.dispose();
  34376. this._textures.dispose();
  34377. this.setRenderTarget( null );
  34378. this.setAnimationLoop( null );
  34379. }
  34380. /**
  34381. * Sets the given render target. Calling this method means the renderer does not
  34382. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  34383. * Use `null` as the first argument to reset the state.
  34384. *
  34385. * @param {RenderTarget?} renderTarget - The render target to set.
  34386. * @param {Number} [activeCubeFace=0] - The active cube face.
  34387. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  34388. */
  34389. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  34390. this._renderTarget = renderTarget;
  34391. this._activeCubeFace = activeCubeFace;
  34392. this._activeMipmapLevel = activeMipmapLevel;
  34393. }
  34394. /**
  34395. * Returns the current render target.
  34396. *
  34397. * @return {RenderTarget?} The render target. Returns `null` if no render target is set.
  34398. */
  34399. getRenderTarget() {
  34400. return this._renderTarget;
  34401. }
  34402. /**
  34403. * Callback for {@link module:Renderer~Renderer#setRenderObjectFunction}.
  34404. *
  34405. * @callback renderObjectFunction
  34406. * @param {Object3D} object - The 3D object.
  34407. * @param {Scene} scene - The scene the 3D object belongs to.
  34408. * @param {Camera} camera - The camera the object should be rendered with.
  34409. * @param {BufferGeometry} geometry - The object's geometry.
  34410. * @param {Material} material - The object's material.
  34411. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34412. * @param {LightsNode} lightsNode - The current lights node.
  34413. * @param {ClippingContext} clippingContext - The clipping context.
  34414. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34415. */
  34416. /**
  34417. * Sets the given render object function. Calling this method overwrites the default implementation
  34418. * which is {@link module:Renderer~Renderer#renderObject}. Defining a custom function can be useful
  34419. * if you want to modify the way objects are rendered. For example you can define things like "every
  34420. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  34421. * The custom function must always call `renderObject()` in its implementation.
  34422. *
  34423. * Use `null` as the first argument to reset the state.
  34424. *
  34425. * @param {module:Renderer~renderObjectFunction?} renderObjectFunction - The render object function.
  34426. */
  34427. setRenderObjectFunction( renderObjectFunction ) {
  34428. this._renderObjectFunction = renderObjectFunction;
  34429. }
  34430. /**
  34431. * Returns the current render object function.
  34432. *
  34433. * @return {Function?} The current render object function. Returns `null` if no function is set.
  34434. */
  34435. getRenderObjectFunction() {
  34436. return this._renderObjectFunction;
  34437. }
  34438. /**
  34439. * Execute a single or an array of compute nodes. This method can only be called
  34440. * if the renderer has been initialized.
  34441. *
  34442. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  34443. * @return {Promise?} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  34444. */
  34445. compute( computeNodes ) {
  34446. if ( this._isDeviceLost === true ) return;
  34447. if ( this._initialized === false ) {
  34448. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  34449. return this.computeAsync( computeNodes );
  34450. }
  34451. //
  34452. const nodeFrame = this._nodes.nodeFrame;
  34453. const previousRenderId = nodeFrame.renderId;
  34454. //
  34455. this.info.calls ++;
  34456. this.info.compute.calls ++;
  34457. this.info.compute.frameCalls ++;
  34458. nodeFrame.renderId = this.info.calls;
  34459. //
  34460. const backend = this.backend;
  34461. const pipelines = this._pipelines;
  34462. const bindings = this._bindings;
  34463. const nodes = this._nodes;
  34464. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  34465. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  34466. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  34467. }
  34468. backend.beginCompute( computeNodes );
  34469. for ( const computeNode of computeList ) {
  34470. // onInit
  34471. if ( pipelines.has( computeNode ) === false ) {
  34472. const dispose = () => {
  34473. computeNode.removeEventListener( 'dispose', dispose );
  34474. pipelines.delete( computeNode );
  34475. bindings.delete( computeNode );
  34476. nodes.delete( computeNode );
  34477. };
  34478. computeNode.addEventListener( 'dispose', dispose );
  34479. //
  34480. const onInitFn = computeNode.onInitFunction;
  34481. if ( onInitFn !== null ) {
  34482. onInitFn.call( computeNode, { renderer: this } );
  34483. }
  34484. }
  34485. nodes.updateForCompute( computeNode );
  34486. bindings.updateForCompute( computeNode );
  34487. const computeBindings = bindings.getForCompute( computeNode );
  34488. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  34489. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  34490. }
  34491. backend.finishCompute( computeNodes );
  34492. //
  34493. nodeFrame.renderId = previousRenderId;
  34494. }
  34495. /**
  34496. * Execute a single or an array of compute nodes.
  34497. *
  34498. * @async
  34499. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  34500. * @return {Promise} A Promise that resolve when the compute has finished.
  34501. */
  34502. async computeAsync( computeNodes ) {
  34503. if ( this._initialized === false ) await this.init();
  34504. this.compute( computeNodes );
  34505. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  34506. }
  34507. /**
  34508. * Checks if the given feature is supported by the selected backend.
  34509. *
  34510. * @async
  34511. * @param {String} name - The feature's name.
  34512. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  34513. */
  34514. async hasFeatureAsync( name ) {
  34515. if ( this._initialized === false ) await this.init();
  34516. return this.backend.hasFeature( name );
  34517. }
  34518. /**
  34519. * Checks if the given feature is supported by the selected backend. If the
  34520. * renderer has not been initialized, this method always returns `false`.
  34521. *
  34522. * @param {String} name - The feature's name.
  34523. * @return {Boolean} Whether the feature is supported or not.
  34524. */
  34525. hasFeature( name ) {
  34526. if ( this._initialized === false ) {
  34527. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  34528. return false;
  34529. }
  34530. return this.backend.hasFeature( name );
  34531. }
  34532. /**
  34533. * Returns `true` when the renderer has been initialized.
  34534. *
  34535. * @return {Boolean} Whether the renderer has been initialized or not.
  34536. */
  34537. hasInitialized() {
  34538. return this._initialized;
  34539. }
  34540. /**
  34541. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  34542. * (which can cause noticeable lags due to decode and GPU upload overhead).
  34543. *
  34544. * @async
  34545. * @param {Texture} texture - The texture.
  34546. * @return {Promise} A Promise that resolves when the texture has been initialized.
  34547. */
  34548. async initTextureAsync( texture ) {
  34549. if ( this._initialized === false ) await this.init();
  34550. this._textures.updateTexture( texture );
  34551. }
  34552. /**
  34553. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  34554. * (which can cause noticeable lags due to decode and GPU upload overhead).
  34555. *
  34556. * This method can only be used if the renderer has been initialized.
  34557. *
  34558. * @param {Texture} texture - The texture.
  34559. */
  34560. initTexture( texture ) {
  34561. if ( this._initialized === false ) {
  34562. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  34563. }
  34564. this._textures.updateTexture( texture );
  34565. }
  34566. /**
  34567. * Copies the current bound framebuffer into the given texture.
  34568. *
  34569. * @param {FramebufferTexture} framebufferTexture - The texture.
  34570. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  34571. */
  34572. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  34573. if ( rectangle !== null ) {
  34574. if ( rectangle.isVector2 ) {
  34575. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  34576. } else if ( rectangle.isVector4 ) {
  34577. rectangle = _vector4.copy( rectangle ).floor();
  34578. } else {
  34579. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  34580. return;
  34581. }
  34582. } else {
  34583. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  34584. }
  34585. //
  34586. let renderContext = this._currentRenderContext;
  34587. let renderTarget;
  34588. if ( renderContext !== null ) {
  34589. renderTarget = renderContext.renderTarget;
  34590. } else {
  34591. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  34592. if ( renderTarget !== null ) {
  34593. this._textures.updateRenderTarget( renderTarget );
  34594. renderContext = this._textures.get( renderTarget );
  34595. }
  34596. }
  34597. //
  34598. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  34599. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  34600. }
  34601. /**
  34602. * Copies data of source texture into a destination texture.
  34603. *
  34604. * @param {Texture} srcTexture - The source texture.
  34605. * @param {Texture} dstTexture - The destination texture.
  34606. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  34607. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  34608. * @param {Number} level - The mipmap level to copy.
  34609. */
  34610. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  34611. this._textures.updateTexture( srcTexture );
  34612. this._textures.updateTexture( dstTexture );
  34613. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  34614. }
  34615. /**
  34616. * Reads pixel data from the given render target.
  34617. *
  34618. * @async
  34619. * @param {RenderTarget} renderTarget - The render target to read from.
  34620. * @param {Number} x - The `x` coordinate of the copy region's origin.
  34621. * @param {Number} y - The `y` coordinate of the copy region's origin.
  34622. * @param {Number} width - The width of the copy region.
  34623. * @param {Number} height - The height of the copy region.
  34624. * @param {Number} [textureIndex=0] - The texture index of a MRT render target.
  34625. * @param {Number} [faceIndex=0] - The active cube face index.
  34626. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  34627. */
  34628. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  34629. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  34630. }
  34631. /**
  34632. * Analyzes the given 3D object's hierarchy and builds render lists from the
  34633. * processed hierarchy.
  34634. *
  34635. * @param {Object3D} object - The 3D object to process (usually a scene).
  34636. * @param {Camera} camera - The camera the object is rendered with.
  34637. * @param {Number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  34638. * @param {RenderList} renderList - The current render list.
  34639. * @param {ClippingContext} clippingContext - The current clipping context.
  34640. */
  34641. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  34642. if ( object.visible === false ) return;
  34643. const visible = object.layers.test( camera.layers );
  34644. if ( visible ) {
  34645. if ( object.isGroup ) {
  34646. groupOrder = object.renderOrder;
  34647. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  34648. } else if ( object.isLOD ) {
  34649. if ( object.autoUpdate === true ) object.update( camera );
  34650. } else if ( object.isLight ) {
  34651. renderList.pushLight( object );
  34652. } else if ( object.isSprite ) {
  34653. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  34654. if ( this.sortObjects === true ) {
  34655. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  34656. }
  34657. const { geometry, material } = object;
  34658. if ( material.visible ) {
  34659. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  34660. }
  34661. }
  34662. } else if ( object.isLineLoop ) {
  34663. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  34664. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  34665. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  34666. const { geometry, material } = object;
  34667. if ( this.sortObjects === true ) {
  34668. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  34669. _vector4
  34670. .copy( geometry.boundingSphere.center )
  34671. .applyMatrix4( object.matrixWorld )
  34672. .applyMatrix4( _projScreenMatrix );
  34673. }
  34674. if ( Array.isArray( material ) ) {
  34675. const groups = geometry.groups;
  34676. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  34677. const group = groups[ i ];
  34678. const groupMaterial = material[ group.materialIndex ];
  34679. if ( groupMaterial && groupMaterial.visible ) {
  34680. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  34681. }
  34682. }
  34683. } else if ( material.visible ) {
  34684. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  34685. }
  34686. }
  34687. }
  34688. }
  34689. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  34690. const baseRenderList = renderList;
  34691. // replace render list
  34692. renderList = this._renderLists.get( object, camera );
  34693. renderList.begin();
  34694. baseRenderList.pushBundle( {
  34695. bundleGroup: object,
  34696. camera,
  34697. renderList,
  34698. } );
  34699. renderList.finish();
  34700. }
  34701. const children = object.children;
  34702. for ( let i = 0, l = children.length; i < l; i ++ ) {
  34703. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  34704. }
  34705. }
  34706. /**
  34707. * Renders the given render bundles.
  34708. *
  34709. * @private
  34710. * @param {Array<Object>} bundles - Array with render bundle data.
  34711. * @param {Scene} sceneRef - The scene the render bundles belong to.
  34712. * @param {LightsNode} lightsNode - The current lights node.
  34713. */
  34714. _renderBundles( bundles, sceneRef, lightsNode ) {
  34715. for ( const bundle of bundles ) {
  34716. this._renderBundle( bundle, sceneRef, lightsNode );
  34717. }
  34718. }
  34719. /**
  34720. * Renders the transparent objects from the given render lists.
  34721. *
  34722. * @private
  34723. * @param {Array<Object>} renderList - The transparent render list.
  34724. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  34725. * @param {Camera} camera - The camera the render list should be rendered with.
  34726. * @param {Scene} scene - The scene the render list belongs to.
  34727. * @param {LightsNode} lightsNode - The current lights node.
  34728. */
  34729. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  34730. if ( doublePassList.length > 0 ) {
  34731. // render back side
  34732. for ( const { material } of doublePassList ) {
  34733. material.side = BackSide;
  34734. }
  34735. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  34736. // render front side
  34737. for ( const { material } of doublePassList ) {
  34738. material.side = FrontSide;
  34739. }
  34740. this._renderObjects( renderList, camera, scene, lightsNode );
  34741. // restore
  34742. for ( const { material } of doublePassList ) {
  34743. material.side = DoubleSide;
  34744. }
  34745. } else {
  34746. this._renderObjects( renderList, camera, scene, lightsNode );
  34747. }
  34748. }
  34749. /**
  34750. * Renders the objects from the given render list.
  34751. *
  34752. * @private
  34753. * @param {Array<Object>} renderList - The render list.
  34754. * @param {Camera} camera - The camera the render list should be rendered with.
  34755. * @param {Scene} scene - The scene the render list belongs to.
  34756. * @param {LightsNode} lightsNode - The current lights node.
  34757. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34758. */
  34759. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  34760. // process renderable objects
  34761. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  34762. const renderItem = renderList[ i ];
  34763. const { object, geometry, material, group, clippingContext } = renderItem;
  34764. if ( camera.isArrayCamera ) {
  34765. const cameras = camera.cameras;
  34766. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  34767. const camera2 = cameras[ j ];
  34768. if ( object.layers.test( camera2.layers ) ) {
  34769. const vp = camera2.viewport;
  34770. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  34771. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  34772. const viewportValue = this._currentRenderContext.viewportValue;
  34773. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  34774. viewportValue.minDepth = minDepth;
  34775. viewportValue.maxDepth = maxDepth;
  34776. this._currentRenderContext.viewport = true;
  34777. this.backend.updateViewport( this._currentRenderContext );
  34778. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  34779. }
  34780. }
  34781. } else {
  34782. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  34783. }
  34784. }
  34785. }
  34786. /**
  34787. * This method represents the default render object function that manages the render lifecycle
  34788. * of the object.
  34789. *
  34790. * @param {Object3D} object - The 3D object.
  34791. * @param {Scene} scene - The scene the 3D object belongs to.
  34792. * @param {Camera} camera - The camera the object should be rendered with.
  34793. * @param {BufferGeometry} geometry - The object's geometry.
  34794. * @param {Material} material - The object's material.
  34795. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34796. * @param {LightsNode} lightsNode - The current lights node.
  34797. * @param {ClippingContext} clippingContext - The clipping context.
  34798. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34799. */
  34800. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  34801. let overridePositionNode;
  34802. let overrideColorNode;
  34803. let overrideDepthNode;
  34804. //
  34805. object.onBeforeRender( this, scene, camera, geometry, material, group );
  34806. //
  34807. if ( scene.overrideMaterial !== null ) {
  34808. const overrideMaterial = scene.overrideMaterial;
  34809. if ( material.positionNode && material.positionNode.isNode ) {
  34810. overridePositionNode = overrideMaterial.positionNode;
  34811. overrideMaterial.positionNode = material.positionNode;
  34812. }
  34813. overrideMaterial.alphaTest = material.alphaTest;
  34814. overrideMaterial.alphaMap = material.alphaMap;
  34815. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  34816. if ( overrideMaterial.isShadowPassMaterial ) {
  34817. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  34818. if ( material.depthNode && material.depthNode.isNode ) {
  34819. overrideDepthNode = overrideMaterial.depthNode;
  34820. overrideMaterial.depthNode = material.depthNode;
  34821. }
  34822. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  34823. overrideColorNode = overrideMaterial.colorNode;
  34824. overrideMaterial.colorNode = material.castShadowNode;
  34825. }
  34826. }
  34827. material = overrideMaterial;
  34828. }
  34829. //
  34830. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  34831. material.side = BackSide;
  34832. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  34833. material.side = FrontSide;
  34834. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  34835. material.side = DoubleSide;
  34836. } else {
  34837. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  34838. }
  34839. //
  34840. if ( overridePositionNode !== undefined ) {
  34841. scene.overrideMaterial.positionNode = overridePositionNode;
  34842. }
  34843. if ( overrideDepthNode !== undefined ) {
  34844. scene.overrideMaterial.depthNode = overrideDepthNode;
  34845. }
  34846. if ( overrideColorNode !== undefined ) {
  34847. scene.overrideMaterial.colorNode = overrideColorNode;
  34848. }
  34849. //
  34850. object.onAfterRender( this, scene, camera, geometry, material, group );
  34851. }
  34852. /**
  34853. * This method represents the default `_handleObjectFunction` implementation which creates
  34854. * a render object from the given data and performs the draw command with the selected backend.
  34855. *
  34856. * @private
  34857. * @param {Object3D} object - The 3D object.
  34858. * @param {Material} material - The object's material.
  34859. * @param {Scene} scene - The scene the 3D object belongs to.
  34860. * @param {Camera} camera - The camera the object should be rendered with.
  34861. * @param {LightsNode} lightsNode - The current lights node.
  34862. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34863. * @param {ClippingContext} clippingContext - The clipping context.
  34864. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34865. */
  34866. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  34867. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  34868. renderObject.drawRange = object.geometry.drawRange;
  34869. renderObject.group = group;
  34870. //
  34871. const needsRefresh = this._nodes.needsRefresh( renderObject );
  34872. if ( needsRefresh ) {
  34873. this._nodes.updateBefore( renderObject );
  34874. this._geometries.updateForRender( renderObject );
  34875. this._nodes.updateForRender( renderObject );
  34876. this._bindings.updateForRender( renderObject );
  34877. }
  34878. this._pipelines.updateForRender( renderObject );
  34879. //
  34880. if ( this._currentRenderBundle !== null ) {
  34881. const renderBundleData = this.backend.get( this._currentRenderBundle );
  34882. renderBundleData.renderObjects.push( renderObject );
  34883. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  34884. }
  34885. this.backend.draw( renderObject, this.info );
  34886. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  34887. }
  34888. /**
  34889. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  34890. * Used in `compileAsync()`.
  34891. *
  34892. * @private
  34893. * @param {Object3D} object - The 3D object.
  34894. * @param {Material} material - The object's material.
  34895. * @param {Scene} scene - The scene the 3D object belongs to.
  34896. * @param {Camera} camera - The camera the object should be rendered with.
  34897. * @param {LightsNode} lightsNode - The current lights node.
  34898. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34899. * @param {ClippingContext} clippingContext - The clipping context.
  34900. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34901. */
  34902. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  34903. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  34904. renderObject.drawRange = object.geometry.drawRange;
  34905. renderObject.group = group;
  34906. //
  34907. this._nodes.updateBefore( renderObject );
  34908. this._geometries.updateForRender( renderObject );
  34909. this._nodes.updateForRender( renderObject );
  34910. this._bindings.updateForRender( renderObject );
  34911. this._pipelines.getForRender( renderObject, this._compilationPromises );
  34912. this._nodes.updateAfter( renderObject );
  34913. }
  34914. /**
  34915. * Alias for `compileAsync()`.
  34916. *
  34917. * @method
  34918. * @param {Object3D} scene - The scene or 3D object to precompile.
  34919. * @param {Camera} camera - The camera that is used to render the scene.
  34920. * @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.
  34921. * @return {Promise} A Promise that resolves when the compile has been finished.
  34922. */
  34923. get compile() {
  34924. return this.compileAsync;
  34925. }
  34926. }
  34927. /**
  34928. * A binding represents the connection between a resource (like a texture, sampler
  34929. * or uniform buffer) and the resource definition in a shader stage.
  34930. *
  34931. * This module is an abstract base class for all concrete bindings types.
  34932. *
  34933. * @abstract
  34934. * @private
  34935. */
  34936. class Binding {
  34937. /**
  34938. * Constructs a new binding.
  34939. *
  34940. * @param {String} [name=''] - The binding's name.
  34941. */
  34942. constructor( name = '' ) {
  34943. /**
  34944. * The binding's name.
  34945. *
  34946. * @type {String}
  34947. */
  34948. this.name = name;
  34949. /**
  34950. * A bitmask that defines in what shader stages the
  34951. * binding's resource is accessible.
  34952. *
  34953. * @type {Number}
  34954. */
  34955. this.visibility = 0;
  34956. }
  34957. /**
  34958. * Makes sure binding's resource is visible for the given shader stage.
  34959. *
  34960. * @param {Number} visibility - The shader stage.
  34961. */
  34962. setVisibility( visibility ) {
  34963. this.visibility |= visibility;
  34964. }
  34965. /**
  34966. * Clones the binding.
  34967. *
  34968. * @return {Binding} The cloned binding.
  34969. */
  34970. clone() {
  34971. return Object.assign( new this.constructor(), this );
  34972. }
  34973. }
  34974. /** @module BufferUtils **/
  34975. /**
  34976. * This function is usually called with the length in bytes of an array buffer.
  34977. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  34978. *
  34979. * @function
  34980. * @param {Number} floatLength - The buffer length.
  34981. * @return {Number} The padded length.
  34982. */
  34983. function getFloatLength( floatLength ) {
  34984. // ensure chunk size alignment (STD140 layout)
  34985. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  34986. }
  34987. /**
  34988. * Represents a buffer binding type.
  34989. *
  34990. * @private
  34991. * @abstract
  34992. * @augments Binding
  34993. */
  34994. class Buffer extends Binding {
  34995. /**
  34996. * Constructs a new buffer.
  34997. *
  34998. * @param {String} name - The buffer's name.
  34999. * @param {TypedArray} [buffer=null] - The buffer.
  35000. */
  35001. constructor( name, buffer = null ) {
  35002. super( name );
  35003. /**
  35004. * This flag can be used for type testing.
  35005. *
  35006. * @type {Boolean}
  35007. * @readonly
  35008. * @default true
  35009. */
  35010. this.isBuffer = true;
  35011. /**
  35012. * The bytes per element.
  35013. *
  35014. * @type {Number}
  35015. */
  35016. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  35017. /**
  35018. * A reference to the internal buffer.
  35019. *
  35020. * @private
  35021. * @type {TypedArray}
  35022. */
  35023. this._buffer = buffer;
  35024. }
  35025. /**
  35026. * The buffer's byte length.
  35027. *
  35028. * @type {Number}
  35029. * @readonly
  35030. */
  35031. get byteLength() {
  35032. return getFloatLength( this._buffer.byteLength );
  35033. }
  35034. /**
  35035. * A reference to the internal buffer.
  35036. *
  35037. * @type {Float32Array}
  35038. * @readonly
  35039. */
  35040. get buffer() {
  35041. return this._buffer;
  35042. }
  35043. /**
  35044. * Updates the binding.
  35045. *
  35046. * @return {Boolean} Whether the buffer has been updated and must be
  35047. * uploaded to the GPU.
  35048. */
  35049. update() {
  35050. return true;
  35051. }
  35052. }
  35053. /**
  35054. * Represents a uniform buffer binding type.
  35055. *
  35056. * @private
  35057. * @augments Buffer
  35058. */
  35059. class UniformBuffer extends Buffer {
  35060. /**
  35061. * Constructs a new uniform buffer.
  35062. *
  35063. * @param {String} name - The buffer's name.
  35064. * @param {TypedArray} [buffer=null] - The buffer.
  35065. */
  35066. constructor( name, buffer = null ) {
  35067. super( name, buffer );
  35068. /**
  35069. * This flag can be used for type testing.
  35070. *
  35071. * @type {Boolean}
  35072. * @readonly
  35073. * @default true
  35074. */
  35075. this.isUniformBuffer = true;
  35076. }
  35077. }
  35078. let _id$4 = 0;
  35079. /**
  35080. * A special form of uniform buffer binding type.
  35081. * It's buffer value is managed by a node object.
  35082. *
  35083. * @private
  35084. * @augments UniformBuffer
  35085. */
  35086. class NodeUniformBuffer extends UniformBuffer {
  35087. /**
  35088. * Constructs a new node-based uniform buffer.
  35089. *
  35090. * @param {BufferNode} nodeUniform - The uniform buffer node.
  35091. * @param {UniformGroupNode} groupNode - The uniform group node.
  35092. */
  35093. constructor( nodeUniform, groupNode ) {
  35094. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  35095. /**
  35096. * The uniform buffer node.
  35097. *
  35098. * @type {BufferNode}
  35099. */
  35100. this.nodeUniform = nodeUniform;
  35101. /**
  35102. * The uniform group node.
  35103. *
  35104. * @type {UniformGroupNode}
  35105. */
  35106. this.groupNode = groupNode;
  35107. }
  35108. /**
  35109. * The uniform buffer.
  35110. *
  35111. * @type {Float32Array}
  35112. */
  35113. get buffer() {
  35114. return this.nodeUniform.value;
  35115. }
  35116. }
  35117. /**
  35118. * This class represents a uniform buffer binding but with
  35119. * an API that allows to maintain individual uniform objects.
  35120. *
  35121. * @private
  35122. * @augments UniformBuffer
  35123. */
  35124. class UniformsGroup extends UniformBuffer {
  35125. /**
  35126. * Constructs a new uniforms group.
  35127. *
  35128. * @param {String} name - The group's name.
  35129. */
  35130. constructor( name ) {
  35131. super( name );
  35132. /**
  35133. * This flag can be used for type testing.
  35134. *
  35135. * @type {Boolean}
  35136. * @readonly
  35137. * @default true
  35138. */
  35139. this.isUniformsGroup = true;
  35140. /**
  35141. * An array with the raw uniform values.
  35142. *
  35143. * @private
  35144. * @type {Array<Number>?}
  35145. * @default null
  35146. */
  35147. this._values = null;
  35148. /**
  35149. * An array of uniform objects.
  35150. *
  35151. * The order of uniforms in this array must match the order of uniforms in the shader.
  35152. *
  35153. * @type {Array<Uniform>}
  35154. */
  35155. this.uniforms = [];
  35156. }
  35157. /**
  35158. * Adds a uniform to this group.
  35159. *
  35160. * @param {Uniform} uniform - The uniform to add.
  35161. * @return {UniformsGroup} A reference to this group.
  35162. */
  35163. addUniform( uniform ) {
  35164. this.uniforms.push( uniform );
  35165. return this;
  35166. }
  35167. /**
  35168. * Removes a uniform from this group.
  35169. *
  35170. * @param {Uniform} uniform - The uniform to remove.
  35171. * @return {UniformsGroup} A reference to this group.
  35172. */
  35173. removeUniform( uniform ) {
  35174. const index = this.uniforms.indexOf( uniform );
  35175. if ( index !== - 1 ) {
  35176. this.uniforms.splice( index, 1 );
  35177. }
  35178. return this;
  35179. }
  35180. /**
  35181. * An array with the raw uniform values.
  35182. *
  35183. * @type {Array<Number>}
  35184. */
  35185. get values() {
  35186. if ( this._values === null ) {
  35187. this._values = Array.from( this.buffer );
  35188. }
  35189. return this._values;
  35190. }
  35191. /**
  35192. * A Float32 array buffer with the uniform values.
  35193. *
  35194. * @type {Float32Array}
  35195. */
  35196. get buffer() {
  35197. let buffer = this._buffer;
  35198. if ( buffer === null ) {
  35199. const byteLength = this.byteLength;
  35200. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  35201. this._buffer = buffer;
  35202. }
  35203. return buffer;
  35204. }
  35205. /**
  35206. * The byte length of the buffer with correct buffer alignment.
  35207. *
  35208. * @type {Number}
  35209. */
  35210. get byteLength() {
  35211. let offset = 0; // global buffer offset in bytes
  35212. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  35213. const uniform = this.uniforms[ i ];
  35214. const { boundary, itemSize } = uniform;
  35215. // offset within a single chunk in bytes
  35216. const chunkOffset = offset % GPU_CHUNK_BYTES;
  35217. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  35218. // conformance tests
  35219. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  35220. // check for chunk overflow
  35221. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  35222. } else if ( chunkOffset % boundary !== 0 ) {
  35223. // check for correct alignment
  35224. offset += ( chunkOffset % boundary );
  35225. }
  35226. uniform.offset = ( offset / this.bytesPerElement );
  35227. offset += ( itemSize * this.bytesPerElement );
  35228. }
  35229. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  35230. }
  35231. /**
  35232. * Updates this group by updating each uniform object of
  35233. * the internal uniform list. The uniform objects check if their
  35234. * values has actually changed so this method only returns
  35235. * `true` if there is a real value change.
  35236. *
  35237. * @return {Boolean} Whether the uniforms have been updated and
  35238. * must be uploaded to the GPU.
  35239. */
  35240. update() {
  35241. let updated = false;
  35242. for ( const uniform of this.uniforms ) {
  35243. if ( this.updateByType( uniform ) === true ) {
  35244. updated = true;
  35245. }
  35246. }
  35247. return updated;
  35248. }
  35249. /**
  35250. * Updates a given uniform by calling an update method matching
  35251. * the uniforms type.
  35252. *
  35253. * @param {Uniform} uniform - The uniform to update.
  35254. * @return {Boolean} Whether the uniform has been updated or not.
  35255. */
  35256. updateByType( uniform ) {
  35257. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  35258. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  35259. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  35260. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  35261. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  35262. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  35263. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  35264. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  35265. }
  35266. /**
  35267. * Updates a given Number uniform.
  35268. *
  35269. * @param {NumberUniform} uniform - The Number uniform.
  35270. * @return {Boolean} Whether the uniform has been updated or not.
  35271. */
  35272. updateNumber( uniform ) {
  35273. let updated = false;
  35274. const a = this.values;
  35275. const v = uniform.getValue();
  35276. const offset = uniform.offset;
  35277. const type = uniform.getType();
  35278. if ( a[ offset ] !== v ) {
  35279. const b = this._getBufferForType( type );
  35280. b[ offset ] = a[ offset ] = v;
  35281. updated = true;
  35282. }
  35283. return updated;
  35284. }
  35285. /**
  35286. * Updates a given Vector2 uniform.
  35287. *
  35288. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  35289. * @return {Boolean} Whether the uniform has been updated or not.
  35290. */
  35291. updateVector2( uniform ) {
  35292. let updated = false;
  35293. const a = this.values;
  35294. const v = uniform.getValue();
  35295. const offset = uniform.offset;
  35296. const type = uniform.getType();
  35297. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  35298. const b = this._getBufferForType( type );
  35299. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  35300. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  35301. updated = true;
  35302. }
  35303. return updated;
  35304. }
  35305. /**
  35306. * Updates a given Vector3 uniform.
  35307. *
  35308. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  35309. * @return {Boolean} Whether the uniform has been updated or not.
  35310. */
  35311. updateVector3( uniform ) {
  35312. let updated = false;
  35313. const a = this.values;
  35314. const v = uniform.getValue();
  35315. const offset = uniform.offset;
  35316. const type = uniform.getType();
  35317. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  35318. const b = this._getBufferForType( type );
  35319. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  35320. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  35321. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  35322. updated = true;
  35323. }
  35324. return updated;
  35325. }
  35326. /**
  35327. * Updates a given Vector4 uniform.
  35328. *
  35329. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  35330. * @return {Boolean} Whether the uniform has been updated or not.
  35331. */
  35332. updateVector4( uniform ) {
  35333. let updated = false;
  35334. const a = this.values;
  35335. const v = uniform.getValue();
  35336. const offset = uniform.offset;
  35337. const type = uniform.getType();
  35338. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  35339. const b = this._getBufferForType( type );
  35340. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  35341. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  35342. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  35343. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  35344. updated = true;
  35345. }
  35346. return updated;
  35347. }
  35348. /**
  35349. * Updates a given Color uniform.
  35350. *
  35351. * @param {ColorUniform} uniform - The Color uniform.
  35352. * @return {Boolean} Whether the uniform has been updated or not.
  35353. */
  35354. updateColor( uniform ) {
  35355. let updated = false;
  35356. const a = this.values;
  35357. const c = uniform.getValue();
  35358. const offset = uniform.offset;
  35359. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  35360. const b = this.buffer;
  35361. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  35362. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  35363. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  35364. updated = true;
  35365. }
  35366. return updated;
  35367. }
  35368. /**
  35369. * Updates a given Matrix3 uniform.
  35370. *
  35371. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  35372. * @return {Boolean} Whether the uniform has been updated or not.
  35373. */
  35374. updateMatrix3( uniform ) {
  35375. let updated = false;
  35376. const a = this.values;
  35377. const e = uniform.getValue().elements;
  35378. const offset = uniform.offset;
  35379. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  35380. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  35381. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  35382. const b = this.buffer;
  35383. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  35384. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  35385. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  35386. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  35387. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  35388. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  35389. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  35390. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  35391. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  35392. updated = true;
  35393. }
  35394. return updated;
  35395. }
  35396. /**
  35397. * Updates a given Matrix4 uniform.
  35398. *
  35399. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  35400. * @return {Boolean} Whether the uniform has been updated or not.
  35401. */
  35402. updateMatrix4( uniform ) {
  35403. let updated = false;
  35404. const a = this.values;
  35405. const e = uniform.getValue().elements;
  35406. const offset = uniform.offset;
  35407. if ( arraysEqual( a, e, offset ) === false ) {
  35408. const b = this.buffer;
  35409. b.set( e, offset );
  35410. setArray( a, e, offset );
  35411. updated = true;
  35412. }
  35413. return updated;
  35414. }
  35415. /**
  35416. * Returns a typed array that matches the given data type.
  35417. *
  35418. * @param {String} type - The data type.
  35419. * @return {TypedArray} The typed array.
  35420. */
  35421. _getBufferForType( type ) {
  35422. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  35423. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  35424. return this.buffer;
  35425. }
  35426. }
  35427. /**
  35428. * Sets the values of the second array to the first array.
  35429. *
  35430. * @private
  35431. * @param {TypedArray} a - The first array.
  35432. * @param {TypedArray} b - The second array.
  35433. * @param {Number} offset - An index offset for the first array.
  35434. */
  35435. function setArray( a, b, offset ) {
  35436. for ( let i = 0, l = b.length; i < l; i ++ ) {
  35437. a[ offset + i ] = b[ i ];
  35438. }
  35439. }
  35440. /**
  35441. * Returns `true` if the given arrays are equal.
  35442. *
  35443. * @private
  35444. * @param {TypedArray} a - The first array.
  35445. * @param {TypedArray} b - The second array.
  35446. * @param {Number} offset - An index offset for the first array.
  35447. * @return {Boolean} Whether the given arrays are equal or not.
  35448. */
  35449. function arraysEqual( a, b, offset ) {
  35450. for ( let i = 0, l = b.length; i < l; i ++ ) {
  35451. if ( a[ offset + i ] !== b[ i ] ) return false;
  35452. }
  35453. return true;
  35454. }
  35455. let _id$3 = 0;
  35456. /**
  35457. * A special form of uniforms group that represents
  35458. * the individual uniforms as node-based uniforms.
  35459. *
  35460. * @private
  35461. * @augments UniformsGroup
  35462. */
  35463. class NodeUniformsGroup extends UniformsGroup {
  35464. /**
  35465. * Constructs a new node-based uniforms group.
  35466. *
  35467. * @param {String} name - The group's name.
  35468. * @param {UniformGroupNode} groupNode - The uniform group node.
  35469. */
  35470. constructor( name, groupNode ) {
  35471. super( name );
  35472. /**
  35473. * The group's ID.
  35474. *
  35475. * @type {Number}
  35476. */
  35477. this.id = _id$3 ++;
  35478. /**
  35479. * The uniform group node.
  35480. *
  35481. * @type {UniformGroupNode}
  35482. */
  35483. this.groupNode = groupNode;
  35484. /**
  35485. * This flag can be used for type testing.
  35486. *
  35487. * @type {Boolean}
  35488. * @readonly
  35489. * @default true
  35490. */
  35491. this.isNodeUniformsGroup = true;
  35492. }
  35493. }
  35494. let _id$2 = 0;
  35495. /**
  35496. * Represents a sampled texture binding type.
  35497. *
  35498. * @private
  35499. * @augments Binding
  35500. */
  35501. class SampledTexture extends Binding {
  35502. /**
  35503. * Constructs a new sampled texture.
  35504. *
  35505. * @param {String} name - The sampled texture's name.
  35506. * @param {Texture?} texture - The texture this binding is referring to.
  35507. */
  35508. constructor( name, texture ) {
  35509. super( name );
  35510. /**
  35511. * This identifier.
  35512. *
  35513. * @type {Number}
  35514. */
  35515. this.id = _id$2 ++;
  35516. /**
  35517. * The texture this binding is referring to.
  35518. *
  35519. * @type {Texture?}
  35520. */
  35521. this.texture = texture;
  35522. /**
  35523. * The binding's version.
  35524. *
  35525. * @type {Number}
  35526. */
  35527. this.version = texture ? texture.version : 0;
  35528. /**
  35529. * Whether the texture is a storage texture or not.
  35530. *
  35531. * @type {Boolean}
  35532. * @default false
  35533. */
  35534. this.store = false;
  35535. /**
  35536. * The binding's generation which is an additional version
  35537. * qualifier.
  35538. *
  35539. * @type {Number?}
  35540. * @default null
  35541. */
  35542. this.generation = null;
  35543. /**
  35544. * This flag can be used for type testing.
  35545. *
  35546. * @type {Boolean}
  35547. * @readonly
  35548. * @default true
  35549. */
  35550. this.isSampledTexture = true;
  35551. }
  35552. /**
  35553. * Returns `true` whether this binding requires an update for the
  35554. * given generation.
  35555. *
  35556. * @param {Number} generation - The generation.
  35557. * @return {Boolean} Whether an update is required or not.
  35558. */
  35559. needsBindingsUpdate( generation ) {
  35560. const { texture } = this;
  35561. if ( generation !== this.generation ) {
  35562. this.generation = generation;
  35563. return true;
  35564. }
  35565. return texture.isVideoTexture;
  35566. }
  35567. /**
  35568. * Updates the binding.
  35569. *
  35570. * @param {Number} generation - The generation.
  35571. * @return {Boolean} Whether the texture has been updated and must be
  35572. * uploaded to the GPU.
  35573. */
  35574. update() {
  35575. const { texture, version } = this;
  35576. if ( version !== texture.version ) {
  35577. this.version = texture.version;
  35578. return true;
  35579. }
  35580. return false;
  35581. }
  35582. }
  35583. /**
  35584. * A special form of sampled texture binding type.
  35585. * It's texture value is managed by a node object.
  35586. *
  35587. * @private
  35588. * @augments SampledTexture
  35589. */
  35590. class NodeSampledTexture extends SampledTexture {
  35591. /**
  35592. * Constructs a new node-based sampled texture.
  35593. *
  35594. * @param {String} name - The textures's name.
  35595. * @param {TextureNode} textureNode - The texture node.
  35596. * @param {UniformGroupNode} groupNode - The uniform group node.
  35597. * @param {String?} [access=null] - The access type.
  35598. */
  35599. constructor( name, textureNode, groupNode, access = null ) {
  35600. super( name, textureNode ? textureNode.value : null );
  35601. /**
  35602. * The texture node.
  35603. *
  35604. * @type {TextureNode}
  35605. */
  35606. this.textureNode = textureNode;
  35607. /**
  35608. * The uniform group node.
  35609. *
  35610. * @type {UniformGroupNode}
  35611. */
  35612. this.groupNode = groupNode;
  35613. /**
  35614. * The access type.
  35615. *
  35616. * @type {String?}
  35617. * @default null
  35618. */
  35619. this.access = access;
  35620. }
  35621. /**
  35622. * Overwrites the default to additionally check if the node value has changed.
  35623. *
  35624. * @param {Number} generation - The generation.
  35625. * @return {Boolean} Whether an update is required or not.
  35626. */
  35627. needsBindingsUpdate( generation ) {
  35628. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  35629. }
  35630. /**
  35631. * Updates the binding.
  35632. *
  35633. * @param {Number} generation - The generation.
  35634. * @return {Boolean} Whether the texture has been updated and must be
  35635. * uploaded to the GPU.
  35636. */
  35637. update() {
  35638. const { textureNode } = this;
  35639. if ( this.texture !== textureNode.value ) {
  35640. this.texture = textureNode.value;
  35641. return true;
  35642. }
  35643. return super.update();
  35644. }
  35645. }
  35646. /**
  35647. * A special form of sampled cube texture binding type.
  35648. * It's texture value is managed by a node object.
  35649. *
  35650. * @private
  35651. * @augments NodeSampledTexture
  35652. */
  35653. class NodeSampledCubeTexture extends NodeSampledTexture {
  35654. /**
  35655. * Constructs a new node-based sampled cube texture.
  35656. *
  35657. * @param {String} name - The textures's name.
  35658. * @param {TextureNode} textureNode - The texture node.
  35659. * @param {UniformGroupNode} groupNode - The uniform group node.
  35660. * @param {String?} [access=null] - The access type.
  35661. */
  35662. constructor( name, textureNode, groupNode, access = null ) {
  35663. super( name, textureNode, groupNode, access );
  35664. /**
  35665. * This flag can be used for type testing.
  35666. *
  35667. * @type {Boolean}
  35668. * @readonly
  35669. * @default true
  35670. */
  35671. this.isSampledCubeTexture = true;
  35672. }
  35673. }
  35674. /**
  35675. * A special form of sampled 3D texture binding type.
  35676. * It's texture value is managed by a node object.
  35677. *
  35678. * @private
  35679. * @augments NodeSampledTexture
  35680. */
  35681. class NodeSampledTexture3D extends NodeSampledTexture {
  35682. /**
  35683. * Constructs a new node-based sampled 3D texture.
  35684. *
  35685. * @param {String} name - The textures's name.
  35686. * @param {TextureNode} textureNode - The texture node.
  35687. * @param {UniformGroupNode} groupNode - The uniform group node.
  35688. * @param {String?} [access=null] - The access type.
  35689. */
  35690. constructor( name, textureNode, groupNode, access = null ) {
  35691. super( name, textureNode, groupNode, access );
  35692. /**
  35693. * This flag can be used for type testing.
  35694. *
  35695. * @type {Boolean}
  35696. * @readonly
  35697. * @default true
  35698. */
  35699. this.isSampledTexture3D = true;
  35700. }
  35701. }
  35702. const glslMethods = {
  35703. textureDimensions: 'textureSize',
  35704. equals: 'equal'
  35705. };
  35706. const precisionLib = {
  35707. low: 'lowp',
  35708. medium: 'mediump',
  35709. high: 'highp'
  35710. };
  35711. const supports$1 = {
  35712. swizzleAssign: true,
  35713. storageBuffer: false
  35714. };
  35715. const defaultPrecisions = `
  35716. precision highp float;
  35717. precision highp int;
  35718. precision highp sampler2D;
  35719. precision highp sampler3D;
  35720. precision highp samplerCube;
  35721. precision highp sampler2DArray;
  35722. precision highp usampler2D;
  35723. precision highp usampler3D;
  35724. precision highp usamplerCube;
  35725. precision highp usampler2DArray;
  35726. precision highp isampler2D;
  35727. precision highp isampler3D;
  35728. precision highp isamplerCube;
  35729. precision highp isampler2DArray;
  35730. precision lowp sampler2DShadow;
  35731. `;
  35732. /**
  35733. * A node builder targeting GLSL.
  35734. *
  35735. * This module generates GLSL shader code from node materials and also
  35736. * generates the respective bindings and vertex buffer definitions. These
  35737. * data are later used by the renderer to create render and compute pipelines
  35738. * for render objects.
  35739. *
  35740. * @augments NodeBuilder
  35741. */
  35742. class GLSLNodeBuilder extends NodeBuilder {
  35743. /**
  35744. * Constructs a new GLSL node builder renderer.
  35745. *
  35746. * @param {Object3D} object - The 3D object.
  35747. * @param {Renderer} renderer - The renderer.
  35748. */
  35749. constructor( object, renderer ) {
  35750. super( object, renderer, new GLSLNodeParser() );
  35751. /**
  35752. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  35753. * another dictionary which manages UBOs per group ('render','frame','object').
  35754. *
  35755. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  35756. */
  35757. this.uniformGroups = {};
  35758. /**
  35759. * An array that holds objects defining the varying and attribute data in
  35760. * context of Transform Feedback.
  35761. *
  35762. * @type {Object<String,Map<String,Object>>}
  35763. */
  35764. this.transforms = [];
  35765. /**
  35766. * A dictionary that holds for each shader stage a Map of used extensions.
  35767. *
  35768. * @type {Object<String,Map<String,Object>>}
  35769. */
  35770. this.extensions = {};
  35771. /**
  35772. * A dictionary that holds for each shader stage an Array of used builtins.
  35773. *
  35774. * @type {Object<String,Array<String>>}
  35775. */
  35776. this.builtins = { vertex: [], fragment: [], compute: [] };
  35777. /**
  35778. * Whether comparison in shader code are generated with methods or not.
  35779. *
  35780. * @type {Boolean}
  35781. * @default true
  35782. */
  35783. this.useComparisonMethod = true;
  35784. }
  35785. /**
  35786. * Checks if the given texture requires a manual conversion to the working color space.
  35787. *
  35788. * @param {Texture} texture - The texture to check.
  35789. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  35790. */
  35791. needsToWorkingColorSpace( texture ) {
  35792. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  35793. }
  35794. /**
  35795. * Returns the native shader method name for a given generic name.
  35796. *
  35797. * @param {String} method - The method name to resolve.
  35798. * @return {String} The resolved GLSL method name.
  35799. */
  35800. getMethod( method ) {
  35801. return glslMethods[ method ] || method;
  35802. }
  35803. /**
  35804. * Returns the output struct name. Not relevant for GLSL.
  35805. *
  35806. * @return {String}
  35807. */
  35808. getOutputStructName() {
  35809. return '';
  35810. }
  35811. /**
  35812. * Builds the given shader node.
  35813. *
  35814. * @param {ShaderNodeInternal} shaderNode - The shader node.
  35815. * @return {String} The GLSL function code.
  35816. */
  35817. buildFunctionCode( shaderNode ) {
  35818. const layout = shaderNode.layout;
  35819. const flowData = this.flowShaderNode( shaderNode );
  35820. const parameters = [];
  35821. for ( const input of layout.inputs ) {
  35822. parameters.push( this.getType( input.type ) + ' ' + input.name );
  35823. }
  35824. //
  35825. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  35826. ${ flowData.vars }
  35827. ${ flowData.code }
  35828. return ${ flowData.result };
  35829. }`;
  35830. //
  35831. return code;
  35832. }
  35833. /**
  35834. * Setups the Pixel Buffer Object (PBO) for the given storage
  35835. * buffer node.
  35836. *
  35837. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  35838. */
  35839. setupPBO( storageBufferNode ) {
  35840. const attribute = storageBufferNode.value;
  35841. if ( attribute.pbo === undefined ) {
  35842. const originalArray = attribute.array;
  35843. const numElements = attribute.count * attribute.itemSize;
  35844. const { itemSize } = attribute;
  35845. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  35846. let format = isInteger ? RedIntegerFormat : RedFormat;
  35847. if ( itemSize === 2 ) {
  35848. format = isInteger ? RGIntegerFormat : RGFormat;
  35849. } else if ( itemSize === 3 ) {
  35850. format = isInteger ? RGBIntegerFormat : RGBFormat;
  35851. } else if ( itemSize === 4 ) {
  35852. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  35853. }
  35854. const typeMap = {
  35855. Float32Array: FloatType,
  35856. Uint8Array: UnsignedByteType,
  35857. Uint16Array: UnsignedShortType,
  35858. Uint32Array: UnsignedIntType,
  35859. Int8Array: ByteType,
  35860. Int16Array: ShortType,
  35861. Int32Array: IntType,
  35862. Uint8ClampedArray: UnsignedByteType,
  35863. };
  35864. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  35865. let height = Math.ceil( ( numElements / itemSize ) / width );
  35866. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  35867. const newSize = width * height * itemSize;
  35868. const newArray = new originalArray.constructor( newSize );
  35869. newArray.set( originalArray, 0 );
  35870. attribute.array = newArray;
  35871. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  35872. pboTexture.needsUpdate = true;
  35873. pboTexture.isPBOTexture = true;
  35874. const pbo = new TextureNode( pboTexture, null, null );
  35875. pbo.setPrecision( 'high' );
  35876. attribute.pboNode = pbo;
  35877. attribute.pbo = pbo.value;
  35878. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  35879. }
  35880. }
  35881. /**
  35882. * Returns a GLSL snippet that represents the property name of the given node.
  35883. *
  35884. * @param {Node} node - The node.
  35885. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  35886. * @return {String} The property name.
  35887. */
  35888. getPropertyName( node, shaderStage = this.shaderStage ) {
  35889. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  35890. return shaderStage.charAt( 0 ) + '_' + node.name;
  35891. }
  35892. return super.getPropertyName( node, shaderStage );
  35893. }
  35894. /**
  35895. * Setups the Pixel Buffer Object (PBO) for the given storage
  35896. * buffer node.
  35897. *
  35898. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  35899. * @return {String} The property name.
  35900. */
  35901. generatePBO( storageArrayElementNode ) {
  35902. const { node, indexNode } = storageArrayElementNode;
  35903. const attribute = node.value;
  35904. if ( this.renderer.backend.has( attribute ) ) {
  35905. const attributeData = this.renderer.backend.get( attribute );
  35906. attributeData.pbo = attribute.pbo;
  35907. }
  35908. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  35909. const textureName = this.getPropertyName( nodeUniform );
  35910. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  35911. const indexSnippet = indexNode.build( this, 'uint' );
  35912. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  35913. let propertyName = elementNodeData.propertyName;
  35914. if ( propertyName === undefined ) {
  35915. // property element
  35916. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  35917. propertyName = this.getPropertyName( nodeVar );
  35918. // property size
  35919. const bufferNodeData = this.getDataFromNode( node );
  35920. let propertySizeName = bufferNodeData.propertySizeName;
  35921. if ( propertySizeName === undefined ) {
  35922. propertySizeName = propertyName + 'Size';
  35923. this.getVarFromNode( node, propertySizeName, 'uint' );
  35924. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  35925. bufferNodeData.propertySizeName = propertySizeName;
  35926. }
  35927. //
  35928. const { itemSize } = attribute;
  35929. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  35930. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  35931. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  35932. //
  35933. let prefix = 'vec4';
  35934. if ( attribute.pbo.type === UnsignedIntType ) {
  35935. prefix = 'uvec4';
  35936. } else if ( attribute.pbo.type === IntType ) {
  35937. prefix = 'ivec4';
  35938. }
  35939. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  35940. elementNodeData.propertyName = propertyName;
  35941. }
  35942. return propertyName;
  35943. }
  35944. /**
  35945. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  35946. *
  35947. * @param {Texture} texture - The texture.
  35948. * @param {String} textureProperty - The name of the texture uniform in the shader.
  35949. * @param {String} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  35950. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  35951. * @param {String} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  35952. * @return {String} The GLSL snippet.
  35953. */
  35954. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  35955. if ( depthSnippet ) {
  35956. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  35957. } else {
  35958. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  35959. }
  35960. }
  35961. /**
  35962. * Generates the GLSL snippet for sampling/loading the given texture.
  35963. *
  35964. * @param {Texture} texture - The texture.
  35965. * @param {String} textureProperty - The name of the texture uniform in the shader.
  35966. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  35967. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  35968. * @return {String} The GLSL snippet.
  35969. */
  35970. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  35971. if ( texture.isDepthTexture ) {
  35972. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  35973. } else {
  35974. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  35975. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  35976. }
  35977. }
  35978. /**
  35979. * Generates the GLSL snippet when sampling textures with explicit mip level.
  35980. *
  35981. * @param {Texture} texture - The texture.
  35982. * @param {String} textureProperty - The name of the texture uniform in the shader.
  35983. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  35984. * @param {String} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  35985. * @return {String} The GLSL snippet.
  35986. */
  35987. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  35988. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  35989. }
  35990. /**
  35991. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  35992. *
  35993. * @param {Texture} texture - The texture.
  35994. * @param {String} textureProperty - The name of the texture uniform in the shader.
  35995. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  35996. * @param {String} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  35997. * @return {String} The GLSL snippet.
  35998. */
  35999. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  36000. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  36001. }
  36002. /**
  36003. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  36004. *
  36005. * @param {Texture} texture - The texture.
  36006. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36007. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36008. * @param {Array<String>} gradSnippet - An array holding both gradient GLSL snippets.
  36009. * @return {String} The GLSL snippet.
  36010. */
  36011. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  36012. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  36013. }
  36014. /**
  36015. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  36016. * against a reference value.
  36017. *
  36018. * @param {Texture} texture - The texture.
  36019. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36020. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36021. * @param {String} compareSnippet - A GLSL snippet that represents the reference value.
  36022. * @param {String?} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  36023. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  36024. * @return {String} The GLSL snippet.
  36025. */
  36026. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  36027. if ( shaderStage === 'fragment' ) {
  36028. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  36029. } else {
  36030. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  36031. }
  36032. }
  36033. /**
  36034. * Returns the variables of the given shader stage as a GLSL string.
  36035. *
  36036. * @param {String} shaderStage - The shader stage.
  36037. * @return {String} The GLSL snippet that defines the variables.
  36038. */
  36039. getVars( shaderStage ) {
  36040. const snippets = [];
  36041. const vars = this.vars[ shaderStage ];
  36042. if ( vars !== undefined ) {
  36043. for ( const variable of vars ) {
  36044. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  36045. }
  36046. }
  36047. return snippets.join( '\n\t' );
  36048. }
  36049. /**
  36050. * Returns the uniforms of the given shader stage as a GLSL string.
  36051. *
  36052. * @param {String} shaderStage - The shader stage.
  36053. * @return {String} The GLSL snippet that defines the uniforms.
  36054. */
  36055. getUniforms( shaderStage ) {
  36056. const uniforms = this.uniforms[ shaderStage ];
  36057. const bindingSnippets = [];
  36058. const uniformGroups = {};
  36059. for ( const uniform of uniforms ) {
  36060. let snippet = null;
  36061. let group = false;
  36062. if ( uniform.type === 'texture' ) {
  36063. const texture = uniform.node.value;
  36064. let typePrefix = '';
  36065. if ( texture.isDataTexture === true ) {
  36066. if ( texture.type === UnsignedIntType ) {
  36067. typePrefix = 'u';
  36068. } else if ( texture.type === IntType ) {
  36069. typePrefix = 'i';
  36070. }
  36071. }
  36072. if ( texture.compareFunction ) {
  36073. snippet = `sampler2DShadow ${ uniform.name };`;
  36074. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  36075. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  36076. } else {
  36077. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  36078. }
  36079. } else if ( uniform.type === 'cubeTexture' ) {
  36080. snippet = `samplerCube ${ uniform.name };`;
  36081. } else if ( uniform.type === 'texture3D' ) {
  36082. snippet = `sampler3D ${ uniform.name };`;
  36083. } else if ( uniform.type === 'buffer' ) {
  36084. const bufferNode = uniform.node;
  36085. const bufferType = this.getType( bufferNode.bufferType );
  36086. const bufferCount = bufferNode.bufferCount;
  36087. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  36088. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  36089. } else {
  36090. const vectorType = this.getVectorType( uniform.type );
  36091. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  36092. group = true;
  36093. }
  36094. const precision = uniform.node.precision;
  36095. if ( precision !== null ) {
  36096. snippet = precisionLib[ precision ] + ' ' + snippet;
  36097. }
  36098. if ( group ) {
  36099. snippet = '\t' + snippet;
  36100. const groupName = uniform.groupNode.name;
  36101. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  36102. groupSnippets.push( snippet );
  36103. } else {
  36104. snippet = 'uniform ' + snippet;
  36105. bindingSnippets.push( snippet );
  36106. }
  36107. }
  36108. let output = '';
  36109. for ( const name in uniformGroups ) {
  36110. const groupSnippets = uniformGroups[ name ];
  36111. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  36112. }
  36113. output += bindingSnippets.join( '\n' );
  36114. return output;
  36115. }
  36116. /**
  36117. * Returns the type for a given buffer attribute.
  36118. *
  36119. * @param {BufferAttribute} attribute - The buffer attribute.
  36120. * @return {String} The type.
  36121. */
  36122. getTypeFromAttribute( attribute ) {
  36123. let nodeType = super.getTypeFromAttribute( attribute );
  36124. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  36125. let dataAttribute = attribute;
  36126. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36127. const array = dataAttribute.array;
  36128. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  36129. nodeType = nodeType.slice( 1 );
  36130. }
  36131. }
  36132. return nodeType;
  36133. }
  36134. /**
  36135. * Returns the shader attributes of the given shader stage as a GLSL string.
  36136. *
  36137. * @param {String} shaderStage - The shader stage.
  36138. * @return {String} The GLSL snippet that defines the shader attributes.
  36139. */
  36140. getAttributes( shaderStage ) {
  36141. let snippet = '';
  36142. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  36143. const attributes = this.getAttributesArray();
  36144. let location = 0;
  36145. for ( const attribute of attributes ) {
  36146. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  36147. }
  36148. }
  36149. return snippet;
  36150. }
  36151. /**
  36152. * Returns the members of the given struct type node as a GLSL string.
  36153. *
  36154. * @param {StructTypeNode} struct - The struct type node.
  36155. * @return {String} The GLSL snippet that defines the struct members.
  36156. */
  36157. getStructMembers( struct ) {
  36158. const snippets = [];
  36159. const members = struct.getMemberTypes();
  36160. for ( let i = 0; i < members.length; i ++ ) {
  36161. const member = members[ i ];
  36162. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  36163. }
  36164. return snippets.join( '\n' );
  36165. }
  36166. /**
  36167. * Returns the structs of the given shader stage as a GLSL string.
  36168. *
  36169. * @param {String} shaderStage - The shader stage.
  36170. * @return {String} The GLSL snippet that defines the structs.
  36171. */
  36172. getStructs( shaderStage ) {
  36173. const snippets = [];
  36174. const structs = this.structs[ shaderStage ];
  36175. if ( structs.length === 0 ) {
  36176. return 'layout( location = 0 ) out vec4 fragColor;\n';
  36177. }
  36178. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  36179. const struct = structs[ index ];
  36180. let snippet = '\n';
  36181. snippet += this.getStructMembers( struct );
  36182. snippet += '\n';
  36183. snippets.push( snippet );
  36184. }
  36185. return snippets.join( '\n\n' );
  36186. }
  36187. /**
  36188. * Returns the varyings of the given shader stage as a GLSL string.
  36189. *
  36190. * @param {String} shaderStage - The shader stage.
  36191. * @return {String} The GLSL snippet that defines the varyings.
  36192. */
  36193. getVaryings( shaderStage ) {
  36194. let snippet = '';
  36195. const varyings = this.varyings;
  36196. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  36197. for ( const varying of varyings ) {
  36198. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  36199. const type = this.getType( varying.type );
  36200. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  36201. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  36202. }
  36203. } else if ( shaderStage === 'fragment' ) {
  36204. for ( const varying of varyings ) {
  36205. if ( varying.needsInterpolation ) {
  36206. const type = this.getType( varying.type );
  36207. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  36208. snippet += `${flat}in ${type} ${varying.name};\n`;
  36209. }
  36210. }
  36211. }
  36212. for ( const builtin of this.builtins[ shaderStage ] ) {
  36213. snippet += `${builtin};\n`;
  36214. }
  36215. return snippet;
  36216. }
  36217. /**
  36218. * Returns the vertex index builtin.
  36219. *
  36220. * @return {String} The vertex index.
  36221. */
  36222. getVertexIndex() {
  36223. return 'uint( gl_VertexID )';
  36224. }
  36225. /**
  36226. * Returns the instance index builtin.
  36227. *
  36228. * @return {String} The instance index.
  36229. */
  36230. getInstanceIndex() {
  36231. return 'uint( gl_InstanceID )';
  36232. }
  36233. /**
  36234. * Returns the invocation local index builtin.
  36235. *
  36236. * @return {String} The invocation local index.
  36237. */
  36238. getInvocationLocalIndex() {
  36239. const workgroupSize = this.object.workgroupSize;
  36240. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  36241. return `uint( gl_InstanceID ) % ${size}u`;
  36242. }
  36243. /**
  36244. * Returns the draw index builtin.
  36245. *
  36246. * @return {String?} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  36247. */
  36248. getDrawIndex() {
  36249. const extensions = this.renderer.backend.extensions;
  36250. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  36251. return 'uint( gl_DrawID )';
  36252. }
  36253. return null;
  36254. }
  36255. /**
  36256. * Returns the front facing builtin.
  36257. *
  36258. * @return {String} The front facing builtin.
  36259. */
  36260. getFrontFacing() {
  36261. return 'gl_FrontFacing';
  36262. }
  36263. /**
  36264. * Returns the frag coord builtin.
  36265. *
  36266. * @return {String} The frag coord builtin.
  36267. */
  36268. getFragCoord() {
  36269. return 'gl_FragCoord.xy';
  36270. }
  36271. /**
  36272. * Returns the frag depth builtin.
  36273. *
  36274. * @return {String} The frag depth builtin.
  36275. */
  36276. getFragDepth() {
  36277. return 'gl_FragDepth';
  36278. }
  36279. /**
  36280. * Enables the given extension.
  36281. *
  36282. * @param {String} name - The extension name.
  36283. * @param {String} behavior - The extension behavior.
  36284. * @param {String} [shaderStage=this.shaderStage] - The shader stage.
  36285. */
  36286. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  36287. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  36288. if ( map.has( name ) === false ) {
  36289. map.set( name, {
  36290. name,
  36291. behavior
  36292. } );
  36293. }
  36294. }
  36295. /**
  36296. * Returns the enabled extensions of the given shader stage as a GLSL string.
  36297. *
  36298. * @param {String} shaderStage - The shader stage.
  36299. * @return {String} The GLSL snippet that defines the enabled extensions.
  36300. */
  36301. getExtensions( shaderStage ) {
  36302. const snippets = [];
  36303. if ( shaderStage === 'vertex' ) {
  36304. const ext = this.renderer.backend.extensions;
  36305. const isBatchedMesh = this.object.isBatchedMesh;
  36306. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  36307. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  36308. }
  36309. }
  36310. const extensions = this.extensions[ shaderStage ];
  36311. if ( extensions !== undefined ) {
  36312. for ( const { name, behavior } of extensions.values() ) {
  36313. snippets.push( `#extension ${name} : ${behavior}` );
  36314. }
  36315. }
  36316. return snippets.join( '\n' );
  36317. }
  36318. /**
  36319. * Returns the clip distances builtin.
  36320. *
  36321. * @return {String} The clip distances builtin.
  36322. */
  36323. getClipDistance() {
  36324. return 'gl_ClipDistance';
  36325. }
  36326. /**
  36327. * Whether the requested feature is available or not.
  36328. *
  36329. * @param {String} name - The requested feature.
  36330. * @return {Boolean} Whether the requested feature is supported or not.
  36331. */
  36332. isAvailable( name ) {
  36333. let result = supports$1[ name ];
  36334. if ( result === undefined ) {
  36335. let extensionName;
  36336. result = false;
  36337. switch ( name ) {
  36338. case 'float32Filterable':
  36339. extensionName = 'OES_texture_float_linear';
  36340. break;
  36341. case 'clipDistance':
  36342. extensionName = 'WEBGL_clip_cull_distance';
  36343. break;
  36344. }
  36345. if ( extensionName !== undefined ) {
  36346. const extensions = this.renderer.backend.extensions;
  36347. if ( extensions.has( extensionName ) ) {
  36348. extensions.get( extensionName );
  36349. result = true;
  36350. }
  36351. }
  36352. supports$1[ name ] = result;
  36353. }
  36354. return result;
  36355. }
  36356. /**
  36357. * Whether to flip texture data along its vertical axis or not.
  36358. *
  36359. * @return {Boolean} Returns always `true` in context of GLSL.
  36360. */
  36361. isFlipY() {
  36362. return true;
  36363. }
  36364. /**
  36365. * Enables hardware clipping.
  36366. *
  36367. * @param {String} planeCount - The clipping plane count.
  36368. */
  36369. enableHardwareClipping( planeCount ) {
  36370. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  36371. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  36372. }
  36373. /**
  36374. * Registers a transform in context of Transform Feedback.
  36375. *
  36376. * @param {String} varyingName - The varying name.
  36377. * @param {AttributeNode} attributeNode - The attribute node.
  36378. */
  36379. registerTransform( varyingName, attributeNode ) {
  36380. this.transforms.push( { varyingName, attributeNode } );
  36381. }
  36382. /**
  36383. * Returns the transforms of the given shader stage as a GLSL string.
  36384. *
  36385. * @param {String} shaderStage - The shader stage.
  36386. * @return {String} The GLSL snippet that defines the transforms.
  36387. */
  36388. getTransforms( /* shaderStage */ ) {
  36389. const transforms = this.transforms;
  36390. let snippet = '';
  36391. for ( let i = 0; i < transforms.length; i ++ ) {
  36392. const transform = transforms[ i ];
  36393. const attributeName = this.getPropertyName( transform.attributeNode );
  36394. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  36395. }
  36396. return snippet;
  36397. }
  36398. /**
  36399. * Returns a GLSL struct based on the given name and variables.
  36400. *
  36401. * @private
  36402. * @param {String} name - The struct name.
  36403. * @param {String} vars - The struct variables.
  36404. * @return {String} The GLSL snippet representing a struct.
  36405. */
  36406. _getGLSLUniformStruct( name, vars ) {
  36407. return `
  36408. layout( std140 ) uniform ${name} {
  36409. ${vars}
  36410. };`;
  36411. }
  36412. /**
  36413. * Returns a GLSL vertex shader based on the given shader data.
  36414. *
  36415. * @private
  36416. * @param {Object} shaderData - The shader data.
  36417. * @return {String} The vertex shader.
  36418. */
  36419. _getGLSLVertexCode( shaderData ) {
  36420. return `#version 300 es
  36421. ${ this.getSignature() }
  36422. // extensions
  36423. ${shaderData.extensions}
  36424. // precision
  36425. ${ defaultPrecisions }
  36426. // uniforms
  36427. ${shaderData.uniforms}
  36428. // varyings
  36429. ${shaderData.varyings}
  36430. // attributes
  36431. ${shaderData.attributes}
  36432. // codes
  36433. ${shaderData.codes}
  36434. void main() {
  36435. // vars
  36436. ${shaderData.vars}
  36437. // transforms
  36438. ${shaderData.transforms}
  36439. // flow
  36440. ${shaderData.flow}
  36441. gl_PointSize = 1.0;
  36442. }
  36443. `;
  36444. }
  36445. /**
  36446. * Returns a GLSL fragment shader based on the given shader data.
  36447. *
  36448. * @private
  36449. * @param {Object} shaderData - The shader data.
  36450. * @return {String} The vertex shader.
  36451. */
  36452. _getGLSLFragmentCode( shaderData ) {
  36453. return `#version 300 es
  36454. ${ this.getSignature() }
  36455. // precision
  36456. ${ defaultPrecisions }
  36457. // uniforms
  36458. ${shaderData.uniforms}
  36459. // varyings
  36460. ${shaderData.varyings}
  36461. // codes
  36462. ${shaderData.codes}
  36463. ${shaderData.structs}
  36464. void main() {
  36465. // vars
  36466. ${shaderData.vars}
  36467. // flow
  36468. ${shaderData.flow}
  36469. }
  36470. `;
  36471. }
  36472. /**
  36473. * Controls the code build of the shader stages.
  36474. */
  36475. buildCode() {
  36476. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  36477. this.sortBindingGroups();
  36478. for ( const shaderStage in shadersData ) {
  36479. let flow = '// code\n\n';
  36480. flow += this.flowCode[ shaderStage ];
  36481. const flowNodes = this.flowNodes[ shaderStage ];
  36482. const mainNode = flowNodes[ flowNodes.length - 1 ];
  36483. for ( const node of flowNodes ) {
  36484. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  36485. const slotName = node.name;
  36486. if ( slotName ) {
  36487. if ( flow.length > 0 ) flow += '\n';
  36488. flow += `\t// flow -> ${ slotName }\n\t`;
  36489. }
  36490. flow += `${ flowSlotData.code }\n\t`;
  36491. if ( node === mainNode && shaderStage !== 'compute' ) {
  36492. flow += '// result\n\t';
  36493. if ( shaderStage === 'vertex' ) {
  36494. flow += 'gl_Position = ';
  36495. flow += `${ flowSlotData.result };`;
  36496. } else if ( shaderStage === 'fragment' ) {
  36497. if ( ! node.outputNode.isOutputStructNode ) {
  36498. flow += 'fragColor = ';
  36499. flow += `${ flowSlotData.result };`;
  36500. }
  36501. }
  36502. }
  36503. }
  36504. const stageData = shadersData[ shaderStage ];
  36505. stageData.extensions = this.getExtensions( shaderStage );
  36506. stageData.uniforms = this.getUniforms( shaderStage );
  36507. stageData.attributes = this.getAttributes( shaderStage );
  36508. stageData.varyings = this.getVaryings( shaderStage );
  36509. stageData.vars = this.getVars( shaderStage );
  36510. stageData.structs = this.getStructs( shaderStage );
  36511. stageData.codes = this.getCodes( shaderStage );
  36512. stageData.transforms = this.getTransforms( shaderStage );
  36513. stageData.flow = flow;
  36514. }
  36515. if ( this.material !== null ) {
  36516. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  36517. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  36518. } else {
  36519. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  36520. }
  36521. }
  36522. /**
  36523. * This method is one of the more important ones since it's responsible
  36524. * for generating a matching binding instance for the given uniform node.
  36525. *
  36526. * These bindings are later used in the renderer to create bind groups
  36527. * and layouts.
  36528. *
  36529. * @param {UniformNode} node - The uniform node.
  36530. * @param {String} type - The node data type.
  36531. * @param {String} shaderStage - The shader stage.
  36532. * @param {String?} [name=null] - An optional uniform name.
  36533. * @return {NodeUniform} The node uniform object.
  36534. */
  36535. getUniformFromNode( node, type, shaderStage, name = null ) {
  36536. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  36537. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36538. let uniformGPU = nodeData.uniformGPU;
  36539. if ( uniformGPU === undefined ) {
  36540. const group = node.groupNode;
  36541. const groupName = group.name;
  36542. const bindings = this.getBindGroupArray( groupName, shaderStage );
  36543. if ( type === 'texture' ) {
  36544. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  36545. bindings.push( uniformGPU );
  36546. } else if ( type === 'cubeTexture' ) {
  36547. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  36548. bindings.push( uniformGPU );
  36549. } else if ( type === 'texture3D' ) {
  36550. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  36551. bindings.push( uniformGPU );
  36552. } else if ( type === 'buffer' ) {
  36553. node.name = `NodeBuffer_${ node.id }`;
  36554. uniformNode.name = `buffer${ node.id }`;
  36555. const buffer = new NodeUniformBuffer( node, group );
  36556. buffer.name = node.name;
  36557. bindings.push( buffer );
  36558. uniformGPU = buffer;
  36559. } else {
  36560. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  36561. let uniformsGroup = uniformsStage[ groupName ];
  36562. if ( uniformsGroup === undefined ) {
  36563. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  36564. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  36565. uniformsStage[ groupName ] = uniformsGroup;
  36566. bindings.push( uniformsGroup );
  36567. }
  36568. uniformGPU = this.getNodeUniform( uniformNode, type );
  36569. uniformsGroup.addUniform( uniformGPU );
  36570. }
  36571. nodeData.uniformGPU = uniformGPU;
  36572. }
  36573. return uniformNode;
  36574. }
  36575. }
  36576. let _vector2 = null;
  36577. let _color4 = null;
  36578. /**
  36579. * Most of the rendering related logic is implemented in the
  36580. * {@link module:Renderer} module and related management components.
  36581. * Sometimes it is required though to execute commands which are
  36582. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  36583. * This abstract base class defines an interface that encapsulates
  36584. * all backend-related logic. Derived classes for each backend must
  36585. * implement the interface.
  36586. *
  36587. * @abstract
  36588. * @private
  36589. */
  36590. class Backend {
  36591. /**
  36592. * Constructs a new backend.
  36593. *
  36594. * @param {Object} parameters - An object holding parameters for the backend.
  36595. */
  36596. constructor( parameters = {} ) {
  36597. /**
  36598. * The parameters of the backend.
  36599. *
  36600. * @type {Object}
  36601. */
  36602. this.parameters = Object.assign( {}, parameters );
  36603. /**
  36604. * This weak map holds backend-specific data of objects
  36605. * like textures, attributes or render targets.
  36606. *
  36607. * @type {WeakMap}
  36608. */
  36609. this.data = new WeakMap();
  36610. /**
  36611. * A reference to the renderer.
  36612. *
  36613. * @type {Renderer?}
  36614. * @default null
  36615. */
  36616. this.renderer = null;
  36617. /**
  36618. * A reference to the canvas element the renderer is drawing to.
  36619. *
  36620. * @type {(HTMLCanvasElement|OffscreenCanvas)?}
  36621. * @default null
  36622. */
  36623. this.domElement = null;
  36624. }
  36625. /**
  36626. * Initializes the backend so it is ready for usage. Concrete backends
  36627. * are supposed to implement their rendering context creation and related
  36628. * operations in this method.
  36629. *
  36630. * @async
  36631. * @param {Renderer} renderer - The renderer.
  36632. * @return {Promise} A Promise that resolves when the backend has been initialized.
  36633. */
  36634. async init( renderer ) {
  36635. this.renderer = renderer;
  36636. }
  36637. /**
  36638. * The coordinate system of the backend.
  36639. *
  36640. * @abstract
  36641. * @type {Number}
  36642. * @readonly
  36643. */
  36644. get coordinateSystem() {}
  36645. // render context
  36646. /**
  36647. * This method is executed at the beginning of a render call and
  36648. * can be used by the backend to prepare the state for upcoming
  36649. * draw calls.
  36650. *
  36651. * @abstract
  36652. * @param {RenderContext} renderContext - The render context.
  36653. */
  36654. beginRender( /*renderContext*/ ) {}
  36655. /**
  36656. * This method is executed at the end of a render call and
  36657. * can be used by the backend to finalize work after draw
  36658. * calls.
  36659. *
  36660. * @abstract
  36661. * @param {RenderContext} renderContext - The render context.
  36662. */
  36663. finishRender( /*renderContext*/ ) {}
  36664. /**
  36665. * This method is executed at the beginning of a compute call and
  36666. * can be used by the backend to prepare the state for upcoming
  36667. * compute tasks.
  36668. *
  36669. * @abstract
  36670. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  36671. */
  36672. beginCompute( /*computeGroup*/ ) {}
  36673. /**
  36674. * This method is executed at the end of a compute call and
  36675. * can be used by the backend to finalize work after compute
  36676. * tasks.
  36677. *
  36678. * @abstract
  36679. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  36680. */
  36681. finishCompute( /*computeGroup*/ ) {}
  36682. // render object
  36683. /**
  36684. * Executes a draw command for the given render object.
  36685. *
  36686. * @abstract
  36687. * @param {RenderObject} renderObject - The render object to draw.
  36688. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  36689. */
  36690. draw( /*renderObject, info*/ ) { }
  36691. // compute node
  36692. /**
  36693. * Executes a compute command for the given compute node.
  36694. *
  36695. * @abstract
  36696. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  36697. * @param {Node} computeNode - The compute node.
  36698. * @param {Array<BindGroup>} bindings - The bindings.
  36699. * @param {ComputePipeline} computePipeline - The compute pipeline.
  36700. */
  36701. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  36702. // program
  36703. /**
  36704. * Creates a shader program from the given programmable stage.
  36705. *
  36706. * @abstract
  36707. * @param {ProgrammableStage} program - The programmable stage.
  36708. */
  36709. createProgram( /*program*/ ) { }
  36710. /**
  36711. * Destroys the shader program of the given programmable stage.
  36712. *
  36713. * @abstract
  36714. * @param {ProgrammableStage} program - The programmable stage.
  36715. */
  36716. destroyProgram( /*program*/ ) { }
  36717. // bindings
  36718. /**
  36719. * Creates bindings from the given bind group definition.
  36720. *
  36721. * @abstract
  36722. * @param {BindGroup} bindGroup - The bind group.
  36723. * @param {Array<BindGroup>} bindings - Array of bind groups.
  36724. * @param {Number} cacheIndex - The cache index.
  36725. * @param {Number} version - The version.
  36726. */
  36727. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  36728. /**
  36729. * Updates the given bind group definition.
  36730. *
  36731. * @abstract
  36732. * @param {BindGroup} bindGroup - The bind group.
  36733. * @param {Array<BindGroup>} bindings - Array of bind groups.
  36734. * @param {Number} cacheIndex - The cache index.
  36735. * @param {Number} version - The version.
  36736. */
  36737. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  36738. /**
  36739. * Updates a buffer binding.
  36740. *
  36741. * @abstract
  36742. * @param {Buffer} binding - The buffer binding to update.
  36743. */
  36744. updateBinding( /*binding*/ ) { }
  36745. // pipeline
  36746. /**
  36747. * Creates a render pipeline for the given render object.
  36748. *
  36749. * @abstract
  36750. * @param {RenderObject} renderObject - The render object.
  36751. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  36752. */
  36753. createRenderPipeline( /*renderObject, promises*/ ) { }
  36754. /**
  36755. * Creates a compute pipeline for the given compute node.
  36756. *
  36757. * @abstract
  36758. * @param {ComputePipeline} computePipeline - The compute pipeline.
  36759. * @param {Array<BindGroup>} bindings - The bindings.
  36760. */
  36761. createComputePipeline( /*computePipeline, bindings*/ ) { }
  36762. // cache key
  36763. /**
  36764. * Returns `true` if the render pipeline requires an update.
  36765. *
  36766. * @abstract
  36767. * @param {RenderObject} renderObject - The render object.
  36768. * @return {Boolean} Whether the render pipeline requires an update or not.
  36769. */
  36770. needsRenderUpdate( /*renderObject*/ ) { }
  36771. /**
  36772. * Returns a cache key that is used to identify render pipelines.
  36773. *
  36774. * @abstract
  36775. * @param {RenderObject} renderObject - The render object.
  36776. * @return {String} The cache key.
  36777. */
  36778. getRenderCacheKey( /*renderObject*/ ) { }
  36779. // node builder
  36780. /**
  36781. * Returns a node builder for the given render object.
  36782. *
  36783. * @abstract
  36784. * @param {RenderObject} renderObject - The render object.
  36785. * @param {Renderer} renderer - The renderer.
  36786. * @return {NodeBuilder} The node builder.
  36787. */
  36788. createNodeBuilder( /*renderObject, renderer*/ ) { }
  36789. // textures
  36790. /**
  36791. * Creates a GPU sampler for the given texture.
  36792. *
  36793. * @abstract
  36794. * @param {Texture} texture - The texture to create the sampler for.
  36795. */
  36796. createSampler( /*texture*/ ) { }
  36797. /**
  36798. * Destroys the GPU sampler for the given texture.
  36799. *
  36800. * @abstract
  36801. * @param {Texture} texture - The texture to destroy the sampler for.
  36802. */
  36803. destroySampler( /*texture*/ ) {}
  36804. /**
  36805. * Creates a default texture for the given texture that can be used
  36806. * as a placeholder until the actual texture is ready for usage.
  36807. *
  36808. * @abstract
  36809. * @param {Texture} texture - The texture to create a default texture for.
  36810. */
  36811. createDefaultTexture( /*texture*/ ) { }
  36812. /**
  36813. * Defines a texture on the GPU for the given texture object.
  36814. *
  36815. * @abstract
  36816. * @param {Texture} texture - The texture.
  36817. * @param {Object} [options={}] - Optional configuration parameter.
  36818. */
  36819. createTexture( /*texture, options={}*/ ) { }
  36820. /**
  36821. * Uploads the updated texture data to the GPU.
  36822. *
  36823. * @abstract
  36824. * @param {Texture} texture - The texture.
  36825. * @param {Object} [options={}] - Optional configuration parameter.
  36826. */
  36827. updateTexture( /*texture, options = {}*/ ) { }
  36828. /**
  36829. * Generates mipmaps for the given texture.
  36830. *
  36831. * @abstract
  36832. * @param {Texture} texture - The texture.
  36833. */
  36834. generateMipmaps( /*texture*/ ) { }
  36835. /**
  36836. * Destroys the GPU data for the given texture object.
  36837. *
  36838. * @abstract
  36839. * @param {Texture} texture - The texture.
  36840. */
  36841. destroyTexture( /*texture*/ ) { }
  36842. /**
  36843. * Returns texture data as a typed array.
  36844. *
  36845. * @abstract
  36846. * @async
  36847. * @param {Texture} texture - The texture to copy.
  36848. * @param {Number} x - The x coordinate of the copy origin.
  36849. * @param {Number} y - The y coordinate of the copy origin.
  36850. * @param {Number} width - The width of the copy.
  36851. * @param {Number} height - The height of the copy.
  36852. * @param {Number} faceIndex - The face index.
  36853. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  36854. */
  36855. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  36856. /**
  36857. * Copies data of the given source texture to the given destination texture.
  36858. *
  36859. * @abstract
  36860. * @param {Texture} srcTexture - The source texture.
  36861. * @param {Texture} dstTexture - The destination texture.
  36862. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  36863. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  36864. * @param {Number} [level=0] - The mip level to copy.
  36865. */
  36866. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0*/ ) {}
  36867. /**
  36868. * Copies the current bound framebuffer to the given texture.
  36869. *
  36870. * @abstract
  36871. * @param {Texture} texture - The destination texture.
  36872. * @param {RenderContext} renderContext - The render context.
  36873. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  36874. */
  36875. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  36876. // attributes
  36877. /**
  36878. * Creates the GPU buffer of a shader attribute.
  36879. *
  36880. * @abstract
  36881. * @param {BufferAttribute} attribute - The buffer attribute.
  36882. */
  36883. createAttribute( /*attribute*/ ) { }
  36884. /**
  36885. * Creates the GPU buffer of an indexed shader attribute.
  36886. *
  36887. * @abstract
  36888. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  36889. */
  36890. createIndexAttribute( /*attribute*/ ) { }
  36891. /**
  36892. * Creates the GPU buffer of a storage attribute.
  36893. *
  36894. * @abstract
  36895. * @param {BufferAttribute} attribute - The buffer attribute.
  36896. */
  36897. createStorageAttribute( /*attribute*/ ) { }
  36898. /**
  36899. * Updates the GPU buffer of a shader attribute.
  36900. *
  36901. * @abstract
  36902. * @param {BufferAttribute} attribute - The buffer attribute to update.
  36903. */
  36904. updateAttribute( /*attribute*/ ) { }
  36905. /**
  36906. * Destroys the GPU buffer of a shader attribute.
  36907. *
  36908. * @abstract
  36909. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  36910. */
  36911. destroyAttribute( /*attribute*/ ) { }
  36912. // canvas
  36913. /**
  36914. * Returns the backend's rendering context.
  36915. *
  36916. * @abstract
  36917. * @return {Object} The rendering context.
  36918. */
  36919. getContext() { }
  36920. /**
  36921. * Backends can use this method if they have to run
  36922. * logic when the renderer gets resized.
  36923. *
  36924. * @abstract
  36925. */
  36926. updateSize() { }
  36927. /**
  36928. * Updates the viewport with the values from the given render context.
  36929. *
  36930. * @abstract
  36931. * @param {RenderContext} renderContext - The render context.
  36932. */
  36933. updateViewport( /*renderContext*/ ) {}
  36934. // utils
  36935. /**
  36936. * Returns `true` if the given 3D object is fully occluded by other
  36937. * 3D objects in the scene. Backends must implement this method by using
  36938. * a Occlusion Query API.
  36939. *
  36940. * @abstract
  36941. * @param {RenderContext} renderContext - The render context.
  36942. * @param {Object3D} object - The 3D object to test.
  36943. * @return {Boolean} Whether the 3D object is fully occluded or not.
  36944. */
  36945. isOccluded( /*renderContext, object*/ ) {}
  36946. /**
  36947. * Resolves the time stamp for the given render context and type.
  36948. *
  36949. * @async
  36950. * @abstract
  36951. * @param {RenderContext} renderContext - The render context.
  36952. * @param {String} type - The render context.
  36953. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  36954. */
  36955. async resolveTimestampAsync( /*renderContext, type*/ ) { }
  36956. /**
  36957. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  36958. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  36959. *
  36960. * @async
  36961. * @abstract
  36962. * @return {Promise} A Promise that resolves when synchronization has been finished.
  36963. */
  36964. async waitForGPU() {}
  36965. /**
  36966. * This method performs a readback operation by moving buffer data from
  36967. * a storage buffer attribute from the GPU to the CPU.
  36968. *
  36969. * @async
  36970. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  36971. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  36972. */
  36973. async getArrayBufferAsync( /* attribute */ ) {}
  36974. /**
  36975. * Checks if the given feature is supported by the backend.
  36976. *
  36977. * @async
  36978. * @abstract
  36979. * @param {String} name - The feature's name.
  36980. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  36981. */
  36982. async hasFeatureAsync( /*name*/ ) { }
  36983. /**
  36984. * Checks if the given feature is supported by the backend.
  36985. *
  36986. * @abstract
  36987. * @param {String} name - The feature's name.
  36988. * @return {Boolean} Whether the feature is supported or not.
  36989. */
  36990. hasFeature( /*name*/ ) {}
  36991. /**
  36992. * Returns the maximum anisotropy texture filtering value.
  36993. *
  36994. * @abstract
  36995. * @return {Number} The maximum anisotropy texture filtering value.
  36996. */
  36997. getMaxAnisotropy() {}
  36998. /**
  36999. * Returns the drawing buffer size.
  37000. *
  37001. * @return {Vector2} The drawing buffer size.
  37002. */
  37003. getDrawingBufferSize() {
  37004. _vector2 = _vector2 || new Vector2();
  37005. return this.renderer.getDrawingBufferSize( _vector2 );
  37006. }
  37007. /**
  37008. * Defines the scissor test.
  37009. *
  37010. * @abstract
  37011. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  37012. */
  37013. setScissorTest( /*boolean*/ ) { }
  37014. /**
  37015. * Returns the clear color and alpha into a single
  37016. * color object.
  37017. *
  37018. * @return {Color4} The clear color.
  37019. */
  37020. getClearColor() {
  37021. const renderer = this.renderer;
  37022. _color4 = _color4 || new Color4();
  37023. renderer.getClearColor( _color4 );
  37024. _color4.getRGB( _color4, this.renderer.currentColorSpace );
  37025. return _color4;
  37026. }
  37027. /**
  37028. * Returns the DOM element. If no DOM element exists, the backend
  37029. * creates a new one.
  37030. *
  37031. * @return {HTMLCanvasElement} The DOM element.
  37032. */
  37033. getDomElement() {
  37034. let domElement = this.domElement;
  37035. if ( domElement === null ) {
  37036. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  37037. // OffscreenCanvas does not have setAttribute, see #22811
  37038. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  37039. this.domElement = domElement;
  37040. }
  37041. return domElement;
  37042. }
  37043. /**
  37044. * Sets a dictionary for the given object into the
  37045. * internal data structure.
  37046. *
  37047. * @param {Object} object - The object.
  37048. * @param {Object} value - The dictionary to set.
  37049. */
  37050. set( object, value ) {
  37051. this.data.set( object, value );
  37052. }
  37053. /**
  37054. * Returns the dictionary for the given object.
  37055. *
  37056. * @param {Object} object - The object.
  37057. * @return {Object} The object's dictionary.
  37058. */
  37059. get( object ) {
  37060. let map = this.data.get( object );
  37061. if ( map === undefined ) {
  37062. map = {};
  37063. this.data.set( object, map );
  37064. }
  37065. return map;
  37066. }
  37067. /**
  37068. * Checks if the given object has a dictionary
  37069. * with data defined.
  37070. *
  37071. * @param {Object} object - The object.
  37072. * @return {Boolean} Whether a dictionary for the given object as been defined or not.
  37073. */
  37074. has( object ) {
  37075. return this.data.has( object );
  37076. }
  37077. /**
  37078. * Deletes an object from the internal data structure.
  37079. *
  37080. * @param {Object} object - The object to delete.
  37081. */
  37082. delete( object ) {
  37083. this.data.delete( object );
  37084. }
  37085. /**
  37086. * Frees internal resources.
  37087. *
  37088. * @abstract
  37089. */
  37090. dispose() { }
  37091. }
  37092. let _id$1 = 0;
  37093. /**
  37094. * This module is internally used in context of compute shaders.
  37095. * This type of shader is not natively supported in WebGL 2 and
  37096. * thus implemented via Transform Feedback. `DualAttributeData`
  37097. * manages the related data.
  37098. *
  37099. * @private
  37100. */
  37101. class DualAttributeData {
  37102. constructor( attributeData, dualBuffer ) {
  37103. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  37104. this.type = attributeData.type;
  37105. this.bufferType = attributeData.bufferType;
  37106. this.pbo = attributeData.pbo;
  37107. this.byteLength = attributeData.byteLength;
  37108. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  37109. this.version = attributeData.version;
  37110. this.isInteger = attributeData.isInteger;
  37111. this.activeBufferIndex = 0;
  37112. this.baseId = attributeData.id;
  37113. }
  37114. get id() {
  37115. return `${ this.baseId }|${ this.activeBufferIndex }`;
  37116. }
  37117. get bufferGPU() {
  37118. return this.buffers[ this.activeBufferIndex ];
  37119. }
  37120. get transformBuffer() {
  37121. return this.buffers[ this.activeBufferIndex ^ 1 ];
  37122. }
  37123. switchBuffers() {
  37124. this.activeBufferIndex ^= 1;
  37125. }
  37126. }
  37127. /**
  37128. * A WebGL 2 backend utility module for managing shader attributes.
  37129. *
  37130. * @private
  37131. */
  37132. class WebGLAttributeUtils {
  37133. /**
  37134. * Constructs a new utility object.
  37135. *
  37136. * @param {WebGLBackend} backend - The WebGL 2 backend.
  37137. */
  37138. constructor( backend ) {
  37139. /**
  37140. * A reference to the WebGL 2 backend.
  37141. *
  37142. * @type {WebGLBackend}
  37143. */
  37144. this.backend = backend;
  37145. }
  37146. /**
  37147. * Creates the GPU buffer for the given buffer attribute.
  37148. *
  37149. * @param {BufferAttribute} attribute - The buffer attribute.
  37150. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  37151. */
  37152. createAttribute( attribute, bufferType ) {
  37153. const backend = this.backend;
  37154. const { gl } = backend;
  37155. const array = attribute.array;
  37156. const usage = attribute.usage || gl.STATIC_DRAW;
  37157. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37158. const bufferData = backend.get( bufferAttribute );
  37159. let bufferGPU = bufferData.bufferGPU;
  37160. if ( bufferGPU === undefined ) {
  37161. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  37162. bufferData.bufferGPU = bufferGPU;
  37163. bufferData.bufferType = bufferType;
  37164. bufferData.version = bufferAttribute.version;
  37165. }
  37166. //attribute.onUploadCallback();
  37167. let type;
  37168. if ( array instanceof Float32Array ) {
  37169. type = gl.FLOAT;
  37170. } else if ( array instanceof Uint16Array ) {
  37171. if ( attribute.isFloat16BufferAttribute ) {
  37172. type = gl.HALF_FLOAT;
  37173. } else {
  37174. type = gl.UNSIGNED_SHORT;
  37175. }
  37176. } else if ( array instanceof Int16Array ) {
  37177. type = gl.SHORT;
  37178. } else if ( array instanceof Uint32Array ) {
  37179. type = gl.UNSIGNED_INT;
  37180. } else if ( array instanceof Int32Array ) {
  37181. type = gl.INT;
  37182. } else if ( array instanceof Int8Array ) {
  37183. type = gl.BYTE;
  37184. } else if ( array instanceof Uint8Array ) {
  37185. type = gl.UNSIGNED_BYTE;
  37186. } else if ( array instanceof Uint8ClampedArray ) {
  37187. type = gl.UNSIGNED_BYTE;
  37188. } else {
  37189. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  37190. }
  37191. let attributeData = {
  37192. bufferGPU,
  37193. bufferType,
  37194. type,
  37195. byteLength: array.byteLength,
  37196. bytesPerElement: array.BYTES_PER_ELEMENT,
  37197. version: attribute.version,
  37198. pbo: attribute.pbo,
  37199. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  37200. id: _id$1 ++
  37201. };
  37202. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  37203. // create buffer for transform feedback use
  37204. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  37205. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  37206. }
  37207. backend.set( attribute, attributeData );
  37208. }
  37209. /**
  37210. * Updates the GPU buffer of the given buffer attribute.
  37211. *
  37212. * @param {BufferAttribute} attribute - The buffer attribute.
  37213. */
  37214. updateAttribute( attribute ) {
  37215. const backend = this.backend;
  37216. const { gl } = backend;
  37217. const array = attribute.array;
  37218. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37219. const bufferData = backend.get( bufferAttribute );
  37220. const bufferType = bufferData.bufferType;
  37221. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  37222. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  37223. if ( updateRanges.length === 0 ) {
  37224. // Not using update ranges
  37225. gl.bufferSubData( bufferType, 0, array );
  37226. } else {
  37227. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  37228. const range = updateRanges[ i ];
  37229. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  37230. array, range.start, range.count );
  37231. }
  37232. bufferAttribute.clearUpdateRanges();
  37233. }
  37234. gl.bindBuffer( bufferType, null );
  37235. bufferData.version = bufferAttribute.version;
  37236. }
  37237. /**
  37238. * Destroys the GPU buffer of the given buffer attribute.
  37239. *
  37240. * @param {BufferAttribute} attribute - The buffer attribute.
  37241. */
  37242. destroyAttribute( attribute ) {
  37243. const backend = this.backend;
  37244. const { gl } = backend;
  37245. if ( attribute.isInterleavedBufferAttribute ) {
  37246. backend.delete( attribute.data );
  37247. }
  37248. const attributeData = backend.get( attribute );
  37249. gl.deleteBuffer( attributeData.bufferGPU );
  37250. backend.delete( attribute );
  37251. }
  37252. /**
  37253. * This method performs a readback operation by moving buffer data from
  37254. * a storage buffer attribute from the GPU to the CPU.
  37255. *
  37256. * @async
  37257. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  37258. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  37259. */
  37260. async getArrayBufferAsync( attribute ) {
  37261. const backend = this.backend;
  37262. const { gl } = backend;
  37263. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  37264. const { bufferGPU } = backend.get( bufferAttribute );
  37265. const array = attribute.array;
  37266. const byteLength = array.byteLength;
  37267. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  37268. const writeBuffer = gl.createBuffer();
  37269. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  37270. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  37271. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  37272. await backend.utils._clientWaitAsync();
  37273. const dstBuffer = new attribute.array.constructor( array.length );
  37274. // Ensure the buffer is bound before reading
  37275. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  37276. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  37277. gl.deleteBuffer( writeBuffer );
  37278. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  37279. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  37280. return dstBuffer.buffer;
  37281. }
  37282. /**
  37283. * Creates a WebGL buffer with the given data.
  37284. *
  37285. * @private
  37286. * @param {WebGL2RenderingContext} gl - The rendering context.
  37287. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  37288. * @param {TypedArray} array - The array of the buffer attribute.
  37289. * @param {GLenum} usage - The usage.
  37290. * @return {WebGLBuffer} The WebGL buffer.
  37291. */
  37292. _createBuffer( gl, bufferType, array, usage ) {
  37293. const bufferGPU = gl.createBuffer();
  37294. gl.bindBuffer( bufferType, bufferGPU );
  37295. gl.bufferData( bufferType, array, usage );
  37296. gl.bindBuffer( bufferType, null );
  37297. return bufferGPU;
  37298. }
  37299. }
  37300. let initialized$1 = false, equationToGL, factorToGL;
  37301. /**
  37302. * A WebGL 2 backend utility module for managing the WebGL state.
  37303. *
  37304. * The major goal of this module is to reduce the number of state changes
  37305. * by caching the WEbGL state with a series of variables. In this way, the
  37306. * renderer only executes state change commands when necessary which
  37307. * improves the overall performance.
  37308. *
  37309. * @private
  37310. */
  37311. class WebGLState {
  37312. /**
  37313. * Constructs a new utility object.
  37314. *
  37315. * @param {WebGLBackend} backend - The WebGL 2 backend.
  37316. */
  37317. constructor( backend ) {
  37318. /**
  37319. * A reference to the WebGL 2 backend.
  37320. *
  37321. * @type {WebGLBackend}
  37322. */
  37323. this.backend = backend;
  37324. /**
  37325. * A reference to the rendering context.
  37326. *
  37327. * @type {WebGL2RenderingContext}
  37328. */
  37329. this.gl = this.backend.gl;
  37330. // Below properties are intended to cache
  37331. // the WebGL state and are not explicitly
  37332. // documented for convenience reasons.
  37333. this.enabled = {};
  37334. this.currentFlipSided = null;
  37335. this.currentCullFace = null;
  37336. this.currentProgram = null;
  37337. this.currentBlendingEnabled = false;
  37338. this.currentBlending = null;
  37339. this.currentBlendSrc = null;
  37340. this.currentBlendDst = null;
  37341. this.currentBlendSrcAlpha = null;
  37342. this.currentBlendDstAlpha = null;
  37343. this.currentPremultipledAlpha = null;
  37344. this.currentPolygonOffsetFactor = null;
  37345. this.currentPolygonOffsetUnits = null;
  37346. this.currentColorMask = null;
  37347. this.currentDepthFunc = null;
  37348. this.currentDepthMask = null;
  37349. this.currentStencilFunc = null;
  37350. this.currentStencilRef = null;
  37351. this.currentStencilFuncMask = null;
  37352. this.currentStencilFail = null;
  37353. this.currentStencilZFail = null;
  37354. this.currentStencilZPass = null;
  37355. this.currentStencilMask = null;
  37356. this.currentLineWidth = null;
  37357. this.currentClippingPlanes = 0;
  37358. this.currentBoundFramebuffers = {};
  37359. this.currentDrawbuffers = new WeakMap();
  37360. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  37361. this.currentTextureSlot = null;
  37362. this.currentBoundTextures = {};
  37363. this.currentBoundBufferBases = {};
  37364. if ( initialized$1 === false ) {
  37365. this._init();
  37366. initialized$1 = true;
  37367. }
  37368. }
  37369. /**
  37370. * Inits the state of the utility.
  37371. *
  37372. * @private
  37373. */
  37374. _init() {
  37375. const gl = this.gl;
  37376. // Store only WebGL constants here.
  37377. equationToGL = {
  37378. [ AddEquation ]: gl.FUNC_ADD,
  37379. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  37380. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  37381. };
  37382. factorToGL = {
  37383. [ ZeroFactor ]: gl.ZERO,
  37384. [ OneFactor ]: gl.ONE,
  37385. [ SrcColorFactor ]: gl.SRC_COLOR,
  37386. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  37387. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  37388. [ DstColorFactor ]: gl.DST_COLOR,
  37389. [ DstAlphaFactor ]: gl.DST_ALPHA,
  37390. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  37391. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  37392. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  37393. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  37394. };
  37395. }
  37396. /**
  37397. * Enables the given WebGL capability.
  37398. *
  37399. * This method caches the capability state so
  37400. * `gl.enable()` is only called when necessary.
  37401. *
  37402. * @param {GLenum} id - The capability to enable.
  37403. */
  37404. enable( id ) {
  37405. const { enabled } = this;
  37406. if ( enabled[ id ] !== true ) {
  37407. this.gl.enable( id );
  37408. enabled[ id ] = true;
  37409. }
  37410. }
  37411. /**
  37412. * Disables the given WebGL capability.
  37413. *
  37414. * This method caches the capability state so
  37415. * `gl.disable()` is only called when necessary.
  37416. *
  37417. * @param {GLenum} id - The capability to enable.
  37418. */
  37419. disable( id ) {
  37420. const { enabled } = this;
  37421. if ( enabled[ id ] !== false ) {
  37422. this.gl.disable( id );
  37423. enabled[ id ] = false;
  37424. }
  37425. }
  37426. /**
  37427. * Specifies whether polygons are front- or back-facing
  37428. * by setting the winding orientation.
  37429. *
  37430. * This method caches the state so `gl.frontFace()` is only
  37431. * called when necessary.
  37432. *
  37433. * @param {Boolean} flipSided - Whether triangles flipped their sides or not.
  37434. */
  37435. setFlipSided( flipSided ) {
  37436. if ( this.currentFlipSided !== flipSided ) {
  37437. const { gl } = this;
  37438. if ( flipSided ) {
  37439. gl.frontFace( gl.CW );
  37440. } else {
  37441. gl.frontFace( gl.CCW );
  37442. }
  37443. this.currentFlipSided = flipSided;
  37444. }
  37445. }
  37446. /**
  37447. * Specifies whether or not front- and/or back-facing
  37448. * polygons can be culled.
  37449. *
  37450. * This method caches the state so `gl.cullFace()` is only
  37451. * called when necessary.
  37452. *
  37453. * @param {Number} cullFace - Defines which polygons are candidates for culling.
  37454. */
  37455. setCullFace( cullFace ) {
  37456. const { gl } = this;
  37457. if ( cullFace !== CullFaceNone ) {
  37458. this.enable( gl.CULL_FACE );
  37459. if ( cullFace !== this.currentCullFace ) {
  37460. if ( cullFace === CullFaceBack ) {
  37461. gl.cullFace( gl.BACK );
  37462. } else if ( cullFace === CullFaceFront ) {
  37463. gl.cullFace( gl.FRONT );
  37464. } else {
  37465. gl.cullFace( gl.FRONT_AND_BACK );
  37466. }
  37467. }
  37468. } else {
  37469. this.disable( gl.CULL_FACE );
  37470. }
  37471. this.currentCullFace = cullFace;
  37472. }
  37473. /**
  37474. * Specifies the width of line primitives.
  37475. *
  37476. * This method caches the state so `gl.lineWidth()` is only
  37477. * called when necessary.
  37478. *
  37479. * @param {Number} width - The line width.
  37480. */
  37481. setLineWidth( width ) {
  37482. const { currentLineWidth, gl } = this;
  37483. if ( width !== currentLineWidth ) {
  37484. gl.lineWidth( width );
  37485. this.currentLineWidth = width;
  37486. }
  37487. }
  37488. /**
  37489. * Defines the blending.
  37490. *
  37491. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  37492. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  37493. *
  37494. * @param {Number} blending - The blending type.
  37495. * @param {Number} blendEquation - The blending equation.
  37496. * @param {Number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  37497. * @param {Number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  37498. * @param {Number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  37499. * @param {Number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  37500. * @param {Number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  37501. * @param {Boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  37502. */
  37503. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  37504. const { gl } = this;
  37505. if ( blending === NoBlending ) {
  37506. if ( this.currentBlendingEnabled === true ) {
  37507. this.disable( gl.BLEND );
  37508. this.currentBlendingEnabled = false;
  37509. }
  37510. return;
  37511. }
  37512. if ( this.currentBlendingEnabled === false ) {
  37513. this.enable( gl.BLEND );
  37514. this.currentBlendingEnabled = true;
  37515. }
  37516. if ( blending !== CustomBlending ) {
  37517. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  37518. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  37519. gl.blendEquation( gl.FUNC_ADD );
  37520. this.currentBlendEquation = AddEquation;
  37521. this.currentBlendEquationAlpha = AddEquation;
  37522. }
  37523. if ( premultipliedAlpha ) {
  37524. switch ( blending ) {
  37525. case NormalBlending:
  37526. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37527. break;
  37528. case AdditiveBlending:
  37529. gl.blendFunc( gl.ONE, gl.ONE );
  37530. break;
  37531. case SubtractiveBlending:
  37532. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37533. break;
  37534. case MultiplyBlending:
  37535. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  37536. break;
  37537. default:
  37538. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  37539. break;
  37540. }
  37541. } else {
  37542. switch ( blending ) {
  37543. case NormalBlending:
  37544. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  37545. break;
  37546. case AdditiveBlending:
  37547. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  37548. break;
  37549. case SubtractiveBlending:
  37550. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  37551. break;
  37552. case MultiplyBlending:
  37553. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  37554. break;
  37555. default:
  37556. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  37557. break;
  37558. }
  37559. }
  37560. this.currentBlendSrc = null;
  37561. this.currentBlendDst = null;
  37562. this.currentBlendSrcAlpha = null;
  37563. this.currentBlendDstAlpha = null;
  37564. this.currentBlending = blending;
  37565. this.currentPremultipledAlpha = premultipliedAlpha;
  37566. }
  37567. return;
  37568. }
  37569. // custom blending
  37570. blendEquationAlpha = blendEquationAlpha || blendEquation;
  37571. blendSrcAlpha = blendSrcAlpha || blendSrc;
  37572. blendDstAlpha = blendDstAlpha || blendDst;
  37573. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  37574. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  37575. this.currentBlendEquation = blendEquation;
  37576. this.currentBlendEquationAlpha = blendEquationAlpha;
  37577. }
  37578. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  37579. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  37580. this.currentBlendSrc = blendSrc;
  37581. this.currentBlendDst = blendDst;
  37582. this.currentBlendSrcAlpha = blendSrcAlpha;
  37583. this.currentBlendDstAlpha = blendDstAlpha;
  37584. }
  37585. this.currentBlending = blending;
  37586. this.currentPremultipledAlpha = false;
  37587. }
  37588. /**
  37589. * Specifies whether colors can be written when rendering
  37590. * into a framebuffer or not.
  37591. *
  37592. * This method caches the state so `gl.colorMask()` is only
  37593. * called when necessary.
  37594. *
  37595. * @param {Boolean} colorMask - The color mask.
  37596. */
  37597. setColorMask( colorMask ) {
  37598. if ( this.currentColorMask !== colorMask ) {
  37599. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  37600. this.currentColorMask = colorMask;
  37601. }
  37602. }
  37603. /**
  37604. * Specifies whether the depth test is enabled or not.
  37605. *
  37606. * @param {Boolean} depthTest - Whether the depth test is enabled or not.
  37607. */
  37608. setDepthTest( depthTest ) {
  37609. const { gl } = this;
  37610. if ( depthTest ) {
  37611. this.enable( gl.DEPTH_TEST );
  37612. } else {
  37613. this.disable( gl.DEPTH_TEST );
  37614. }
  37615. }
  37616. /**
  37617. * Specifies whether depth values can be written when rendering
  37618. * into a framebuffer or not.
  37619. *
  37620. * This method caches the state so `gl.depthMask()` is only
  37621. * called when necessary.
  37622. *
  37623. * @param {Boolean} depthMask - The depth mask.
  37624. */
  37625. setDepthMask( depthMask ) {
  37626. if ( this.currentDepthMask !== depthMask ) {
  37627. this.gl.depthMask( depthMask );
  37628. this.currentDepthMask = depthMask;
  37629. }
  37630. }
  37631. /**
  37632. * Specifies the depth compare function.
  37633. *
  37634. * This method caches the state so `gl.depthFunc()` is only
  37635. * called when necessary.
  37636. *
  37637. * @param {Number} depthFunc - The depth compare function.
  37638. */
  37639. setDepthFunc( depthFunc ) {
  37640. if ( this.currentDepthFunc !== depthFunc ) {
  37641. const { gl } = this;
  37642. switch ( depthFunc ) {
  37643. case NeverDepth:
  37644. gl.depthFunc( gl.NEVER );
  37645. break;
  37646. case AlwaysDepth:
  37647. gl.depthFunc( gl.ALWAYS );
  37648. break;
  37649. case LessDepth:
  37650. gl.depthFunc( gl.LESS );
  37651. break;
  37652. case LessEqualDepth:
  37653. gl.depthFunc( gl.LEQUAL );
  37654. break;
  37655. case EqualDepth:
  37656. gl.depthFunc( gl.EQUAL );
  37657. break;
  37658. case GreaterEqualDepth:
  37659. gl.depthFunc( gl.GEQUAL );
  37660. break;
  37661. case GreaterDepth:
  37662. gl.depthFunc( gl.GREATER );
  37663. break;
  37664. case NotEqualDepth:
  37665. gl.depthFunc( gl.NOTEQUAL );
  37666. break;
  37667. default:
  37668. gl.depthFunc( gl.LEQUAL );
  37669. }
  37670. this.currentDepthFunc = depthFunc;
  37671. }
  37672. }
  37673. /**
  37674. * Specifies whether the stencil test is enabled or not.
  37675. *
  37676. * @param {Boolean} stencilTest - Whether the stencil test is enabled or not.
  37677. */
  37678. setStencilTest( stencilTest ) {
  37679. const { gl } = this;
  37680. if ( stencilTest ) {
  37681. this.enable( gl.STENCIL_TEST );
  37682. } else {
  37683. this.disable( gl.STENCIL_TEST );
  37684. }
  37685. }
  37686. /**
  37687. * Specifies whether stencil values can be written when rendering
  37688. * into a framebuffer or not.
  37689. *
  37690. * This method caches the state so `gl.stencilMask()` is only
  37691. * called when necessary.
  37692. *
  37693. * @param {Boolean} stencilMask - The stencil mask.
  37694. */
  37695. setStencilMask( stencilMask ) {
  37696. if ( this.currentStencilMask !== stencilMask ) {
  37697. this.gl.stencilMask( stencilMask );
  37698. this.currentStencilMask = stencilMask;
  37699. }
  37700. }
  37701. /**
  37702. * Specifies whether the stencil test functions.
  37703. *
  37704. * This method caches the state so `gl.stencilFunc()` is only
  37705. * called when necessary.
  37706. *
  37707. * @param {Number} stencilFunc - The stencil compare function.
  37708. * @param {Number} stencilRef - The reference value for the stencil test.
  37709. * @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.
  37710. */
  37711. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  37712. if ( this.currentStencilFunc !== stencilFunc ||
  37713. this.currentStencilRef !== stencilRef ||
  37714. this.currentStencilFuncMask !== stencilMask ) {
  37715. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  37716. this.currentStencilFunc = stencilFunc;
  37717. this.currentStencilRef = stencilRef;
  37718. this.currentStencilFuncMask = stencilMask;
  37719. }
  37720. }
  37721. /**
  37722. * Specifies whether the stencil test operation.
  37723. *
  37724. * This method caches the state so `gl.stencilOp()` is only
  37725. * called when necessary.
  37726. *
  37727. * @param {Number} stencilFail - The function to use when the stencil test fails.
  37728. * @param {Number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  37729. * @param {Number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  37730. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  37731. */
  37732. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  37733. if ( this.currentStencilFail !== stencilFail ||
  37734. this.currentStencilZFail !== stencilZFail ||
  37735. this.currentStencilZPass !== stencilZPass ) {
  37736. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  37737. this.currentStencilFail = stencilFail;
  37738. this.currentStencilZFail = stencilZFail;
  37739. this.currentStencilZPass = stencilZPass;
  37740. }
  37741. }
  37742. /**
  37743. * Configures the WebGL state for the given material.
  37744. *
  37745. * @param {Material} material - The material to configure the state for.
  37746. * @param {Number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  37747. * @param {Number} hardwareClippingPlanes - The number of hardware clipping planes.
  37748. */
  37749. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  37750. const { gl } = this;
  37751. material.side === DoubleSide
  37752. ? this.disable( gl.CULL_FACE )
  37753. : this.enable( gl.CULL_FACE );
  37754. let flipSided = ( material.side === BackSide );
  37755. if ( frontFaceCW ) flipSided = ! flipSided;
  37756. this.setFlipSided( flipSided );
  37757. ( material.blending === NormalBlending && material.transparent === false )
  37758. ? this.setBlending( NoBlending )
  37759. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  37760. this.setDepthFunc( material.depthFunc );
  37761. this.setDepthTest( material.depthTest );
  37762. this.setDepthMask( material.depthWrite );
  37763. this.setColorMask( material.colorWrite );
  37764. const stencilWrite = material.stencilWrite;
  37765. this.setStencilTest( stencilWrite );
  37766. if ( stencilWrite ) {
  37767. this.setStencilMask( material.stencilWriteMask );
  37768. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  37769. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  37770. }
  37771. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  37772. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  37773. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  37774. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  37775. if ( hardwareClippingPlanes > 0 ) {
  37776. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  37777. const CLIP_DISTANCE0_WEBGL = 0x3000;
  37778. for ( let i = 0; i < 8; i ++ ) {
  37779. if ( i < hardwareClippingPlanes ) {
  37780. this.enable( CLIP_DISTANCE0_WEBGL + i );
  37781. } else {
  37782. this.disable( CLIP_DISTANCE0_WEBGL + i );
  37783. }
  37784. }
  37785. }
  37786. }
  37787. }
  37788. /**
  37789. * Specifies the polygon offset.
  37790. *
  37791. * This method caches the state so `gl.polygonOffset()` is only
  37792. * called when necessary.
  37793. *
  37794. * @param {Boolean} polygonOffset - Whether polygon offset is enabled or not.
  37795. * @param {Number} factor - The scale factor for the variable depth offset for each polygon.
  37796. * @param {Number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  37797. */
  37798. setPolygonOffset( polygonOffset, factor, units ) {
  37799. const { gl } = this;
  37800. if ( polygonOffset ) {
  37801. this.enable( gl.POLYGON_OFFSET_FILL );
  37802. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  37803. gl.polygonOffset( factor, units );
  37804. this.currentPolygonOffsetFactor = factor;
  37805. this.currentPolygonOffsetUnits = units;
  37806. }
  37807. } else {
  37808. this.disable( gl.POLYGON_OFFSET_FILL );
  37809. }
  37810. }
  37811. /**
  37812. * Defines the usage of the given WebGL program.
  37813. *
  37814. * This method caches the state so `gl.useProgram()` is only
  37815. * called when necessary.
  37816. *
  37817. * @param {WebGLProgram} program - The WebGL program to use.
  37818. * @return {Boolean} Whether a program change has been executed or not.
  37819. */
  37820. useProgram( program ) {
  37821. if ( this.currentProgram !== program ) {
  37822. this.gl.useProgram( program );
  37823. this.currentProgram = program;
  37824. return true;
  37825. }
  37826. return false;
  37827. }
  37828. // framebuffer
  37829. /**
  37830. * Binds the given framebuffer.
  37831. *
  37832. * This method caches the state so `gl.bindFramebuffer()` is only
  37833. * called when necessary.
  37834. *
  37835. * @param {Number} target - The binding point (target).
  37836. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  37837. * @return {Boolean} Whether a bind has been executed or not.
  37838. */
  37839. bindFramebuffer( target, framebuffer ) {
  37840. const { gl, currentBoundFramebuffers } = this;
  37841. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  37842. gl.bindFramebuffer( target, framebuffer );
  37843. currentBoundFramebuffers[ target ] = framebuffer;
  37844. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  37845. if ( target === gl.DRAW_FRAMEBUFFER ) {
  37846. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  37847. }
  37848. if ( target === gl.FRAMEBUFFER ) {
  37849. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  37850. }
  37851. return true;
  37852. }
  37853. return false;
  37854. }
  37855. /**
  37856. * Defines draw buffers to which fragment colors are written into.
  37857. * Configures the MRT setup of custom framebuffers.
  37858. *
  37859. * This method caches the state so `gl.drawBuffers()` is only
  37860. * called when necessary.
  37861. *
  37862. * @param {RenderContext} renderContext - The render context.
  37863. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  37864. */
  37865. drawBuffers( renderContext, framebuffer ) {
  37866. const { gl } = this;
  37867. let drawBuffers = [];
  37868. let needsUpdate = false;
  37869. if ( renderContext.textures !== null ) {
  37870. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  37871. if ( drawBuffers === undefined ) {
  37872. drawBuffers = [];
  37873. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  37874. }
  37875. const textures = renderContext.textures;
  37876. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  37877. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  37878. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  37879. }
  37880. drawBuffers.length = textures.length;
  37881. needsUpdate = true;
  37882. }
  37883. } else {
  37884. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  37885. drawBuffers[ 0 ] = gl.BACK;
  37886. needsUpdate = true;
  37887. }
  37888. }
  37889. if ( needsUpdate ) {
  37890. gl.drawBuffers( drawBuffers );
  37891. }
  37892. }
  37893. // texture
  37894. /**
  37895. * Makes the given texture unit active.
  37896. *
  37897. * This method caches the state so `gl.activeTexture()` is only
  37898. * called when necessary.
  37899. *
  37900. * @param {Number} webglSlot - The texture unit to make active.
  37901. */
  37902. activeTexture( webglSlot ) {
  37903. const { gl, currentTextureSlot, maxTextures } = this;
  37904. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  37905. if ( currentTextureSlot !== webglSlot ) {
  37906. gl.activeTexture( webglSlot );
  37907. this.currentTextureSlot = webglSlot;
  37908. }
  37909. }
  37910. /**
  37911. * Binds the given WebGL texture to a target.
  37912. *
  37913. * This method caches the state so `gl.bindTexture()` is only
  37914. * called when necessary.
  37915. *
  37916. * @param {Number} webglType - The binding point (target).
  37917. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  37918. * @param {Number} webglSlot - The texture.
  37919. */
  37920. bindTexture( webglType, webglTexture, webglSlot ) {
  37921. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  37922. if ( webglSlot === undefined ) {
  37923. if ( currentTextureSlot === null ) {
  37924. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  37925. } else {
  37926. webglSlot = currentTextureSlot;
  37927. }
  37928. }
  37929. let boundTexture = currentBoundTextures[ webglSlot ];
  37930. if ( boundTexture === undefined ) {
  37931. boundTexture = { type: undefined, texture: undefined };
  37932. currentBoundTextures[ webglSlot ] = boundTexture;
  37933. }
  37934. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  37935. if ( currentTextureSlot !== webglSlot ) {
  37936. gl.activeTexture( webglSlot );
  37937. this.currentTextureSlot = webglSlot;
  37938. }
  37939. gl.bindTexture( webglType, webglTexture );
  37940. boundTexture.type = webglType;
  37941. boundTexture.texture = webglTexture;
  37942. }
  37943. }
  37944. /**
  37945. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  37946. *
  37947. * This method caches the state so `gl.bindBufferBase()` is only
  37948. * called when necessary.
  37949. *
  37950. * @param {Number} target - The target for the bind operation.
  37951. * @param {Number} index - The index of the target.
  37952. * @param {WebGLBuffer} buffer - The WebGL buffer.
  37953. * @return {Boolean} Whether a bind has been executed or not.
  37954. */
  37955. bindBufferBase( target, index, buffer ) {
  37956. const { gl } = this;
  37957. const key = `${target}-${index}`;
  37958. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  37959. gl.bindBufferBase( target, index, buffer );
  37960. this.currentBoundBufferBases[ key ] = buffer;
  37961. return true;
  37962. }
  37963. return false;
  37964. }
  37965. /**
  37966. * Unbinds the current bound texture.
  37967. *
  37968. * This method caches the state so `gl.bindTexture()` is only
  37969. * called when necessary.
  37970. */
  37971. unbindTexture() {
  37972. const { gl, currentTextureSlot, currentBoundTextures } = this;
  37973. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  37974. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  37975. gl.bindTexture( boundTexture.type, null );
  37976. boundTexture.type = undefined;
  37977. boundTexture.texture = undefined;
  37978. }
  37979. }
  37980. }
  37981. /**
  37982. * A WebGL 2 backend utility module with common helpers.
  37983. *
  37984. * @private
  37985. */
  37986. class WebGLUtils {
  37987. /**
  37988. * Constructs a new utility object.
  37989. *
  37990. * @param {WebGLBackend} backend - The WebGL 2 backend.
  37991. */
  37992. constructor( backend ) {
  37993. /**
  37994. * A reference to the WebGL 2 backend.
  37995. *
  37996. * @type {WebGLBackend}
  37997. */
  37998. this.backend = backend;
  37999. /**
  38000. * A reference to the rendering context.
  38001. *
  38002. * @type {WebGL2RenderingContext}
  38003. */
  38004. this.gl = this.backend.gl;
  38005. /**
  38006. * A reference to a backend module holding extension-related
  38007. * utility functions.
  38008. *
  38009. * @type {WebGLExtensions}
  38010. */
  38011. this.extensions = backend.extensions;
  38012. }
  38013. /**
  38014. * Converts the given three.js constant into a WebGL constant.
  38015. * The method currently supports the conversion of texture formats
  38016. * and types.
  38017. *
  38018. * @param {Number} p - The three.js constant.
  38019. * @param {String} [colorSpace=NoColorSpace] - The color space.
  38020. * @return {Number} The corresponding WebGL constant.
  38021. */
  38022. convert( p, colorSpace = NoColorSpace ) {
  38023. const { gl, extensions } = this;
  38024. let extension;
  38025. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  38026. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  38027. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  38028. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  38029. if ( p === ByteType ) return gl.BYTE;
  38030. if ( p === ShortType ) return gl.SHORT;
  38031. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  38032. if ( p === IntType ) return gl.INT;
  38033. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  38034. if ( p === FloatType ) return gl.FLOAT;
  38035. if ( p === HalfFloatType ) {
  38036. return gl.HALF_FLOAT;
  38037. }
  38038. if ( p === AlphaFormat ) return gl.ALPHA;
  38039. if ( p === RGBFormat ) return gl.RGB;
  38040. if ( p === RGBAFormat ) return gl.RGBA;
  38041. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  38042. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  38043. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  38044. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  38045. // WebGL2 formats.
  38046. if ( p === RedFormat ) return gl.RED;
  38047. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  38048. if ( p === RGFormat ) return gl.RG;
  38049. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  38050. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  38051. // S3TC
  38052. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  38053. if ( colorSpace === SRGBColorSpace ) {
  38054. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  38055. if ( extension !== null ) {
  38056. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  38057. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  38058. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  38059. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  38060. } else {
  38061. return null;
  38062. }
  38063. } else {
  38064. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  38065. if ( extension !== null ) {
  38066. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  38067. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  38068. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  38069. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  38070. } else {
  38071. return null;
  38072. }
  38073. }
  38074. }
  38075. // PVRTC
  38076. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  38077. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  38078. if ( extension !== null ) {
  38079. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  38080. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  38081. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  38082. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  38083. } else {
  38084. return null;
  38085. }
  38086. }
  38087. // ETC
  38088. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  38089. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  38090. if ( extension !== null ) {
  38091. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  38092. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  38093. } else {
  38094. return null;
  38095. }
  38096. }
  38097. // ASTC
  38098. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  38099. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  38100. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  38101. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  38102. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  38103. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  38104. if ( extension !== null ) {
  38105. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  38106. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  38107. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  38108. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  38109. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  38110. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  38111. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  38112. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  38113. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  38114. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  38115. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  38116. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  38117. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  38118. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  38119. } else {
  38120. return null;
  38121. }
  38122. }
  38123. // BPTC
  38124. if ( p === RGBA_BPTC_Format ) {
  38125. extension = extensions.get( 'EXT_texture_compression_bptc' );
  38126. if ( extension !== null ) {
  38127. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  38128. } else {
  38129. return null;
  38130. }
  38131. }
  38132. // RGTC
  38133. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  38134. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  38135. if ( extension !== null ) {
  38136. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  38137. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  38138. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  38139. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  38140. } else {
  38141. return null;
  38142. }
  38143. }
  38144. //
  38145. if ( p === UnsignedInt248Type ) {
  38146. return gl.UNSIGNED_INT_24_8;
  38147. }
  38148. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  38149. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  38150. }
  38151. /**
  38152. * This method can be used to synchronize the CPU with the GPU by waiting until
  38153. * ongoing GPU commands have been completed.
  38154. *
  38155. * @private
  38156. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  38157. */
  38158. _clientWaitAsync() {
  38159. const { gl } = this;
  38160. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  38161. gl.flush();
  38162. return new Promise( ( resolve, reject ) => {
  38163. function test() {
  38164. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  38165. if ( res === gl.WAIT_FAILED ) {
  38166. gl.deleteSync( sync );
  38167. reject();
  38168. return;
  38169. }
  38170. if ( res === gl.TIMEOUT_EXPIRED ) {
  38171. requestAnimationFrame( test );
  38172. return;
  38173. }
  38174. gl.deleteSync( sync );
  38175. resolve();
  38176. }
  38177. test();
  38178. } );
  38179. }
  38180. }
  38181. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  38182. /**
  38183. * A WebGL 2 backend utility module for managing textures.
  38184. *
  38185. * @private
  38186. */
  38187. class WebGLTextureUtils {
  38188. /**
  38189. * Constructs a new utility object.
  38190. *
  38191. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38192. */
  38193. constructor( backend ) {
  38194. /**
  38195. * A reference to the WebGL 2 backend.
  38196. *
  38197. * @type {WebGLBackend}
  38198. */
  38199. this.backend = backend;
  38200. /**
  38201. * A reference to the rendering context.
  38202. *
  38203. * @type {WebGL2RenderingContext}
  38204. */
  38205. this.gl = backend.gl;
  38206. /**
  38207. * A reference to a backend module holding extension-related
  38208. * utility functions.
  38209. *
  38210. * @type {WebGLExtensions}
  38211. */
  38212. this.extensions = backend.extensions;
  38213. /**
  38214. * A dictionary for managing default textures. The key
  38215. * is the binding point (target), the value the WEbGL texture object.
  38216. *
  38217. * @type {Object<GLenum,WebGLTexture>}
  38218. */
  38219. this.defaultTextures = {};
  38220. if ( initialized === false ) {
  38221. this._init();
  38222. initialized = true;
  38223. }
  38224. }
  38225. /**
  38226. * Inits the state of the utility.
  38227. *
  38228. * @private
  38229. */
  38230. _init() {
  38231. const gl = this.gl;
  38232. // Store only WebGL constants here.
  38233. wrappingToGL = {
  38234. [ RepeatWrapping ]: gl.REPEAT,
  38235. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  38236. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  38237. };
  38238. filterToGL = {
  38239. [ NearestFilter ]: gl.NEAREST,
  38240. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  38241. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  38242. [ LinearFilter ]: gl.LINEAR,
  38243. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  38244. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  38245. };
  38246. compareToGL = {
  38247. [ NeverCompare ]: gl.NEVER,
  38248. [ AlwaysCompare ]: gl.ALWAYS,
  38249. [ LessCompare ]: gl.LESS,
  38250. [ LessEqualCompare ]: gl.LEQUAL,
  38251. [ EqualCompare ]: gl.EQUAL,
  38252. [ GreaterEqualCompare ]: gl.GEQUAL,
  38253. [ GreaterCompare ]: gl.GREATER,
  38254. [ NotEqualCompare ]: gl.NOTEQUAL
  38255. };
  38256. }
  38257. /**
  38258. * Returns the native texture type for the given texture.
  38259. *
  38260. * @param {Texture} texture - The texture.
  38261. * @return {GLenum} The native texture type.
  38262. */
  38263. getGLTextureType( texture ) {
  38264. const { gl } = this;
  38265. let glTextureType;
  38266. if ( texture.isCubeTexture === true ) {
  38267. glTextureType = gl.TEXTURE_CUBE_MAP;
  38268. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  38269. glTextureType = gl.TEXTURE_2D_ARRAY;
  38270. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  38271. glTextureType = gl.TEXTURE_3D;
  38272. } else {
  38273. glTextureType = gl.TEXTURE_2D;
  38274. }
  38275. return glTextureType;
  38276. }
  38277. /**
  38278. * Returns the native texture type for the given texture.
  38279. *
  38280. * @param {String?} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  38281. * @param {GLenum} glFormat - The WebGL format.
  38282. * @param {GLenum} glType - The WebGL type.
  38283. * @param {String} colorSpace - The texture's color space.
  38284. * @param {Boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  38285. * @return {GLenum} The internal format.
  38286. */
  38287. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  38288. const { gl, extensions } = this;
  38289. if ( internalFormatName !== null ) {
  38290. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  38291. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  38292. }
  38293. let internalFormat = glFormat;
  38294. if ( glFormat === gl.RED ) {
  38295. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  38296. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  38297. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  38298. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  38299. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38300. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38301. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38302. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38303. }
  38304. if ( glFormat === gl.RED_INTEGER ) {
  38305. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  38306. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  38307. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  38308. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  38309. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  38310. if ( glType === gl.INT ) internalFormat = gl.R32I;
  38311. }
  38312. if ( glFormat === gl.RG ) {
  38313. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  38314. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  38315. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  38316. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  38317. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38318. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38319. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38320. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38321. }
  38322. if ( glFormat === gl.RG_INTEGER ) {
  38323. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  38324. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  38325. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  38326. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  38327. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  38328. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  38329. }
  38330. if ( glFormat === gl.RGB ) {
  38331. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  38332. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  38333. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  38334. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  38335. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38336. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38337. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38338. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38339. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  38340. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  38341. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38342. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  38343. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  38344. }
  38345. if ( glFormat === gl.RGB_INTEGER ) {
  38346. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  38347. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  38348. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  38349. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  38350. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  38351. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  38352. }
  38353. if ( glFormat === gl.RGBA ) {
  38354. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  38355. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  38356. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  38357. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  38358. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38359. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38360. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38361. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38362. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  38363. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  38364. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  38365. }
  38366. if ( glFormat === gl.RGBA_INTEGER ) {
  38367. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  38368. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  38369. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  38370. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  38371. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  38372. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  38373. }
  38374. if ( glFormat === gl.DEPTH_COMPONENT ) {
  38375. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  38376. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  38377. }
  38378. if ( glFormat === gl.DEPTH_STENCIL ) {
  38379. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  38380. }
  38381. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  38382. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  38383. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  38384. extensions.get( 'EXT_color_buffer_float' );
  38385. }
  38386. return internalFormat;
  38387. }
  38388. /**
  38389. * Sets the texture parameters for the given texture.
  38390. *
  38391. * @param {GLenum} textureType - The texture type.
  38392. * @param {Texture} texture - The texture.
  38393. */
  38394. setTextureParameters( textureType, texture ) {
  38395. const { gl, extensions, backend } = this;
  38396. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  38397. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  38398. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  38399. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  38400. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  38401. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  38402. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  38403. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  38404. }
  38405. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  38406. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  38407. // follow WebGPU backend mapping for texture filtering
  38408. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  38409. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  38410. if ( texture.compareFunction ) {
  38411. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  38412. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  38413. }
  38414. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38415. if ( texture.magFilter === NearestFilter ) return;
  38416. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  38417. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  38418. if ( texture.anisotropy > 1 ) {
  38419. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38420. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  38421. }
  38422. }
  38423. }
  38424. /**
  38425. * Creates a default texture for the given texture that can be used
  38426. * as a placeholder until the actual texture is ready for usage.
  38427. *
  38428. * @param {Texture} texture - The texture to create a default texture for.
  38429. */
  38430. createDefaultTexture( texture ) {
  38431. const { gl, backend, defaultTextures } = this;
  38432. const glTextureType = this.getGLTextureType( texture );
  38433. let textureGPU = defaultTextures[ glTextureType ];
  38434. if ( textureGPU === undefined ) {
  38435. textureGPU = gl.createTexture();
  38436. backend.state.bindTexture( glTextureType, textureGPU );
  38437. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  38438. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  38439. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  38440. defaultTextures[ glTextureType ] = textureGPU;
  38441. }
  38442. backend.set( texture, {
  38443. textureGPU,
  38444. glTextureType,
  38445. isDefault: true
  38446. } );
  38447. }
  38448. /**
  38449. * Defines a texture on the GPU for the given texture object.
  38450. *
  38451. * @param {Texture} texture - The texture.
  38452. * @param {Object} [options={}] - Optional configuration parameter.
  38453. * @return {undefined}
  38454. */
  38455. createTexture( texture, options ) {
  38456. const { gl, backend } = this;
  38457. const { levels, width, height, depth } = options;
  38458. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  38459. const glType = backend.utils.convert( texture.type );
  38460. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  38461. const textureGPU = gl.createTexture();
  38462. const glTextureType = this.getGLTextureType( texture );
  38463. backend.state.bindTexture( glTextureType, textureGPU );
  38464. this.setTextureParameters( glTextureType, texture );
  38465. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  38466. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  38467. } else if ( texture.isData3DTexture ) {
  38468. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  38469. } else if ( ! texture.isVideoTexture ) {
  38470. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  38471. }
  38472. backend.set( texture, {
  38473. textureGPU,
  38474. glTextureType,
  38475. glFormat,
  38476. glType,
  38477. glInternalFormat
  38478. } );
  38479. }
  38480. /**
  38481. * Uploads texture buffer data to the GPU memory.
  38482. *
  38483. * @param {WebGLBuffer} buffer - The buffer data.
  38484. * @param {Texture} texture - The texture,
  38485. */
  38486. copyBufferToTexture( buffer, texture ) {
  38487. const { gl, backend } = this;
  38488. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  38489. const { width, height } = texture.source.data;
  38490. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  38491. backend.state.bindTexture( glTextureType, textureGPU );
  38492. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  38493. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  38494. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  38495. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  38496. backend.state.unbindTexture();
  38497. // debug
  38498. // const framebuffer = gl.createFramebuffer();
  38499. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  38500. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  38501. // const readout = new Float32Array( width * height * 4 );
  38502. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  38503. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  38504. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  38505. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  38506. // console.log( readout );
  38507. }
  38508. /**
  38509. * Uploads the updated texture data to the GPU.
  38510. *
  38511. * @param {Texture} texture - The texture.
  38512. * @param {Object} [options={}] - Optional configuration parameter.
  38513. */
  38514. updateTexture( texture, options ) {
  38515. const { gl } = this;
  38516. const { width, height } = options;
  38517. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  38518. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  38519. return;
  38520. const getImage = ( source ) => {
  38521. if ( source.isDataTexture ) {
  38522. return source.image.data;
  38523. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  38524. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  38525. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  38526. source instanceof OffscreenCanvas ) {
  38527. return source;
  38528. }
  38529. return source.data;
  38530. };
  38531. this.backend.state.bindTexture( glTextureType, textureGPU );
  38532. this.setTextureParameters( glTextureType, texture );
  38533. if ( texture.isCompressedTexture ) {
  38534. const mipmaps = texture.mipmaps;
  38535. const image = options.image;
  38536. for ( let i = 0; i < mipmaps.length; i ++ ) {
  38537. const mipmap = mipmaps[ i ];
  38538. if ( texture.isCompressedArrayTexture ) {
  38539. if ( texture.format !== gl.RGBA ) {
  38540. if ( glFormat !== null ) {
  38541. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  38542. } else {
  38543. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  38544. }
  38545. } else {
  38546. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  38547. }
  38548. } else {
  38549. if ( glFormat !== null ) {
  38550. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  38551. } else {
  38552. console.warn( 'Unsupported compressed texture format' );
  38553. }
  38554. }
  38555. }
  38556. } else if ( texture.isCubeTexture ) {
  38557. const images = options.images;
  38558. for ( let i = 0; i < 6; i ++ ) {
  38559. const image = getImage( images[ i ] );
  38560. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  38561. }
  38562. } else if ( texture.isDataArrayTexture ) {
  38563. const image = options.image;
  38564. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38565. } else if ( texture.isData3DTexture ) {
  38566. const image = options.image;
  38567. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  38568. } else if ( texture.isVideoTexture ) {
  38569. texture.update();
  38570. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  38571. } else {
  38572. const image = getImage( options.image );
  38573. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  38574. }
  38575. }
  38576. /**
  38577. * Generates mipmaps for the given texture.
  38578. *
  38579. * @param {Texture} texture - The texture.
  38580. */
  38581. generateMipmaps( texture ) {
  38582. const { gl, backend } = this;
  38583. const { textureGPU, glTextureType } = backend.get( texture );
  38584. backend.state.bindTexture( glTextureType, textureGPU );
  38585. gl.generateMipmap( glTextureType );
  38586. }
  38587. /**
  38588. * Deallocates the render buffers of the given render target.
  38589. *
  38590. * @param {RenderTarget} renderTarget - The render target.
  38591. */
  38592. deallocateRenderBuffers( renderTarget ) {
  38593. const { gl, backend } = this;
  38594. // remove framebuffer reference
  38595. if ( renderTarget ) {
  38596. const renderContextData = backend.get( renderTarget );
  38597. renderContextData.renderBufferStorageSetup = undefined;
  38598. if ( renderContextData.framebuffers ) {
  38599. for ( const cacheKey in renderContextData.framebuffers ) {
  38600. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  38601. }
  38602. delete renderContextData.framebuffers;
  38603. }
  38604. if ( renderContextData.depthRenderbuffer ) {
  38605. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  38606. delete renderContextData.depthRenderbuffer;
  38607. }
  38608. if ( renderContextData.stencilRenderbuffer ) {
  38609. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  38610. delete renderContextData.stencilRenderbuffer;
  38611. }
  38612. if ( renderContextData.msaaFrameBuffer ) {
  38613. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  38614. delete renderContextData.msaaFrameBuffer;
  38615. }
  38616. if ( renderContextData.msaaRenderbuffers ) {
  38617. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  38618. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  38619. }
  38620. delete renderContextData.msaaRenderbuffers;
  38621. }
  38622. }
  38623. }
  38624. /**
  38625. * Destroys the GPU data for the given texture object.
  38626. *
  38627. * @param {Texture} texture - The texture.
  38628. */
  38629. destroyTexture( texture ) {
  38630. const { gl, backend } = this;
  38631. const { textureGPU, renderTarget } = backend.get( texture );
  38632. this.deallocateRenderBuffers( renderTarget );
  38633. gl.deleteTexture( textureGPU );
  38634. backend.delete( texture );
  38635. }
  38636. /**
  38637. * Copies data of the given source texture to the given destination texture.
  38638. *
  38639. * @param {Texture} srcTexture - The source texture.
  38640. * @param {Texture} dstTexture - The destination texture.
  38641. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  38642. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  38643. * @param {Number} [level=0] - The mip level to copy.
  38644. */
  38645. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38646. const { gl, backend } = this;
  38647. const { state } = this.backend;
  38648. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  38649. let width, height, minX, minY;
  38650. let dstX, dstY;
  38651. if ( srcRegion !== null ) {
  38652. width = srcRegion.max.x - srcRegion.min.x;
  38653. height = srcRegion.max.y - srcRegion.min.y;
  38654. minX = srcRegion.min.x;
  38655. minY = srcRegion.min.y;
  38656. } else {
  38657. width = srcTexture.image.width;
  38658. height = srcTexture.image.height;
  38659. minX = 0;
  38660. minY = 0;
  38661. }
  38662. if ( dstPosition !== null ) {
  38663. dstX = dstPosition.x;
  38664. dstY = dstPosition.y;
  38665. } else {
  38666. dstX = 0;
  38667. dstY = 0;
  38668. }
  38669. state.bindTexture( glTextureType, dstTextureGPU );
  38670. // As another texture upload may have changed pixelStorei
  38671. // parameters, make sure they are correct for the dstTexture
  38672. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38673. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  38674. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  38675. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  38676. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  38677. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  38678. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  38679. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  38680. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  38681. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  38682. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  38683. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  38684. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  38685. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  38686. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  38687. const srcTextureData = backend.get( srcTexture );
  38688. const dstTextureData = backend.get( dstTexture );
  38689. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  38690. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  38691. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  38692. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  38693. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  38694. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  38695. let mask = gl.COLOR_BUFFER_BIT;
  38696. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  38697. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  38698. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  38699. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  38700. } else {
  38701. if ( srcTexture.isDataTexture ) {
  38702. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  38703. } else {
  38704. if ( srcTexture.isCompressedTexture ) {
  38705. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  38706. } else {
  38707. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  38708. }
  38709. }
  38710. }
  38711. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  38712. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  38713. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  38714. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  38715. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  38716. // Generate mipmaps only when copying level 0
  38717. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  38718. state.unbindTexture();
  38719. }
  38720. /**
  38721. * Copies the current bound framebuffer to the given texture.
  38722. *
  38723. * @param {Texture} texture - The destination texture.
  38724. * @param {RenderContext} renderContext - The render context.
  38725. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  38726. */
  38727. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  38728. const { gl } = this;
  38729. const { state } = this.backend;
  38730. const { textureGPU } = this.backend.get( texture );
  38731. const { x, y, z: width, w: height } = rectangle;
  38732. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  38733. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  38734. if ( requireDrawFrameBuffer ) {
  38735. const partial = ( x !== 0 || y !== 0 );
  38736. let mask;
  38737. let attachment;
  38738. if ( texture.isDepthTexture === true ) {
  38739. mask = gl.DEPTH_BUFFER_BIT;
  38740. attachment = gl.DEPTH_ATTACHMENT;
  38741. if ( renderContext.stencil ) {
  38742. mask |= gl.STENCIL_BUFFER_BIT;
  38743. }
  38744. } else {
  38745. mask = gl.COLOR_BUFFER_BIT;
  38746. attachment = gl.COLOR_ATTACHMENT0;
  38747. }
  38748. if ( partial ) {
  38749. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  38750. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  38751. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  38752. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38753. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  38754. const flippedY = srcHeight - y - height;
  38755. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  38756. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  38757. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  38758. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  38759. state.unbindTexture();
  38760. } else {
  38761. const fb = gl.createFramebuffer();
  38762. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38763. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  38764. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  38765. gl.deleteFramebuffer( fb );
  38766. }
  38767. } else {
  38768. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  38769. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  38770. state.unbindTexture();
  38771. }
  38772. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  38773. this.backend._setFramebuffer( renderContext );
  38774. }
  38775. /**
  38776. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  38777. *
  38778. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  38779. * @param {RenderContext} renderContext - The render context.
  38780. */
  38781. setupRenderBufferStorage( renderbuffer, renderContext ) {
  38782. const { gl } = this;
  38783. const renderTarget = renderContext.renderTarget;
  38784. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  38785. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  38786. if ( depthBuffer && ! stencilBuffer ) {
  38787. let glInternalFormat = gl.DEPTH_COMPONENT24;
  38788. if ( samples > 0 ) {
  38789. if ( depthTexture && depthTexture.isDepthTexture ) {
  38790. if ( depthTexture.type === gl.FLOAT ) {
  38791. glInternalFormat = gl.DEPTH_COMPONENT32F;
  38792. }
  38793. }
  38794. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  38795. } else {
  38796. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  38797. }
  38798. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38799. } else if ( depthBuffer && stencilBuffer ) {
  38800. if ( samples > 0 ) {
  38801. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  38802. } else {
  38803. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  38804. }
  38805. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  38806. }
  38807. }
  38808. /**
  38809. * Returns texture data as a typed array.
  38810. *
  38811. * @async
  38812. * @param {Texture} texture - The texture to copy.
  38813. * @param {Number} x - The x coordinate of the copy origin.
  38814. * @param {Number} y - The y coordinate of the copy origin.
  38815. * @param {Number} width - The width of the copy.
  38816. * @param {Number} height - The height of the copy.
  38817. * @param {Number} faceIndex - The face index.
  38818. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  38819. */
  38820. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  38821. const { backend, gl } = this;
  38822. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  38823. const fb = gl.createFramebuffer();
  38824. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  38825. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  38826. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  38827. const typedArrayType = this._getTypedArrayType( glType );
  38828. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  38829. const elementCount = width * height;
  38830. const byteLength = elementCount * bytesPerTexel;
  38831. const buffer = gl.createBuffer();
  38832. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38833. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  38834. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  38835. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38836. await backend.utils._clientWaitAsync();
  38837. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  38838. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  38839. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  38840. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  38841. gl.deleteFramebuffer( fb );
  38842. return dstBuffer;
  38843. }
  38844. /**
  38845. * Returns the corresponding typed array type for the given WebGL data type.
  38846. *
  38847. * @private
  38848. * @param {GLenum} glType - The WebGL data type.
  38849. * @return {TypedArray.constructor} The typed array type.
  38850. */
  38851. _getTypedArrayType( glType ) {
  38852. const { gl } = this;
  38853. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  38854. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  38855. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  38856. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  38857. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  38858. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  38859. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  38860. if ( glType === gl.FLOAT ) return Float32Array;
  38861. throw new Error( `Unsupported WebGL type: ${glType}` );
  38862. }
  38863. /**
  38864. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  38865. *
  38866. * @private
  38867. * @param {GLenum} glType - The WebGL data type.
  38868. * @param {GLenum} glFormat - The WebGL texture format.
  38869. * @return {Number} The bytes-per-texel.
  38870. */
  38871. _getBytesPerTexel( glType, glFormat ) {
  38872. const { gl } = this;
  38873. let bytesPerComponent = 0;
  38874. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  38875. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  38876. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  38877. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  38878. glType === gl.UNSIGNED_SHORT ||
  38879. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  38880. if ( glType === gl.UNSIGNED_INT ||
  38881. glType === gl.FLOAT ) bytesPerComponent = 4;
  38882. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  38883. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  38884. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  38885. }
  38886. }
  38887. /**
  38888. * A WebGL 2 backend utility module for managing extensions.
  38889. *
  38890. * @private
  38891. */
  38892. class WebGLExtensions {
  38893. /**
  38894. * Constructs a new utility object.
  38895. *
  38896. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38897. */
  38898. constructor( backend ) {
  38899. /**
  38900. * A reference to the WebGL 2 backend.
  38901. *
  38902. * @type {WebGLBackend}
  38903. */
  38904. this.backend = backend;
  38905. /**
  38906. * A reference to the rendering context.
  38907. *
  38908. * @type {WebGL2RenderingContext}
  38909. */
  38910. this.gl = this.backend.gl;
  38911. /**
  38912. * A list with all the supported WebGL extensions.
  38913. *
  38914. * @type {Array<String>}
  38915. */
  38916. this.availableExtensions = this.gl.getSupportedExtensions();
  38917. /**
  38918. * A dictionary with requested WebGL extensions.
  38919. * The key is the name of the extension, the value
  38920. * the requested extension object.
  38921. *
  38922. * @type {Object<String,Object>}
  38923. */
  38924. this.extensions = {};
  38925. }
  38926. /**
  38927. * Returns the extension object for the given extension name.
  38928. *
  38929. * @param {String} name - The extension name.
  38930. * @return {Object} The extension object.
  38931. */
  38932. get( name ) {
  38933. let extension = this.extensions[ name ];
  38934. if ( extension === undefined ) {
  38935. extension = this.gl.getExtension( name );
  38936. this.extensions[ name ] = extension;
  38937. }
  38938. return extension;
  38939. }
  38940. /**
  38941. * Returns `true` if the requested extension is available.
  38942. *
  38943. * @param {String} name - The extension name.
  38944. * @return {Boolean} Whether the given extension is available or not.
  38945. */
  38946. has( name ) {
  38947. return this.availableExtensions.includes( name );
  38948. }
  38949. }
  38950. /**
  38951. * A WebGL 2 backend utility module for managing the device's capabilities.
  38952. *
  38953. * @private
  38954. */
  38955. class WebGLCapabilities {
  38956. /**
  38957. * Constructs a new utility object.
  38958. *
  38959. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38960. */
  38961. constructor( backend ) {
  38962. /**
  38963. * A reference to the WebGL 2 backend.
  38964. *
  38965. * @type {WebGLBackend}
  38966. */
  38967. this.backend = backend;
  38968. /**
  38969. * This value holds the cached max anisotropy value.
  38970. *
  38971. * @type {Number?}
  38972. * @default null
  38973. */
  38974. this.maxAnisotropy = null;
  38975. }
  38976. /**
  38977. * Returns the maximum anisotropy texture filtering value. This value
  38978. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  38979. * WebGL extension.
  38980. *
  38981. * @return {Number} The maximum anisotropy texture filtering value.
  38982. */
  38983. getMaxAnisotropy() {
  38984. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  38985. const gl = this.backend.gl;
  38986. const extensions = this.backend.extensions;
  38987. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  38988. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  38989. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  38990. } else {
  38991. this.maxAnisotropy = 0;
  38992. }
  38993. return this.maxAnisotropy;
  38994. }
  38995. }
  38996. const GLFeatureName = {
  38997. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  38998. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  38999. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  39000. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  39001. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  39002. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  39003. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  39004. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  39005. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  39006. };
  39007. class WebGLBufferRenderer {
  39008. constructor( backend ) {
  39009. this.gl = backend.gl;
  39010. this.extensions = backend.extensions;
  39011. this.info = backend.renderer.info;
  39012. this.mode = null;
  39013. this.index = 0;
  39014. this.type = null;
  39015. this.object = null;
  39016. }
  39017. render( start, count ) {
  39018. const { gl, mode, object, type, info, index } = this;
  39019. if ( index !== 0 ) {
  39020. gl.drawElements( mode, count, type, start );
  39021. } else {
  39022. gl.drawArrays( mode, start, count );
  39023. }
  39024. info.update( object, count, mode, 1 );
  39025. }
  39026. renderInstances( start, count, primcount ) {
  39027. const { gl, mode, type, index, object, info } = this;
  39028. if ( primcount === 0 ) return;
  39029. if ( index !== 0 ) {
  39030. gl.drawElementsInstanced( mode, count, type, start, primcount );
  39031. } else {
  39032. gl.drawArraysInstanced( mode, start, count, primcount );
  39033. }
  39034. info.update( object, count, mode, primcount );
  39035. }
  39036. renderMultiDraw( starts, counts, drawCount ) {
  39037. const { extensions, mode, object, info } = this;
  39038. if ( drawCount === 0 ) return;
  39039. const extension = extensions.get( 'WEBGL_multi_draw' );
  39040. if ( extension === null ) {
  39041. for ( let i = 0; i < drawCount; i ++ ) {
  39042. this.render( starts[ i ], counts[ i ] );
  39043. }
  39044. } else {
  39045. if ( this.index !== 0 ) {
  39046. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  39047. } else {
  39048. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  39049. }
  39050. let elementCount = 0;
  39051. for ( let i = 0; i < drawCount; i ++ ) {
  39052. elementCount += counts[ i ];
  39053. }
  39054. info.update( object, elementCount, mode, 1 );
  39055. }
  39056. }
  39057. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  39058. const { extensions, mode, object, info } = this;
  39059. if ( drawCount === 0 ) return;
  39060. const extension = extensions.get( 'WEBGL_multi_draw' );
  39061. if ( extension === null ) {
  39062. for ( let i = 0; i < drawCount; i ++ ) {
  39063. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  39064. }
  39065. } else {
  39066. if ( this.index !== 0 ) {
  39067. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  39068. } else {
  39069. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  39070. }
  39071. let elementCount = 0;
  39072. for ( let i = 0; i < drawCount; i ++ ) {
  39073. elementCount += counts[ i ] * primcount[ i ];
  39074. }
  39075. info.update( object, elementCount, mode, 1 );
  39076. }
  39077. }
  39078. //
  39079. }
  39080. /**
  39081. * A backend implementation targeting WebGL 2.
  39082. *
  39083. * @private
  39084. * @augments Backend
  39085. */
  39086. class WebGLBackend extends Backend {
  39087. /**
  39088. * Constructs a new WebGPU backend.
  39089. *
  39090. * @param {Object} parameters - The configuration parameter.
  39091. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  39092. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  39093. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  39094. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  39095. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  39096. * @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.
  39097. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  39098. * @param {WebGL2RenderingContext} [parameters.context=undefined] - A WebGL 2 rendering context.
  39099. */
  39100. constructor( parameters = {} ) {
  39101. super( parameters );
  39102. /**
  39103. * This flag can be used for type testing.
  39104. *
  39105. * @type {Boolean}
  39106. * @readonly
  39107. * @default true
  39108. */
  39109. this.isWebGLBackend = true;
  39110. /**
  39111. * A reference to a backend module holding shader attribute-related
  39112. * utility functions.
  39113. *
  39114. * @type {WebGLAttributeUtils?}
  39115. * @default null
  39116. */
  39117. this.attributeUtils = null;
  39118. /**
  39119. * A reference to a backend module holding extension-related
  39120. * utility functions.
  39121. *
  39122. * @type {WebGLExtensions?}
  39123. * @default null
  39124. */
  39125. this.extensions = null;
  39126. /**
  39127. * A reference to a backend module holding capability-related
  39128. * utility functions.
  39129. *
  39130. * @type {WebGLCapabilities?}
  39131. * @default null
  39132. */
  39133. this.capabilities = null;
  39134. /**
  39135. * A reference to a backend module holding texture-related
  39136. * utility functions.
  39137. *
  39138. * @type {WebGLTextureUtils?}
  39139. * @default null
  39140. */
  39141. this.textureUtils = null;
  39142. /**
  39143. * A reference to a backend module holding renderer-related
  39144. * utility functions.
  39145. *
  39146. * @type {WebGLBufferRenderer?}
  39147. * @default null
  39148. */
  39149. this.bufferRenderer = null;
  39150. /**
  39151. * A reference to the rendering context.
  39152. *
  39153. * @type {WebGL2RenderingContext?}
  39154. * @default null
  39155. */
  39156. this.gl = null;
  39157. /**
  39158. * A reference to a backend module holding state-related
  39159. * utility functions.
  39160. *
  39161. * @type {WebGLState?}
  39162. * @default null
  39163. */
  39164. this.state = null;
  39165. /**
  39166. * A reference to a backend module holding common
  39167. * utility functions.
  39168. *
  39169. * @type {WebGLUtils?}
  39170. * @default null
  39171. */
  39172. this.utils = null;
  39173. /**
  39174. * Dictionary for caching VAOs.
  39175. *
  39176. * @type {Object<String,WebGLVertexArrayObject>}
  39177. */
  39178. this.vaoCache = {};
  39179. /**
  39180. * Dictionary for caching transform feedback objects.
  39181. *
  39182. * @type {Object<String,WebGLTransformFeedback>}
  39183. */
  39184. this.transformFeedbackCache = {};
  39185. /**
  39186. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  39187. * Only relevant when using compute shaders.
  39188. *
  39189. * @type {Boolean}
  39190. * @default false
  39191. */
  39192. this.discard = false;
  39193. /**
  39194. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  39195. * device does not support the extension.
  39196. *
  39197. * @type {EXTDisjointTimerQueryWebGL2?}
  39198. * @default null
  39199. */
  39200. this.disjoint = null;
  39201. /**
  39202. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  39203. * device does not support the extension.
  39204. *
  39205. * @type {KHRParallelShaderCompile?}
  39206. * @default null
  39207. */
  39208. this.parallel = null;
  39209. /**
  39210. * Whether to track timestamps with a Timestamp Query API or not.
  39211. *
  39212. * @type {Boolean}
  39213. * @default false
  39214. */
  39215. this.trackTimestamp = ( parameters.trackTimestamp === true );
  39216. /**
  39217. * A reference to the current render context.
  39218. *
  39219. * @private
  39220. * @type {RenderContext}
  39221. * @default null
  39222. */
  39223. this._currentContext = null;
  39224. /**
  39225. * A unique collection of bindings.
  39226. *
  39227. * @private
  39228. * @type {WeakSet}
  39229. */
  39230. this._knownBindings = new WeakSet();
  39231. }
  39232. /**
  39233. * Initializes the backend so it is ready for usage.
  39234. *
  39235. * @param {Renderer} renderer - The renderer.
  39236. */
  39237. init( renderer ) {
  39238. super.init( renderer );
  39239. //
  39240. const parameters = this.parameters;
  39241. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  39242. function onContextLost( event ) {
  39243. event.preventDefault();
  39244. const contextLossInfo = {
  39245. api: 'WebGL',
  39246. message: event.statusMessage || 'Unknown reason',
  39247. reason: null,
  39248. originalEvent: event
  39249. };
  39250. renderer.onDeviceLost( contextLossInfo );
  39251. }
  39252. this._onContextLost = onContextLost;
  39253. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  39254. this.gl = glContext;
  39255. this.extensions = new WebGLExtensions( this );
  39256. this.capabilities = new WebGLCapabilities( this );
  39257. this.attributeUtils = new WebGLAttributeUtils( this );
  39258. this.textureUtils = new WebGLTextureUtils( this );
  39259. this.bufferRenderer = new WebGLBufferRenderer( this );
  39260. this.state = new WebGLState( this );
  39261. this.utils = new WebGLUtils( this );
  39262. this.extensions.get( 'EXT_color_buffer_float' );
  39263. this.extensions.get( 'WEBGL_clip_cull_distance' );
  39264. this.extensions.get( 'OES_texture_float_linear' );
  39265. this.extensions.get( 'EXT_color_buffer_half_float' );
  39266. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  39267. this.extensions.get( 'WEBGL_render_shared_exponent' );
  39268. this.extensions.get( 'WEBGL_multi_draw' );
  39269. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  39270. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  39271. }
  39272. /**
  39273. * The coordinate system of the backend.
  39274. *
  39275. * @type {Number}
  39276. * @readonly
  39277. */
  39278. get coordinateSystem() {
  39279. return WebGLCoordinateSystem;
  39280. }
  39281. /**
  39282. * This method performs a readback operation by moving buffer data from
  39283. * a storage buffer attribute from the GPU to the CPU.
  39284. *
  39285. * @async
  39286. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  39287. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  39288. */
  39289. async getArrayBufferAsync( attribute ) {
  39290. return await this.attributeUtils.getArrayBufferAsync( attribute );
  39291. }
  39292. /**
  39293. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  39294. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  39295. *
  39296. * @async
  39297. * @return {Promise} A Promise that resolves when synchronization has been finished.
  39298. */
  39299. async waitForGPU() {
  39300. await this.utils._clientWaitAsync();
  39301. }
  39302. /**
  39303. * Inits a time stamp query for the given render context.
  39304. *
  39305. * @param {RenderContext} renderContext - The render context.
  39306. */
  39307. initTimestampQuery( renderContext ) {
  39308. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  39309. const renderContextData = this.get( renderContext );
  39310. if ( this.queryRunning ) {
  39311. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  39312. renderContextData.queryQueue.push( renderContext );
  39313. return;
  39314. }
  39315. if ( renderContextData.activeQuery ) {
  39316. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  39317. renderContextData.activeQuery = null;
  39318. }
  39319. renderContextData.activeQuery = this.gl.createQuery();
  39320. if ( renderContextData.activeQuery !== null ) {
  39321. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  39322. this.queryRunning = true;
  39323. }
  39324. }
  39325. // timestamp utils
  39326. /**
  39327. * Prepares the timestamp buffer.
  39328. *
  39329. * @param {RenderContext} renderContext - The render context.
  39330. */
  39331. prepareTimestampBuffer( renderContext ) {
  39332. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  39333. const renderContextData = this.get( renderContext );
  39334. if ( renderContextData.activeQuery ) {
  39335. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  39336. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  39337. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  39338. renderContextData.activeQuery = null;
  39339. this.queryRunning = false;
  39340. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  39341. const nextRenderContext = renderContextData.queryQueue.shift();
  39342. this.initTimestampQuery( nextRenderContext );
  39343. }
  39344. }
  39345. }
  39346. /**
  39347. * Resolves the time stamp for the given render context and type.
  39348. *
  39349. * @async
  39350. * @param {RenderContext} renderContext - The render context.
  39351. * @param {String} type - The render context.
  39352. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  39353. */
  39354. async resolveTimestampAsync( renderContext, type = 'render' ) {
  39355. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  39356. const renderContextData = this.get( renderContext );
  39357. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  39358. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  39359. const queryInfo = renderContextData.gpuQueries[ i ];
  39360. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  39361. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  39362. if ( available && ! disjoint ) {
  39363. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  39364. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  39365. this.gl.deleteQuery( queryInfo.query );
  39366. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  39367. i --;
  39368. this.renderer.info.updateTimestamp( type, duration );
  39369. }
  39370. }
  39371. }
  39372. /**
  39373. * Returns the backend's rendering context.
  39374. *
  39375. * @return {WebGL2RenderingContext} The rendering context.
  39376. */
  39377. getContext() {
  39378. return this.gl;
  39379. }
  39380. /**
  39381. * This method is executed at the beginning of a render call and prepares
  39382. * the WebGL state for upcoming render calls
  39383. *
  39384. * @param {RenderContext} renderContext - The render context.
  39385. */
  39386. beginRender( renderContext ) {
  39387. const { gl } = this;
  39388. const renderContextData = this.get( renderContext );
  39389. //
  39390. //
  39391. this.initTimestampQuery( renderContext );
  39392. renderContextData.previousContext = this._currentContext;
  39393. this._currentContext = renderContext;
  39394. this._setFramebuffer( renderContext );
  39395. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  39396. //
  39397. if ( renderContext.viewport ) {
  39398. this.updateViewport( renderContext );
  39399. } else {
  39400. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  39401. }
  39402. if ( renderContext.scissor ) {
  39403. const { x, y, width, height } = renderContext.scissorValue;
  39404. gl.scissor( x, renderContext.height - height - y, width, height );
  39405. }
  39406. const occlusionQueryCount = renderContext.occlusionQueryCount;
  39407. if ( occlusionQueryCount > 0 ) {
  39408. // Get a reference to the array of objects with queries. The renderContextData property
  39409. // can be changed by another render pass before the async reading of all previous queries complete
  39410. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  39411. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  39412. renderContextData.lastOcclusionObject = null;
  39413. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  39414. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  39415. renderContextData.occlusionQueryIndex = 0;
  39416. }
  39417. }
  39418. /**
  39419. * This method is executed at the end of a render call and finalizes work
  39420. * after draw calls.
  39421. *
  39422. * @param {RenderContext} renderContext - The render context.
  39423. */
  39424. finishRender( renderContext ) {
  39425. const { gl, state } = this;
  39426. const renderContextData = this.get( renderContext );
  39427. const previousContext = renderContextData.previousContext;
  39428. const occlusionQueryCount = renderContext.occlusionQueryCount;
  39429. if ( occlusionQueryCount > 0 ) {
  39430. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  39431. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  39432. }
  39433. this.resolveOccludedAsync( renderContext );
  39434. }
  39435. const textures = renderContext.textures;
  39436. if ( textures !== null ) {
  39437. for ( let i = 0; i < textures.length; i ++ ) {
  39438. const texture = textures[ i ];
  39439. if ( texture.generateMipmaps ) {
  39440. this.generateMipmaps( texture );
  39441. }
  39442. }
  39443. }
  39444. this._currentContext = previousContext;
  39445. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  39446. const renderTargetContextData = this.get( renderContext.renderTarget );
  39447. const { samples } = renderContext.renderTarget;
  39448. if ( samples > 0 ) {
  39449. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  39450. const mask = gl.COLOR_BUFFER_BIT;
  39451. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39452. const textures = renderContext.textures;
  39453. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  39454. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39455. for ( let i = 0; i < textures.length; i ++ ) {
  39456. // TODO Add support for MRT
  39457. if ( renderContext.scissor ) {
  39458. const { x, y, width, height } = renderContext.scissorValue;
  39459. const viewY = renderContext.height - height - y;
  39460. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  39461. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  39462. } else {
  39463. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  39464. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  39465. }
  39466. }
  39467. }
  39468. }
  39469. if ( previousContext !== null ) {
  39470. this._setFramebuffer( previousContext );
  39471. if ( previousContext.viewport ) {
  39472. this.updateViewport( previousContext );
  39473. } else {
  39474. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  39475. }
  39476. }
  39477. this.prepareTimestampBuffer( renderContext );
  39478. }
  39479. /**
  39480. * This method processes the result of occlusion queries and writes it
  39481. * into render context data.
  39482. *
  39483. * @async
  39484. * @param {RenderContext} renderContext - The render context.
  39485. */
  39486. resolveOccludedAsync( renderContext ) {
  39487. const renderContextData = this.get( renderContext );
  39488. // handle occlusion query results
  39489. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  39490. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  39491. const occluded = new WeakSet();
  39492. const { gl } = this;
  39493. renderContextData.currentOcclusionQueryObjects = null;
  39494. renderContextData.currentOcclusionQueries = null;
  39495. const check = () => {
  39496. let completed = 0;
  39497. // check all queries and requeue as appropriate
  39498. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  39499. const query = currentOcclusionQueries[ i ];
  39500. if ( query === null ) continue;
  39501. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  39502. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  39503. currentOcclusionQueries[ i ] = null;
  39504. gl.deleteQuery( query );
  39505. completed ++;
  39506. }
  39507. }
  39508. if ( completed < currentOcclusionQueries.length ) {
  39509. requestAnimationFrame( check );
  39510. } else {
  39511. renderContextData.occluded = occluded;
  39512. }
  39513. };
  39514. check();
  39515. }
  39516. }
  39517. /**
  39518. * Returns `true` if the given 3D object is fully occluded by other
  39519. * 3D objects in the scene.
  39520. *
  39521. * @param {RenderContext} renderContext - The render context.
  39522. * @param {Object3D} object - The 3D object to test.
  39523. * @return {Boolean} Whether the 3D object is fully occluded or not.
  39524. */
  39525. isOccluded( renderContext, object ) {
  39526. const renderContextData = this.get( renderContext );
  39527. return renderContextData.occluded && renderContextData.occluded.has( object );
  39528. }
  39529. /**
  39530. * Updates the viewport with the values from the given render context.
  39531. *
  39532. * @param {RenderContext} renderContext - The render context.
  39533. */
  39534. updateViewport( renderContext ) {
  39535. const gl = this.gl;
  39536. const { x, y, width, height } = renderContext.viewportValue;
  39537. gl.viewport( x, renderContext.height - height - y, width, height );
  39538. }
  39539. /**
  39540. * Defines the scissor test.
  39541. *
  39542. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  39543. */
  39544. setScissorTest( boolean ) {
  39545. const gl = this.gl;
  39546. if ( boolean ) {
  39547. gl.enable( gl.SCISSOR_TEST );
  39548. } else {
  39549. gl.disable( gl.SCISSOR_TEST );
  39550. }
  39551. }
  39552. /**
  39553. * Performs a clear operation.
  39554. *
  39555. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  39556. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  39557. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  39558. * @param {Object?} [descriptor=null] - The render context of the current set render target.
  39559. * @param {Boolean} [setFrameBuffer=true] - TODO.
  39560. */
  39561. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  39562. const { gl } = this;
  39563. if ( descriptor === null ) {
  39564. const clearColor = this.getClearColor();
  39565. // premultiply alpha
  39566. clearColor.r *= clearColor.a;
  39567. clearColor.g *= clearColor.a;
  39568. clearColor.b *= clearColor.a;
  39569. descriptor = {
  39570. textures: null,
  39571. clearColorValue: clearColor
  39572. };
  39573. }
  39574. //
  39575. let clear = 0;
  39576. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  39577. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  39578. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  39579. if ( clear !== 0 ) {
  39580. let clearColor;
  39581. if ( descriptor.clearColorValue ) {
  39582. clearColor = descriptor.clearColorValue;
  39583. } else {
  39584. clearColor = this.getClearColor();
  39585. // premultiply alpha
  39586. clearColor.r *= clearColor.a;
  39587. clearColor.g *= clearColor.a;
  39588. clearColor.b *= clearColor.a;
  39589. }
  39590. if ( depth ) this.state.setDepthMask( true );
  39591. if ( descriptor.textures === null ) {
  39592. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  39593. gl.clear( clear );
  39594. } else {
  39595. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  39596. if ( color ) {
  39597. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  39598. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  39599. }
  39600. }
  39601. if ( depth && stencil ) {
  39602. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  39603. } else if ( depth ) {
  39604. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  39605. } else if ( stencil ) {
  39606. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  39607. }
  39608. }
  39609. }
  39610. }
  39611. /**
  39612. * This method is executed at the beginning of a compute call and
  39613. * prepares the state for upcoming compute tasks.
  39614. *
  39615. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  39616. */
  39617. beginCompute( computeGroup ) {
  39618. const { state, gl } = this;
  39619. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  39620. this.initTimestampQuery( computeGroup );
  39621. }
  39622. /**
  39623. * Executes a compute command for the given compute node.
  39624. *
  39625. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  39626. * @param {Node} computeNode - The compute node.
  39627. * @param {Array<BindGroup>} bindings - The bindings.
  39628. * @param {ComputePipeline} pipeline - The compute pipeline.
  39629. */
  39630. compute( computeGroup, computeNode, bindings, pipeline ) {
  39631. const { state, gl } = this;
  39632. if ( this.discard === false ) {
  39633. // required here to handle async behaviour of render.compute()
  39634. gl.enable( gl.RASTERIZER_DISCARD );
  39635. this.discard = true;
  39636. }
  39637. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  39638. const vaoKey = this._getVaoKey( null, attributes );
  39639. const vaoGPU = this.vaoCache[ vaoKey ];
  39640. if ( vaoGPU === undefined ) {
  39641. this._createVao( null, attributes );
  39642. } else {
  39643. gl.bindVertexArray( vaoGPU );
  39644. }
  39645. state.useProgram( programGPU );
  39646. this._bindUniforms( bindings );
  39647. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  39648. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39649. gl.beginTransformFeedback( gl.POINTS );
  39650. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  39651. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  39652. } else {
  39653. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  39654. }
  39655. gl.endTransformFeedback();
  39656. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39657. // switch active buffers
  39658. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39659. const dualAttributeData = transformBuffers[ i ];
  39660. if ( dualAttributeData.pbo ) {
  39661. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  39662. }
  39663. dualAttributeData.switchBuffers();
  39664. }
  39665. }
  39666. /**
  39667. * This method is executed at the end of a compute call and
  39668. * finalizes work after compute tasks.
  39669. *
  39670. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  39671. */
  39672. finishCompute( computeGroup ) {
  39673. const gl = this.gl;
  39674. this.discard = false;
  39675. gl.disable( gl.RASTERIZER_DISCARD );
  39676. this.prepareTimestampBuffer( computeGroup );
  39677. if ( this._currentContext ) {
  39678. this._setFramebuffer( this._currentContext );
  39679. }
  39680. }
  39681. /**
  39682. * Executes a draw command for the given render object.
  39683. *
  39684. * @param {RenderObject} renderObject - The render object to draw.
  39685. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  39686. */
  39687. draw( renderObject/*, info*/ ) {
  39688. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  39689. const { programGPU } = this.get( pipeline );
  39690. const { gl, state } = this;
  39691. const contextData = this.get( context );
  39692. const drawParams = renderObject.getDrawParameters();
  39693. if ( drawParams === null ) return;
  39694. //
  39695. this._bindUniforms( renderObject.getBindings() );
  39696. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  39697. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  39698. state.useProgram( programGPU );
  39699. //
  39700. const renderObjectData = this.get( renderObject );
  39701. let vaoGPU = renderObjectData.staticVao;
  39702. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  39703. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  39704. vaoGPU = this.vaoCache[ vaoKey ];
  39705. if ( vaoGPU === undefined ) {
  39706. let staticVao;
  39707. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  39708. if ( staticVao ) {
  39709. renderObjectData.staticVao = vaoGPU;
  39710. renderObjectData.geometryId = renderObject.geometry.id;
  39711. }
  39712. }
  39713. }
  39714. gl.bindVertexArray( vaoGPU );
  39715. //
  39716. const index = renderObject.getIndex();
  39717. //
  39718. const lastObject = contextData.lastOcclusionObject;
  39719. if ( lastObject !== object && lastObject !== undefined ) {
  39720. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  39721. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  39722. contextData.occlusionQueryIndex ++;
  39723. }
  39724. if ( object.occlusionTest === true ) {
  39725. const query = gl.createQuery();
  39726. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  39727. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  39728. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  39729. }
  39730. contextData.lastOcclusionObject = object;
  39731. }
  39732. //
  39733. const renderer = this.bufferRenderer;
  39734. if ( object.isPoints ) renderer.mode = gl.POINTS;
  39735. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  39736. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  39737. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  39738. else {
  39739. if ( material.wireframe === true ) {
  39740. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  39741. renderer.mode = gl.LINES;
  39742. } else {
  39743. renderer.mode = gl.TRIANGLES;
  39744. }
  39745. }
  39746. //
  39747. const { vertexCount, instanceCount } = drawParams;
  39748. let { firstVertex } = drawParams;
  39749. renderer.object = object;
  39750. if ( index !== null ) {
  39751. firstVertex *= index.array.BYTES_PER_ELEMENT;
  39752. const indexData = this.get( index );
  39753. renderer.index = index.count;
  39754. renderer.type = indexData.type;
  39755. } else {
  39756. renderer.index = 0;
  39757. }
  39758. if ( object.isBatchedMesh ) {
  39759. if ( object._multiDrawInstances !== null ) {
  39760. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  39761. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  39762. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  39763. } else {
  39764. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  39765. }
  39766. } else if ( instanceCount > 1 ) {
  39767. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  39768. } else {
  39769. renderer.render( firstVertex, vertexCount );
  39770. }
  39771. //
  39772. gl.bindVertexArray( null );
  39773. }
  39774. /**
  39775. * Explain why always null is returned.
  39776. *
  39777. * @param {RenderObject} renderObject - The render object.
  39778. * @return {Boolean} Whether the render pipeline requires an update or not.
  39779. */
  39780. needsRenderUpdate( /*renderObject*/ ) {
  39781. return false;
  39782. }
  39783. /**
  39784. * Explain why no cache key is computed.
  39785. *
  39786. * @param {RenderObject} renderObject - The render object.
  39787. * @return {String} The cache key.
  39788. */
  39789. getRenderCacheKey( /*renderObject*/ ) {
  39790. return '';
  39791. }
  39792. // textures
  39793. /**
  39794. * Creates a default texture for the given texture that can be used
  39795. * as a placeholder until the actual texture is ready for usage.
  39796. *
  39797. * @param {Texture} texture - The texture to create a default texture for.
  39798. */
  39799. createDefaultTexture( texture ) {
  39800. this.textureUtils.createDefaultTexture( texture );
  39801. }
  39802. /**
  39803. * Defines a texture on the GPU for the given texture object.
  39804. *
  39805. * @param {Texture} texture - The texture.
  39806. * @param {Object} [options={}] - Optional configuration parameter.
  39807. */
  39808. createTexture( texture, options ) {
  39809. this.textureUtils.createTexture( texture, options );
  39810. }
  39811. /**
  39812. * Uploads the updated texture data to the GPU.
  39813. *
  39814. * @param {Texture} texture - The texture.
  39815. * @param {Object} [options={}] - Optional configuration parameter.
  39816. */
  39817. updateTexture( texture, options ) {
  39818. this.textureUtils.updateTexture( texture, options );
  39819. }
  39820. /**
  39821. * Generates mipmaps for the given texture.
  39822. *
  39823. * @param {Texture} texture - The texture.
  39824. */
  39825. generateMipmaps( texture ) {
  39826. this.textureUtils.generateMipmaps( texture );
  39827. }
  39828. /**
  39829. * Destroys the GPU data for the given texture object.
  39830. *
  39831. * @param {Texture} texture - The texture.
  39832. */
  39833. destroyTexture( texture ) {
  39834. this.textureUtils.destroyTexture( texture );
  39835. }
  39836. /**
  39837. * Returns texture data as a typed array.
  39838. *
  39839. * @async
  39840. * @param {Texture} texture - The texture to copy.
  39841. * @param {Number} x - The x coordinate of the copy origin.
  39842. * @param {Number} y - The y coordinate of the copy origin.
  39843. * @param {Number} width - The width of the copy.
  39844. * @param {Number} height - The height of the copy.
  39845. * @param {Number} faceIndex - The face index.
  39846. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  39847. */
  39848. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  39849. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  39850. }
  39851. /**
  39852. * This method does nothing since WebGL 2 has no concept of samplers.
  39853. *
  39854. * @param {Texture} texture - The texture to create the sampler for.
  39855. */
  39856. createSampler( /*texture*/ ) {
  39857. //console.warn( 'Abstract class.' );
  39858. }
  39859. /**
  39860. * This method does nothing since WebGL 2 has no concept of samplers.
  39861. *
  39862. * @param {Texture} texture - The texture to destroy the sampler for.
  39863. */
  39864. destroySampler( /*texture*/ ) {}
  39865. // node builder
  39866. /**
  39867. * Returns a node builder for the given render object.
  39868. *
  39869. * @param {RenderObject} object - The render object.
  39870. * @param {Renderer} renderer - The renderer.
  39871. * @return {GLSLNodeBuilder} The node builder.
  39872. */
  39873. createNodeBuilder( object, renderer ) {
  39874. return new GLSLNodeBuilder( object, renderer );
  39875. }
  39876. // program
  39877. /**
  39878. * Creates a shader program from the given programmable stage.
  39879. *
  39880. * @param {ProgrammableStage} program - The programmable stage.
  39881. */
  39882. createProgram( program ) {
  39883. const gl = this.gl;
  39884. const { stage, code } = program;
  39885. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  39886. gl.shaderSource( shader, code );
  39887. gl.compileShader( shader );
  39888. this.set( program, {
  39889. shaderGPU: shader
  39890. } );
  39891. }
  39892. /**
  39893. * Destroys the shader program of the given programmable stage.
  39894. *
  39895. * @param {ProgrammableStage} program - The programmable stage.
  39896. */
  39897. destroyProgram( program ) {
  39898. this.delete( program );
  39899. }
  39900. /**
  39901. * Creates a render pipeline for the given render object.
  39902. *
  39903. * @param {RenderObject} renderObject - The render object.
  39904. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  39905. */
  39906. createRenderPipeline( renderObject, promises ) {
  39907. const gl = this.gl;
  39908. const pipeline = renderObject.pipeline;
  39909. // Program
  39910. const { fragmentProgram, vertexProgram } = pipeline;
  39911. const programGPU = gl.createProgram();
  39912. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  39913. const vertexShader = this.get( vertexProgram ).shaderGPU;
  39914. gl.attachShader( programGPU, fragmentShader );
  39915. gl.attachShader( programGPU, vertexShader );
  39916. gl.linkProgram( programGPU );
  39917. this.set( pipeline, {
  39918. programGPU,
  39919. fragmentShader,
  39920. vertexShader
  39921. } );
  39922. if ( promises !== null && this.parallel ) {
  39923. const p = new Promise( ( resolve /*, reject*/ ) => {
  39924. const parallel = this.parallel;
  39925. const checkStatus = () => {
  39926. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  39927. this._completeCompile( renderObject, pipeline );
  39928. resolve();
  39929. } else {
  39930. requestAnimationFrame( checkStatus );
  39931. }
  39932. };
  39933. checkStatus();
  39934. } );
  39935. promises.push( p );
  39936. return;
  39937. }
  39938. this._completeCompile( renderObject, pipeline );
  39939. }
  39940. /**
  39941. * Formats the source code of error messages.
  39942. *
  39943. * @private
  39944. * @param {String} string - The code.
  39945. * @param {Number} errorLine - The error line.
  39946. * @return {String} The formatted code.
  39947. */
  39948. _handleSource( string, errorLine ) {
  39949. const lines = string.split( '\n' );
  39950. const lines2 = [];
  39951. const from = Math.max( errorLine - 6, 0 );
  39952. const to = Math.min( errorLine + 6, lines.length );
  39953. for ( let i = from; i < to; i ++ ) {
  39954. const line = i + 1;
  39955. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  39956. }
  39957. return lines2.join( '\n' );
  39958. }
  39959. /**
  39960. * Gets the shader compilation errors from the info log.
  39961. *
  39962. * @private
  39963. * @param {WebGL2RenderingContext} gl - The rendering context.
  39964. * @param {WebGLShader} shader - The WebGL shader object.
  39965. * @param {String} type - The shader type.
  39966. * @return {String} The shader errors.
  39967. */
  39968. _getShaderErrors( gl, shader, type ) {
  39969. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  39970. const errors = gl.getShaderInfoLog( shader ).trim();
  39971. if ( status && errors === '' ) return '';
  39972. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  39973. if ( errorMatches ) {
  39974. const errorLine = parseInt( errorMatches[ 1 ] );
  39975. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  39976. } else {
  39977. return errors;
  39978. }
  39979. }
  39980. /**
  39981. * Logs shader compilation errors.
  39982. *
  39983. * @private
  39984. * @param {WebGLProgram} programGPU - The WebGL program.
  39985. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  39986. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  39987. */
  39988. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  39989. if ( this.renderer.debug.checkShaderErrors ) {
  39990. const gl = this.gl;
  39991. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  39992. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  39993. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  39994. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  39995. } else {
  39996. // default error reporting
  39997. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  39998. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  39999. console.error(
  40000. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  40001. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  40002. 'Program Info Log: ' + programLog + '\n' +
  40003. vertexErrors + '\n' +
  40004. fragmentErrors
  40005. );
  40006. }
  40007. } else if ( programLog !== '' ) {
  40008. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  40009. }
  40010. }
  40011. }
  40012. /**
  40013. * Completes the shader program setup for the given render object.
  40014. *
  40015. * @private
  40016. * @param {RenderObject} renderObject - The render object.
  40017. * @param {RenderPipeline} pipeline - The render pipeline.
  40018. */
  40019. _completeCompile( renderObject, pipeline ) {
  40020. const { state, gl } = this;
  40021. const pipelineData = this.get( pipeline );
  40022. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  40023. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  40024. this._logProgramError( programGPU, fragmentShader, vertexShader );
  40025. }
  40026. state.useProgram( programGPU );
  40027. // Bindings
  40028. const bindings = renderObject.getBindings();
  40029. this._setupBindings( bindings, programGPU );
  40030. //
  40031. this.set( pipeline, {
  40032. programGPU
  40033. } );
  40034. }
  40035. /**
  40036. * Creates a compute pipeline for the given compute node.
  40037. *
  40038. * @param {ComputePipeline} computePipeline - The compute pipeline.
  40039. * @param {Array<BindGroup>} bindings - The bindings.
  40040. */
  40041. createComputePipeline( computePipeline, bindings ) {
  40042. const { state, gl } = this;
  40043. // Program
  40044. const fragmentProgram = {
  40045. stage: 'fragment',
  40046. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  40047. };
  40048. this.createProgram( fragmentProgram );
  40049. const { computeProgram } = computePipeline;
  40050. const programGPU = gl.createProgram();
  40051. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  40052. const vertexShader = this.get( computeProgram ).shaderGPU;
  40053. const transforms = computeProgram.transforms;
  40054. const transformVaryingNames = [];
  40055. const transformAttributeNodes = [];
  40056. for ( let i = 0; i < transforms.length; i ++ ) {
  40057. const transform = transforms[ i ];
  40058. transformVaryingNames.push( transform.varyingName );
  40059. transformAttributeNodes.push( transform.attributeNode );
  40060. }
  40061. gl.attachShader( programGPU, fragmentShader );
  40062. gl.attachShader( programGPU, vertexShader );
  40063. gl.transformFeedbackVaryings(
  40064. programGPU,
  40065. transformVaryingNames,
  40066. gl.SEPARATE_ATTRIBS
  40067. );
  40068. gl.linkProgram( programGPU );
  40069. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  40070. this._logProgramError( programGPU, fragmentShader, vertexShader );
  40071. }
  40072. state.useProgram( programGPU );
  40073. // Bindings
  40074. this._setupBindings( bindings, programGPU );
  40075. const attributeNodes = computeProgram.attributes;
  40076. const attributes = [];
  40077. const transformBuffers = [];
  40078. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  40079. const attribute = attributeNodes[ i ].node.attribute;
  40080. attributes.push( attribute );
  40081. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40082. }
  40083. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  40084. const attribute = transformAttributeNodes[ i ].attribute;
  40085. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40086. const attributeData = this.get( attribute );
  40087. transformBuffers.push( attributeData );
  40088. }
  40089. //
  40090. this.set( computePipeline, {
  40091. programGPU,
  40092. transformBuffers,
  40093. attributes
  40094. } );
  40095. }
  40096. /**
  40097. * Creates bindings from the given bind group definition.
  40098. *
  40099. * @param {BindGroup} bindGroup - The bind group.
  40100. * @param {Array<BindGroup>} bindings - Array of bind groups.
  40101. * @param {Number} cacheIndex - The cache index.
  40102. * @param {Number} version - The version.
  40103. */
  40104. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  40105. if ( this._knownBindings.has( bindings ) === false ) {
  40106. this._knownBindings.add( bindings );
  40107. let uniformBuffers = 0;
  40108. let textures = 0;
  40109. for ( const bindGroup of bindings ) {
  40110. this.set( bindGroup, {
  40111. textures: textures,
  40112. uniformBuffers: uniformBuffers
  40113. } );
  40114. for ( const binding of bindGroup.bindings ) {
  40115. if ( binding.isUniformBuffer ) uniformBuffers ++;
  40116. if ( binding.isSampledTexture ) textures ++;
  40117. }
  40118. }
  40119. }
  40120. this.updateBindings( bindGroup, bindings );
  40121. }
  40122. /**
  40123. * Updates the given bind group definition.
  40124. *
  40125. * @param {BindGroup} bindGroup - The bind group.
  40126. * @param {Array<BindGroup>} bindings - Array of bind groups.
  40127. * @param {Number} cacheIndex - The cache index.
  40128. * @param {Number} version - The version.
  40129. */
  40130. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  40131. const { gl } = this;
  40132. const bindGroupData = this.get( bindGroup );
  40133. let i = bindGroupData.uniformBuffers;
  40134. let t = bindGroupData.textures;
  40135. for ( const binding of bindGroup.bindings ) {
  40136. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40137. const data = binding.buffer;
  40138. const bufferGPU = gl.createBuffer();
  40139. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  40140. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  40141. this.set( binding, {
  40142. index: i ++,
  40143. bufferGPU
  40144. } );
  40145. } else if ( binding.isSampledTexture ) {
  40146. const { textureGPU, glTextureType } = this.get( binding.texture );
  40147. this.set( binding, {
  40148. index: t ++,
  40149. textureGPU,
  40150. glTextureType
  40151. } );
  40152. }
  40153. }
  40154. }
  40155. /**
  40156. * Updates a buffer binding.
  40157. *
  40158. * @param {Buffer} binding - The buffer binding to update.
  40159. */
  40160. updateBinding( binding ) {
  40161. const gl = this.gl;
  40162. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40163. const bindingData = this.get( binding );
  40164. const bufferGPU = bindingData.bufferGPU;
  40165. const data = binding.buffer;
  40166. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  40167. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  40168. }
  40169. }
  40170. // attributes
  40171. /**
  40172. * Creates the GPU buffer of an indexed shader attribute.
  40173. *
  40174. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  40175. */
  40176. createIndexAttribute( attribute ) {
  40177. const gl = this.gl;
  40178. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  40179. }
  40180. /**
  40181. * Creates the GPU buffer of a shader attribute.
  40182. *
  40183. * @param {BufferAttribute} attribute - The buffer attribute.
  40184. */
  40185. createAttribute( attribute ) {
  40186. if ( this.has( attribute ) ) return;
  40187. const gl = this.gl;
  40188. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40189. }
  40190. /**
  40191. * Creates the GPU buffer of a storage attribute.
  40192. *
  40193. * @param {BufferAttribute} attribute - The buffer attribute.
  40194. */
  40195. createStorageAttribute( attribute ) {
  40196. if ( this.has( attribute ) ) return;
  40197. const gl = this.gl;
  40198. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  40199. }
  40200. /**
  40201. * Updates the GPU buffer of a shader attribute.
  40202. *
  40203. * @param {BufferAttribute} attribute - The buffer attribute to update.
  40204. */
  40205. updateAttribute( attribute ) {
  40206. this.attributeUtils.updateAttribute( attribute );
  40207. }
  40208. /**
  40209. * Destroys the GPU buffer of a shader attribute.
  40210. *
  40211. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  40212. */
  40213. destroyAttribute( attribute ) {
  40214. this.attributeUtils.destroyAttribute( attribute );
  40215. }
  40216. /**
  40217. * Checks if the given feature is supported by the backend.
  40218. *
  40219. * @param {String} name - The feature's name.
  40220. * @return {Boolean} Whether the feature is supported or not.
  40221. */
  40222. hasFeature( name ) {
  40223. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  40224. const extensions = this.extensions;
  40225. for ( let i = 0; i < keysMatching.length; i ++ ) {
  40226. if ( extensions.has( keysMatching[ i ] ) ) return true;
  40227. }
  40228. return false;
  40229. }
  40230. /**
  40231. * Returns the maximum anisotropy texture filtering value.
  40232. *
  40233. * @return {Number} The maximum anisotropy texture filtering value.
  40234. */
  40235. getMaxAnisotropy() {
  40236. return this.capabilities.getMaxAnisotropy();
  40237. }
  40238. /**
  40239. * Copies data of the given source texture to the given destination texture.
  40240. *
  40241. * @param {Texture} srcTexture - The source texture.
  40242. * @param {Texture} dstTexture - The destination texture.
  40243. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  40244. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  40245. * @param {Number} [level=0] - The mip level to copy.
  40246. */
  40247. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40248. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  40249. }
  40250. /**
  40251. * Copies the current bound framebuffer to the given texture.
  40252. *
  40253. * @param {Texture} texture - The destination texture.
  40254. * @param {RenderContext} renderContext - The render context.
  40255. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  40256. */
  40257. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  40258. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  40259. }
  40260. /**
  40261. * Configures the active framebuffer from the given render context.
  40262. *
  40263. * @private
  40264. * @param {RenderContext} descriptor - The render context.
  40265. */
  40266. _setFramebuffer( descriptor ) {
  40267. const { gl, state } = this;
  40268. let currentFrameBuffer = null;
  40269. if ( descriptor.textures !== null ) {
  40270. const renderTarget = descriptor.renderTarget;
  40271. const renderTargetContextData = this.get( renderTarget );
  40272. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  40273. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  40274. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  40275. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  40276. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  40277. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  40278. const cacheKey = getCacheKey( descriptor );
  40279. let fb;
  40280. if ( isCube ) {
  40281. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  40282. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  40283. } else {
  40284. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  40285. fb = renderTargetContextData.framebuffers[ cacheKey ];
  40286. }
  40287. if ( fb === undefined ) {
  40288. fb = gl.createFramebuffer();
  40289. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  40290. const textures = descriptor.textures;
  40291. if ( isCube ) {
  40292. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  40293. const { textureGPU } = this.get( textures[ 0 ] );
  40294. const cubeFace = this.renderer._activeCubeFace;
  40295. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  40296. } else {
  40297. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  40298. for ( let i = 0; i < textures.length; i ++ ) {
  40299. const texture = textures[ i ];
  40300. const textureData = this.get( texture );
  40301. textureData.renderTarget = descriptor.renderTarget;
  40302. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  40303. const attachment = gl.COLOR_ATTACHMENT0 + i;
  40304. if ( isRenderTarget3D || isRenderTargetArray ) {
  40305. const layer = this.renderer._activeCubeFace;
  40306. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  40307. } else {
  40308. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  40309. }
  40310. }
  40311. state.drawBuffers( descriptor, fb );
  40312. }
  40313. if ( descriptor.depthTexture !== null ) {
  40314. const textureData = this.get( descriptor.depthTexture );
  40315. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40316. textureData.renderTarget = descriptor.renderTarget;
  40317. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  40318. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  40319. }
  40320. }
  40321. if ( samples > 0 ) {
  40322. if ( msaaFb === undefined ) {
  40323. const invalidationArray = [];
  40324. msaaFb = gl.createFramebuffer();
  40325. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  40326. const msaaRenderbuffers = [];
  40327. const textures = descriptor.textures;
  40328. for ( let i = 0; i < textures.length; i ++ ) {
  40329. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  40330. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  40331. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  40332. if ( depthBuffer ) {
  40333. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40334. invalidationArray.push( depthStyle );
  40335. }
  40336. const texture = descriptor.textures[ i ];
  40337. const textureData = this.get( texture );
  40338. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  40339. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  40340. }
  40341. renderTargetContextData.msaaFrameBuffer = msaaFb;
  40342. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  40343. if ( depthRenderbuffer === undefined ) {
  40344. depthRenderbuffer = gl.createRenderbuffer();
  40345. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  40346. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  40347. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  40348. invalidationArray.push( depthStyle );
  40349. }
  40350. renderTargetContextData.invalidationArray = invalidationArray;
  40351. }
  40352. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40353. } else {
  40354. currentFrameBuffer = fb;
  40355. }
  40356. }
  40357. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  40358. }
  40359. /**
  40360. * Computes the VAO key for the given index and attributes.
  40361. *
  40362. * @private
  40363. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  40364. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  40365. * @return {String} The VAO key.
  40366. */
  40367. _getVaoKey( index, attributes ) {
  40368. let key = '';
  40369. if ( index !== null ) {
  40370. const indexData = this.get( index );
  40371. key += ':' + indexData.id;
  40372. }
  40373. for ( let i = 0; i < attributes.length; i ++ ) {
  40374. const attributeData = this.get( attributes[ i ] );
  40375. key += ':' + attributeData.id;
  40376. }
  40377. return key;
  40378. }
  40379. /**
  40380. * Creates a VAO from the index and attributes.
  40381. *
  40382. * @private
  40383. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  40384. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  40385. * @return {Object} The VAO data.
  40386. */
  40387. _createVao( index, attributes ) {
  40388. const { gl } = this;
  40389. const vaoGPU = gl.createVertexArray();
  40390. let key = '';
  40391. let staticVao = true;
  40392. gl.bindVertexArray( vaoGPU );
  40393. if ( index !== null ) {
  40394. const indexData = this.get( index );
  40395. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  40396. key += ':' + indexData.id;
  40397. }
  40398. for ( let i = 0; i < attributes.length; i ++ ) {
  40399. const attribute = attributes[ i ];
  40400. const attributeData = this.get( attribute );
  40401. key += ':' + attributeData.id;
  40402. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  40403. gl.enableVertexAttribArray( i );
  40404. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  40405. let stride, offset;
  40406. if ( attribute.isInterleavedBufferAttribute === true ) {
  40407. stride = attribute.data.stride * attributeData.bytesPerElement;
  40408. offset = attribute.offset * attributeData.bytesPerElement;
  40409. } else {
  40410. stride = 0;
  40411. offset = 0;
  40412. }
  40413. if ( attributeData.isInteger ) {
  40414. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  40415. } else {
  40416. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  40417. }
  40418. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  40419. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  40420. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  40421. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  40422. }
  40423. }
  40424. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  40425. this.vaoCache[ key ] = vaoGPU;
  40426. return { vaoGPU, staticVao };
  40427. }
  40428. /**
  40429. * Creates a transform feedback from the given transform buffers.
  40430. *
  40431. * @private
  40432. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  40433. * @return {WebGLTransformFeedback} The transform feedback.
  40434. */
  40435. _getTransformFeedback( transformBuffers ) {
  40436. let key = '';
  40437. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40438. key += ':' + transformBuffers[ i ].id;
  40439. }
  40440. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  40441. if ( transformFeedbackGPU !== undefined ) {
  40442. return transformFeedbackGPU;
  40443. }
  40444. const { gl } = this;
  40445. transformFeedbackGPU = gl.createTransformFeedback();
  40446. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40447. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40448. const attributeData = transformBuffers[ i ];
  40449. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  40450. }
  40451. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40452. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  40453. return transformFeedbackGPU;
  40454. }
  40455. /**
  40456. * Setups the given bindings.
  40457. *
  40458. * @private
  40459. * @param {Array<BindGroup>} bindings - The bindings.
  40460. * @param {WebGLProgram} programGPU - The WebGL program.
  40461. */
  40462. _setupBindings( bindings, programGPU ) {
  40463. const gl = this.gl;
  40464. for ( const bindGroup of bindings ) {
  40465. for ( const binding of bindGroup.bindings ) {
  40466. const bindingData = this.get( binding );
  40467. const index = bindingData.index;
  40468. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40469. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  40470. gl.uniformBlockBinding( programGPU, location, index );
  40471. } else if ( binding.isSampledTexture ) {
  40472. const location = gl.getUniformLocation( programGPU, binding.name );
  40473. gl.uniform1i( location, index );
  40474. }
  40475. }
  40476. }
  40477. }
  40478. /**
  40479. * Binds the given uniforms.
  40480. *
  40481. * @private
  40482. * @param {Array<BindGroup>} bindings - The bindings.
  40483. */
  40484. _bindUniforms( bindings ) {
  40485. const { gl, state } = this;
  40486. for ( const bindGroup of bindings ) {
  40487. for ( const binding of bindGroup.bindings ) {
  40488. const bindingData = this.get( binding );
  40489. const index = bindingData.index;
  40490. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  40491. // TODO USE bindBufferRange to group multiple uniform buffers
  40492. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  40493. } else if ( binding.isSampledTexture ) {
  40494. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  40495. }
  40496. }
  40497. }
  40498. }
  40499. /**
  40500. * Frees internal resources.
  40501. */
  40502. dispose() {
  40503. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  40504. }
  40505. }
  40506. const GPUPrimitiveTopology = {
  40507. PointList: 'point-list',
  40508. LineList: 'line-list',
  40509. LineStrip: 'line-strip',
  40510. TriangleList: 'triangle-list',
  40511. TriangleStrip: 'triangle-strip',
  40512. };
  40513. const GPUCompareFunction = {
  40514. Never: 'never',
  40515. Less: 'less',
  40516. Equal: 'equal',
  40517. LessEqual: 'less-equal',
  40518. Greater: 'greater',
  40519. NotEqual: 'not-equal',
  40520. GreaterEqual: 'greater-equal',
  40521. Always: 'always'
  40522. };
  40523. const GPUStoreOp = {
  40524. Store: 'store',
  40525. Discard: 'discard'
  40526. };
  40527. const GPULoadOp = {
  40528. Load: 'load',
  40529. Clear: 'clear'
  40530. };
  40531. const GPUFrontFace = {
  40532. CCW: 'ccw',
  40533. CW: 'cw'
  40534. };
  40535. const GPUCullMode = {
  40536. None: 'none',
  40537. Front: 'front',
  40538. Back: 'back'
  40539. };
  40540. const GPUIndexFormat = {
  40541. Uint16: 'uint16',
  40542. Uint32: 'uint32'
  40543. };
  40544. const GPUTextureFormat = {
  40545. // 8-bit formats
  40546. R8Unorm: 'r8unorm',
  40547. R8Snorm: 'r8snorm',
  40548. R8Uint: 'r8uint',
  40549. R8Sint: 'r8sint',
  40550. // 16-bit formats
  40551. R16Uint: 'r16uint',
  40552. R16Sint: 'r16sint',
  40553. R16Float: 'r16float',
  40554. RG8Unorm: 'rg8unorm',
  40555. RG8Snorm: 'rg8snorm',
  40556. RG8Uint: 'rg8uint',
  40557. RG8Sint: 'rg8sint',
  40558. // 32-bit formats
  40559. R32Uint: 'r32uint',
  40560. R32Sint: 'r32sint',
  40561. R32Float: 'r32float',
  40562. RG16Uint: 'rg16uint',
  40563. RG16Sint: 'rg16sint',
  40564. RG16Float: 'rg16float',
  40565. RGBA8Unorm: 'rgba8unorm',
  40566. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  40567. RGBA8Snorm: 'rgba8snorm',
  40568. RGBA8Uint: 'rgba8uint',
  40569. RGBA8Sint: 'rgba8sint',
  40570. BGRA8Unorm: 'bgra8unorm',
  40571. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  40572. // Packed 32-bit formats
  40573. RGB9E5UFloat: 'rgb9e5ufloat',
  40574. RGB10A2Unorm: 'rgb10a2unorm',
  40575. RG11B10uFloat: 'rgb10a2unorm',
  40576. // 64-bit formats
  40577. RG32Uint: 'rg32uint',
  40578. RG32Sint: 'rg32sint',
  40579. RG32Float: 'rg32float',
  40580. RGBA16Uint: 'rgba16uint',
  40581. RGBA16Sint: 'rgba16sint',
  40582. RGBA16Float: 'rgba16float',
  40583. // 128-bit formats
  40584. RGBA32Uint: 'rgba32uint',
  40585. RGBA32Sint: 'rgba32sint',
  40586. RGBA32Float: 'rgba32float',
  40587. // Depth and stencil formats
  40588. Stencil8: 'stencil8',
  40589. Depth16Unorm: 'depth16unorm',
  40590. Depth24Plus: 'depth24plus',
  40591. Depth24PlusStencil8: 'depth24plus-stencil8',
  40592. Depth32Float: 'depth32float',
  40593. // 'depth32float-stencil8' extension
  40594. Depth32FloatStencil8: 'depth32float-stencil8',
  40595. // BC compressed formats usable if 'texture-compression-bc' is both
  40596. // supported by the device/user agent and enabled in requestDevice.
  40597. BC1RGBAUnorm: 'bc1-rgba-unorm',
  40598. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  40599. BC2RGBAUnorm: 'bc2-rgba-unorm',
  40600. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  40601. BC3RGBAUnorm: 'bc3-rgba-unorm',
  40602. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  40603. BC4RUnorm: 'bc4-r-unorm',
  40604. BC4RSnorm: 'bc4-r-snorm',
  40605. BC5RGUnorm: 'bc5-rg-unorm',
  40606. BC5RGSnorm: 'bc5-rg-snorm',
  40607. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  40608. BC6HRGBFloat: 'bc6h-rgb-float',
  40609. BC7RGBAUnorm: 'bc7-rgba-unorm',
  40610. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  40611. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  40612. // supported by the device/user agent and enabled in requestDevice.
  40613. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  40614. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  40615. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  40616. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  40617. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  40618. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  40619. EACR11Unorm: 'eac-r11unorm',
  40620. EACR11Snorm: 'eac-r11snorm',
  40621. EACRG11Unorm: 'eac-rg11unorm',
  40622. EACRG11Snorm: 'eac-rg11snorm',
  40623. // ASTC compressed formats usable if 'texture-compression-astc' is both
  40624. // supported by the device/user agent and enabled in requestDevice.
  40625. ASTC4x4Unorm: 'astc-4x4-unorm',
  40626. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  40627. ASTC5x4Unorm: 'astc-5x4-unorm',
  40628. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  40629. ASTC5x5Unorm: 'astc-5x5-unorm',
  40630. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  40631. ASTC6x5Unorm: 'astc-6x5-unorm',
  40632. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  40633. ASTC6x6Unorm: 'astc-6x6-unorm',
  40634. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  40635. ASTC8x5Unorm: 'astc-8x5-unorm',
  40636. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  40637. ASTC8x6Unorm: 'astc-8x6-unorm',
  40638. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  40639. ASTC8x8Unorm: 'astc-8x8-unorm',
  40640. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  40641. ASTC10x5Unorm: 'astc-10x5-unorm',
  40642. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  40643. ASTC10x6Unorm: 'astc-10x6-unorm',
  40644. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  40645. ASTC10x8Unorm: 'astc-10x8-unorm',
  40646. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  40647. ASTC10x10Unorm: 'astc-10x10-unorm',
  40648. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  40649. ASTC12x10Unorm: 'astc-12x10-unorm',
  40650. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  40651. ASTC12x12Unorm: 'astc-12x12-unorm',
  40652. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  40653. };
  40654. const GPUAddressMode = {
  40655. ClampToEdge: 'clamp-to-edge',
  40656. Repeat: 'repeat',
  40657. MirrorRepeat: 'mirror-repeat'
  40658. };
  40659. const GPUFilterMode = {
  40660. Linear: 'linear',
  40661. Nearest: 'nearest'
  40662. };
  40663. const GPUBlendFactor = {
  40664. Zero: 'zero',
  40665. One: 'one',
  40666. Src: 'src',
  40667. OneMinusSrc: 'one-minus-src',
  40668. SrcAlpha: 'src-alpha',
  40669. OneMinusSrcAlpha: 'one-minus-src-alpha',
  40670. Dst: 'dst',
  40671. OneMinusDstColor: 'one-minus-dst',
  40672. DstAlpha: 'dst-alpha',
  40673. OneMinusDstAlpha: 'one-minus-dst-alpha',
  40674. SrcAlphaSaturated: 'src-alpha-saturated',
  40675. Constant: 'constant',
  40676. OneMinusConstant: 'one-minus-constant'
  40677. };
  40678. const GPUBlendOperation = {
  40679. Add: 'add',
  40680. Subtract: 'subtract',
  40681. ReverseSubtract: 'reverse-subtract',
  40682. Min: 'min',
  40683. Max: 'max'
  40684. };
  40685. const GPUColorWriteFlags = {
  40686. None: 0,
  40687. Red: 0x1,
  40688. Green: 0x2,
  40689. Blue: 0x4,
  40690. Alpha: 0x8,
  40691. All: 0xF
  40692. };
  40693. const GPUStencilOperation = {
  40694. Keep: 'keep',
  40695. Zero: 'zero',
  40696. Replace: 'replace',
  40697. Invert: 'invert',
  40698. IncrementClamp: 'increment-clamp',
  40699. DecrementClamp: 'decrement-clamp',
  40700. IncrementWrap: 'increment-wrap',
  40701. DecrementWrap: 'decrement-wrap'
  40702. };
  40703. const GPUBufferBindingType = {
  40704. Uniform: 'uniform',
  40705. Storage: 'storage',
  40706. ReadOnlyStorage: 'read-only-storage'
  40707. };
  40708. const GPUStorageTextureAccess = {
  40709. WriteOnly: 'write-only',
  40710. ReadOnly: 'read-only',
  40711. ReadWrite: 'read-write',
  40712. };
  40713. const GPUTextureSampleType = {
  40714. Float: 'float',
  40715. UnfilterableFloat: 'unfilterable-float',
  40716. Depth: 'depth',
  40717. SInt: 'sint',
  40718. UInt: 'uint'
  40719. };
  40720. const GPUTextureDimension = {
  40721. OneD: '1d',
  40722. TwoD: '2d',
  40723. ThreeD: '3d'
  40724. };
  40725. const GPUTextureViewDimension = {
  40726. OneD: '1d',
  40727. TwoD: '2d',
  40728. TwoDArray: '2d-array',
  40729. Cube: 'cube',
  40730. CubeArray: 'cube-array',
  40731. ThreeD: '3d'
  40732. };
  40733. const GPUTextureAspect = {
  40734. All: 'all',
  40735. StencilOnly: 'stencil-only',
  40736. DepthOnly: 'depth-only'
  40737. };
  40738. const GPUInputStepMode = {
  40739. Vertex: 'vertex',
  40740. Instance: 'instance'
  40741. };
  40742. const GPUFeatureName = {
  40743. DepthClipControl: 'depth-clip-control',
  40744. Depth32FloatStencil8: 'depth32float-stencil8',
  40745. TextureCompressionBC: 'texture-compression-bc',
  40746. TextureCompressionETC2: 'texture-compression-etc2',
  40747. TextureCompressionASTC: 'texture-compression-astc',
  40748. TimestampQuery: 'timestamp-query',
  40749. IndirectFirstInstance: 'indirect-first-instance',
  40750. ShaderF16: 'shader-f16',
  40751. RG11B10UFloat: 'rg11b10ufloat-renderable',
  40752. BGRA8UNormStorage: 'bgra8unorm-storage',
  40753. Float32Filterable: 'float32-filterable',
  40754. ClipDistances: 'clip-distances',
  40755. DualSourceBlending: 'dual-source-blending',
  40756. Subgroups: 'subgroups'
  40757. };
  40758. /**
  40759. * Represents a sampler binding type.
  40760. *
  40761. * @private
  40762. * @augments Binding
  40763. */
  40764. class Sampler extends Binding {
  40765. /**
  40766. * Constructs a new sampler.
  40767. *
  40768. * @param {String} name - The samplers's name.
  40769. * @param {Texture?} texture - The texture this binding is referring to.
  40770. */
  40771. constructor( name, texture ) {
  40772. super( name );
  40773. /**
  40774. * The texture the sampler is referring to.
  40775. *
  40776. * @type {Texture?}
  40777. */
  40778. this.texture = texture;
  40779. /**
  40780. * The binding's version.
  40781. *
  40782. * @type {Number}
  40783. */
  40784. this.version = texture ? texture.version : 0;
  40785. /**
  40786. * This flag can be used for type testing.
  40787. *
  40788. * @type {Boolean}
  40789. * @readonly
  40790. * @default true
  40791. */
  40792. this.isSampler = true;
  40793. }
  40794. }
  40795. /**
  40796. * A special form of sampler binding type.
  40797. * It's texture value is managed by a node object.
  40798. *
  40799. * @private
  40800. * @augments Sampler
  40801. */
  40802. class NodeSampler extends Sampler {
  40803. /**
  40804. * Constructs a new node-based sampler.
  40805. *
  40806. * @param {String} name - The samplers's name.
  40807. * @param {TextureNode} textureNode - The texture node.
  40808. * @param {UniformGroupNode} groupNode - The uniform group node.
  40809. */
  40810. constructor( name, textureNode, groupNode ) {
  40811. super( name, textureNode ? textureNode.value : null );
  40812. /**
  40813. * The texture node.
  40814. *
  40815. * @type {TextureNode}
  40816. */
  40817. this.textureNode = textureNode;
  40818. /**
  40819. * The uniform group node.
  40820. *
  40821. * @type {UniformGroupNode}
  40822. */
  40823. this.groupNode = groupNode;
  40824. }
  40825. /**
  40826. * Updates the texture value of this sampler.
  40827. */
  40828. update() {
  40829. this.texture = this.textureNode.value;
  40830. }
  40831. }
  40832. /**
  40833. * Represents a storage buffer binding type.
  40834. *
  40835. * @private
  40836. * @augments Buffer
  40837. */
  40838. class StorageBuffer extends Buffer {
  40839. /**
  40840. * Constructs a new uniform buffer.
  40841. *
  40842. * @param {String} name - The buffer's name.
  40843. * @param {BufferAttribute} attribute - The buffer attribute.
  40844. */
  40845. constructor( name, attribute ) {
  40846. super( name, attribute ? attribute.array : null );
  40847. /**
  40848. * This flag can be used for type testing.
  40849. *
  40850. * @type {BufferAttribute}
  40851. */
  40852. this.attribute = attribute;
  40853. /**
  40854. * This flag can be used for type testing.
  40855. *
  40856. * @type {Boolean}
  40857. * @readonly
  40858. * @default true
  40859. */
  40860. this.isStorageBuffer = true;
  40861. }
  40862. }
  40863. let _id = 0;
  40864. /**
  40865. * A special form of storage buffer binding type.
  40866. * It's buffer value is managed by a node object.
  40867. *
  40868. * @private
  40869. * @augments StorageBuffer
  40870. */
  40871. class NodeStorageBuffer extends StorageBuffer {
  40872. /**
  40873. * Constructs a new node-based storage buffer.
  40874. *
  40875. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  40876. * @param {UniformGroupNode} groupNode - The uniform group node.
  40877. */
  40878. constructor( nodeUniform, groupNode ) {
  40879. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  40880. /**
  40881. * The node uniform.
  40882. *
  40883. * @type {StorageBufferNode}
  40884. */
  40885. this.nodeUniform = nodeUniform;
  40886. /**
  40887. * The access type.
  40888. *
  40889. * @type {String}
  40890. */
  40891. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  40892. /**
  40893. * The uniform group node.
  40894. *
  40895. * @type {UniformGroupNode}
  40896. */
  40897. this.groupNode = groupNode;
  40898. }
  40899. /**
  40900. * The storage buffer.
  40901. *
  40902. * @type {BufferAttribute}
  40903. */
  40904. get buffer() {
  40905. return this.nodeUniform.value;
  40906. }
  40907. }
  40908. /**
  40909. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  40910. *
  40911. * @private
  40912. */
  40913. class WebGPUTexturePassUtils extends DataMap {
  40914. /**
  40915. * Constructs a new utility object.
  40916. *
  40917. * @param {GPUDevice} device - The WebGPU device.
  40918. */
  40919. constructor( device ) {
  40920. super();
  40921. /**
  40922. * The WebGPU device.
  40923. *
  40924. * @type {GPUDevice}
  40925. */
  40926. this.device = device;
  40927. const mipmapVertexSource = `
  40928. struct VarysStruct {
  40929. @builtin( position ) Position: vec4<f32>,
  40930. @location( 0 ) vTex : vec2<f32>
  40931. };
  40932. @vertex
  40933. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  40934. var Varys : VarysStruct;
  40935. var pos = array< vec2<f32>, 4 >(
  40936. vec2<f32>( -1.0, 1.0 ),
  40937. vec2<f32>( 1.0, 1.0 ),
  40938. vec2<f32>( -1.0, -1.0 ),
  40939. vec2<f32>( 1.0, -1.0 )
  40940. );
  40941. var tex = array< vec2<f32>, 4 >(
  40942. vec2<f32>( 0.0, 0.0 ),
  40943. vec2<f32>( 1.0, 0.0 ),
  40944. vec2<f32>( 0.0, 1.0 ),
  40945. vec2<f32>( 1.0, 1.0 )
  40946. );
  40947. Varys.vTex = tex[ vertexIndex ];
  40948. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  40949. return Varys;
  40950. }
  40951. `;
  40952. const mipmapFragmentSource = `
  40953. @group( 0 ) @binding( 0 )
  40954. var imgSampler : sampler;
  40955. @group( 0 ) @binding( 1 )
  40956. var img : texture_2d<f32>;
  40957. @fragment
  40958. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  40959. return textureSample( img, imgSampler, vTex );
  40960. }
  40961. `;
  40962. const flipYFragmentSource = `
  40963. @group( 0 ) @binding( 0 )
  40964. var imgSampler : sampler;
  40965. @group( 0 ) @binding( 1 )
  40966. var img : texture_2d<f32>;
  40967. @fragment
  40968. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  40969. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  40970. }
  40971. `;
  40972. /**
  40973. * The mipmap GPU sampler.
  40974. *
  40975. * @type {GPUSampler}
  40976. */
  40977. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  40978. /**
  40979. * The flipY GPU sampler.
  40980. *
  40981. * @type {GPUSampler}
  40982. */
  40983. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  40984. /**
  40985. * A cache for GPU render pipelines used for copy/transfer passes.
  40986. * Every texture format requires a unique pipeline.
  40987. *
  40988. * @type {Object<String,GPURenderPipeline>}
  40989. */
  40990. this.transferPipelines = {};
  40991. /**
  40992. * A cache for GPU render pipelines used for flipY passes.
  40993. * Every texture format requires a unique pipeline.
  40994. *
  40995. * @type {Object<String,GPURenderPipeline>}
  40996. */
  40997. this.flipYPipelines = {};
  40998. /**
  40999. * The mipmap vertex shader module.
  41000. *
  41001. * @type {GPUShaderModule}
  41002. */
  41003. this.mipmapVertexShaderModule = device.createShaderModule( {
  41004. label: 'mipmapVertex',
  41005. code: mipmapVertexSource
  41006. } );
  41007. /**
  41008. * The mipmap fragment shader module.
  41009. *
  41010. * @type {GPUShaderModule}
  41011. */
  41012. this.mipmapFragmentShaderModule = device.createShaderModule( {
  41013. label: 'mipmapFragment',
  41014. code: mipmapFragmentSource
  41015. } );
  41016. /**
  41017. * The flipY fragment shader module.
  41018. *
  41019. * @type {GPUShaderModule}
  41020. */
  41021. this.flipYFragmentShaderModule = device.createShaderModule( {
  41022. label: 'flipYFragment',
  41023. code: flipYFragmentSource
  41024. } );
  41025. }
  41026. /**
  41027. * Returns a render pipeline for the internal copy render pass. The pass
  41028. * requires a unique render pipeline for each texture format.
  41029. *
  41030. * @param {String} format - The GPU texture format
  41031. * @return {GPURenderPipeline} The GPU render pipeline.
  41032. */
  41033. getTransferPipeline( format ) {
  41034. let pipeline = this.transferPipelines[ format ];
  41035. if ( pipeline === undefined ) {
  41036. pipeline = this.device.createRenderPipeline( {
  41037. label: `mipmap-${ format }`,
  41038. vertex: {
  41039. module: this.mipmapVertexShaderModule,
  41040. entryPoint: 'main'
  41041. },
  41042. fragment: {
  41043. module: this.mipmapFragmentShaderModule,
  41044. entryPoint: 'main',
  41045. targets: [ { format } ]
  41046. },
  41047. primitive: {
  41048. topology: GPUPrimitiveTopology.TriangleStrip,
  41049. stripIndexFormat: GPUIndexFormat.Uint32
  41050. },
  41051. layout: 'auto'
  41052. } );
  41053. this.transferPipelines[ format ] = pipeline;
  41054. }
  41055. return pipeline;
  41056. }
  41057. /**
  41058. * Returns a render pipeline for the flipY render pass. The pass
  41059. * requires a unique render pipeline for each texture format.
  41060. *
  41061. * @param {String} format - The GPU texture format
  41062. * @return {GPURenderPipeline} The GPU render pipeline.
  41063. */
  41064. getFlipYPipeline( format ) {
  41065. let pipeline = this.flipYPipelines[ format ];
  41066. if ( pipeline === undefined ) {
  41067. pipeline = this.device.createRenderPipeline( {
  41068. label: `flipY-${ format }`,
  41069. vertex: {
  41070. module: this.mipmapVertexShaderModule,
  41071. entryPoint: 'main'
  41072. },
  41073. fragment: {
  41074. module: this.flipYFragmentShaderModule,
  41075. entryPoint: 'main',
  41076. targets: [ { format } ]
  41077. },
  41078. primitive: {
  41079. topology: GPUPrimitiveTopology.TriangleStrip,
  41080. stripIndexFormat: GPUIndexFormat.Uint32
  41081. },
  41082. layout: 'auto'
  41083. } );
  41084. this.flipYPipelines[ format ] = pipeline;
  41085. }
  41086. return pipeline;
  41087. }
  41088. /**
  41089. * Flip the contents of the given GPU texture along its vertical axis.
  41090. *
  41091. * @param {GPUTexture} textureGPU - The GPU texture object.
  41092. * @param {Object} textureGPUDescriptor - The texture descriptor.
  41093. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  41094. */
  41095. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41096. const format = textureGPUDescriptor.format;
  41097. const { width, height } = textureGPUDescriptor.size;
  41098. const transferPipeline = this.getTransferPipeline( format );
  41099. const flipYPipeline = this.getFlipYPipeline( format );
  41100. const tempTexture = this.device.createTexture( {
  41101. size: { width, height, depthOrArrayLayers: 1 },
  41102. format,
  41103. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  41104. } );
  41105. const srcView = textureGPU.createView( {
  41106. baseMipLevel: 0,
  41107. mipLevelCount: 1,
  41108. dimension: GPUTextureViewDimension.TwoD,
  41109. baseArrayLayer
  41110. } );
  41111. const dstView = tempTexture.createView( {
  41112. baseMipLevel: 0,
  41113. mipLevelCount: 1,
  41114. dimension: GPUTextureViewDimension.TwoD,
  41115. baseArrayLayer: 0
  41116. } );
  41117. const commandEncoder = this.device.createCommandEncoder( {} );
  41118. const pass = ( pipeline, sourceView, destinationView ) => {
  41119. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41120. const bindGroup = this.device.createBindGroup( {
  41121. layout: bindGroupLayout,
  41122. entries: [ {
  41123. binding: 0,
  41124. resource: this.flipYSampler
  41125. }, {
  41126. binding: 1,
  41127. resource: sourceView
  41128. } ]
  41129. } );
  41130. const passEncoder = commandEncoder.beginRenderPass( {
  41131. colorAttachments: [ {
  41132. view: destinationView,
  41133. loadOp: GPULoadOp.Clear,
  41134. storeOp: GPUStoreOp.Store,
  41135. clearValue: [ 0, 0, 0, 0 ]
  41136. } ]
  41137. } );
  41138. passEncoder.setPipeline( pipeline );
  41139. passEncoder.setBindGroup( 0, bindGroup );
  41140. passEncoder.draw( 4, 1, 0, 0 );
  41141. passEncoder.end();
  41142. };
  41143. pass( transferPipeline, srcView, dstView );
  41144. pass( flipYPipeline, dstView, srcView );
  41145. this.device.queue.submit( [ commandEncoder.finish() ] );
  41146. tempTexture.destroy();
  41147. }
  41148. /**
  41149. * Generates mipmaps for the given GPU texture.
  41150. *
  41151. * @param {GPUTexture} textureGPU - The GPU texture object.
  41152. * @param {Object} textureGPUDescriptor - The texture descriptor.
  41153. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  41154. */
  41155. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41156. const textureData = this.get( textureGPU );
  41157. if ( textureData.useCount === undefined ) {
  41158. textureData.useCount = 0;
  41159. textureData.layers = [];
  41160. }
  41161. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  41162. const commandEncoder = this.device.createCommandEncoder( {} );
  41163. this._mipmapRunBundles( commandEncoder, passes );
  41164. this.device.queue.submit( [ commandEncoder.finish() ] );
  41165. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  41166. textureData.useCount ++;
  41167. }
  41168. /**
  41169. * Since multiple copy render passes are required to generate mipmaps, the passes
  41170. * are managed as render bundles to improve performance.
  41171. *
  41172. * @param {GPUTexture} textureGPU - The GPU texture object.
  41173. * @param {Object} textureGPUDescriptor - The texture descriptor.
  41174. * @param {Number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  41175. * @return {Array} An array of render bundles.
  41176. */
  41177. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  41178. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  41179. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41180. let srcView = textureGPU.createView( {
  41181. baseMipLevel: 0,
  41182. mipLevelCount: 1,
  41183. dimension: GPUTextureViewDimension.TwoD,
  41184. baseArrayLayer
  41185. } );
  41186. const passes = [];
  41187. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  41188. const bindGroup = this.device.createBindGroup( {
  41189. layout: bindGroupLayout,
  41190. entries: [ {
  41191. binding: 0,
  41192. resource: this.mipmapSampler
  41193. }, {
  41194. binding: 1,
  41195. resource: srcView
  41196. } ]
  41197. } );
  41198. const dstView = textureGPU.createView( {
  41199. baseMipLevel: i,
  41200. mipLevelCount: 1,
  41201. dimension: GPUTextureViewDimension.TwoD,
  41202. baseArrayLayer
  41203. } );
  41204. const passDescriptor = {
  41205. colorAttachments: [ {
  41206. view: dstView,
  41207. loadOp: GPULoadOp.Clear,
  41208. storeOp: GPUStoreOp.Store,
  41209. clearValue: [ 0, 0, 0, 0 ]
  41210. } ]
  41211. };
  41212. const passEncoder = this.device.createRenderBundleEncoder( {
  41213. colorFormats: [ textureGPUDescriptor.format ]
  41214. } );
  41215. passEncoder.setPipeline( pipeline );
  41216. passEncoder.setBindGroup( 0, bindGroup );
  41217. passEncoder.draw( 4, 1, 0, 0 );
  41218. passes.push( {
  41219. renderBundles: [ passEncoder.finish() ],
  41220. passDescriptor
  41221. } );
  41222. srcView = dstView;
  41223. }
  41224. return passes;
  41225. }
  41226. /**
  41227. * Executes the render bundles.
  41228. *
  41229. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  41230. * @param {Array} passes - An array of render bundles.
  41231. */
  41232. _mipmapRunBundles( commandEncoder, passes ) {
  41233. const levels = passes.length;
  41234. for ( let i = 0; i < levels; i ++ ) {
  41235. const pass = passes[ i ];
  41236. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  41237. passEncoder.executeBundles( pass.renderBundles );
  41238. passEncoder.end();
  41239. }
  41240. }
  41241. }
  41242. const _compareToWebGPU = {
  41243. [ NeverCompare ]: 'never',
  41244. [ LessCompare ]: 'less',
  41245. [ EqualCompare ]: 'equal',
  41246. [ LessEqualCompare ]: 'less-equal',
  41247. [ GreaterCompare ]: 'greater',
  41248. [ GreaterEqualCompare ]: 'greater-equal',
  41249. [ AlwaysCompare ]: 'always',
  41250. [ NotEqualCompare ]: 'not-equal'
  41251. };
  41252. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  41253. /**
  41254. * A WebGPU backend utility module for managing textures.
  41255. *
  41256. * @private
  41257. */
  41258. class WebGPUTextureUtils {
  41259. /**
  41260. * Constructs a new utility object.
  41261. *
  41262. * @param {WebGPUBackend} backend - The WebGPU backend.
  41263. */
  41264. constructor( backend ) {
  41265. /**
  41266. * A reference to the WebGPU backend.
  41267. *
  41268. * @type {WebGPUBackend}
  41269. */
  41270. this.backend = backend;
  41271. /**
  41272. * A reference to the pass utils.
  41273. *
  41274. * @type {WebGPUTexturePassUtils?}
  41275. * @default null
  41276. */
  41277. this._passUtils = null;
  41278. /**
  41279. * A dictionary for managing default textures. The key
  41280. * is the texture format, the value the texture object.
  41281. *
  41282. * @type {Object<String,Texture>}
  41283. */
  41284. this.defaultTexture = {};
  41285. /**
  41286. * A dictionary for managing default cube textures. The key
  41287. * is the texture format, the value the texture object.
  41288. *
  41289. * @type {Object<String,CubeTexture>}
  41290. */
  41291. this.defaultCubeTexture = {};
  41292. /**
  41293. * A default video frame.
  41294. *
  41295. * @type {VideoFrame?}
  41296. * @default null
  41297. */
  41298. this.defaultVideoFrame = null;
  41299. /**
  41300. * Represents the color attachment of the default framebuffer.
  41301. *
  41302. * @type {GPUTexture?}
  41303. * @default null
  41304. */
  41305. this.colorBuffer = null;
  41306. /**
  41307. * Represents the depth attachment of the default framebuffer.
  41308. *
  41309. * @type {DepthTexture}
  41310. */
  41311. this.depthTexture = new DepthTexture();
  41312. this.depthTexture.name = 'depthBuffer';
  41313. }
  41314. /**
  41315. * Creates a GPU sampler for the given texture.
  41316. *
  41317. * @param {Texture} texture - The texture to create the sampler for.
  41318. */
  41319. createSampler( texture ) {
  41320. const backend = this.backend;
  41321. const device = backend.device;
  41322. const textureGPU = backend.get( texture );
  41323. const samplerDescriptorGPU = {
  41324. addressModeU: this._convertAddressMode( texture.wrapS ),
  41325. addressModeV: this._convertAddressMode( texture.wrapT ),
  41326. addressModeW: this._convertAddressMode( texture.wrapR ),
  41327. magFilter: this._convertFilterMode( texture.magFilter ),
  41328. minFilter: this._convertFilterMode( texture.minFilter ),
  41329. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  41330. maxAnisotropy: 1
  41331. };
  41332. // anisotropy can only be used when all filter modes are set to linear.
  41333. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  41334. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  41335. }
  41336. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  41337. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  41338. }
  41339. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  41340. }
  41341. /**
  41342. * Creates a default texture for the given texture that can be used
  41343. * as a placeholder until the actual texture is ready for usage.
  41344. *
  41345. * @param {Texture} texture - The texture to create a default texture for.
  41346. */
  41347. createDefaultTexture( texture ) {
  41348. let textureGPU;
  41349. const format = getFormat( texture );
  41350. if ( texture.isCubeTexture ) {
  41351. textureGPU = this._getDefaultCubeTextureGPU( format );
  41352. } else if ( texture.isVideoTexture ) {
  41353. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  41354. } else {
  41355. textureGPU = this._getDefaultTextureGPU( format );
  41356. }
  41357. this.backend.get( texture ).texture = textureGPU;
  41358. }
  41359. /**
  41360. * Defines a texture on the GPU for the given texture object.
  41361. *
  41362. * @param {Texture} texture - The texture.
  41363. * @param {Object} [options={}] - Optional configuration parameter.
  41364. * @return {undefined}
  41365. */
  41366. createTexture( texture, options = {} ) {
  41367. const backend = this.backend;
  41368. const textureData = backend.get( texture );
  41369. if ( textureData.initialized ) {
  41370. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  41371. }
  41372. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  41373. if ( options.levels === undefined ) options.levels = 1;
  41374. if ( options.depth === undefined ) options.depth = 1;
  41375. const { width, height, depth, levels } = options;
  41376. if ( texture.isFramebufferTexture ) {
  41377. if ( options.renderTarget ) {
  41378. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  41379. } else {
  41380. options.format = this.backend.utils.getPreferredCanvasFormat();
  41381. }
  41382. }
  41383. const dimension = this._getDimension( texture );
  41384. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  41385. textureData.format = format;
  41386. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  41387. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  41388. if ( texture.isStorageTexture === true ) {
  41389. usage |= GPUTextureUsage.STORAGE_BINDING;
  41390. }
  41391. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  41392. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  41393. }
  41394. const textureDescriptorGPU = {
  41395. label: texture.name,
  41396. size: {
  41397. width: width,
  41398. height: height,
  41399. depthOrArrayLayers: depth,
  41400. },
  41401. mipLevelCount: levels,
  41402. sampleCount: primarySamples,
  41403. dimension: dimension,
  41404. format: format,
  41405. usage: usage
  41406. };
  41407. // texture creation
  41408. if ( texture.isVideoTexture ) {
  41409. const video = texture.source.data;
  41410. const videoFrame = new VideoFrame( video );
  41411. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  41412. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  41413. videoFrame.close();
  41414. textureData.externalTexture = video;
  41415. } else {
  41416. if ( format === undefined ) {
  41417. console.warn( 'WebGPURenderer: Texture format not supported.' );
  41418. return this.createDefaultTexture( texture );
  41419. }
  41420. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  41421. }
  41422. if ( isMSAA ) {
  41423. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  41424. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  41425. msaaTextureDescriptorGPU.sampleCount = samples;
  41426. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  41427. }
  41428. textureData.initialized = true;
  41429. textureData.textureDescriptorGPU = textureDescriptorGPU;
  41430. }
  41431. /**
  41432. * Destroys the GPU data for the given texture object.
  41433. *
  41434. * @param {Texture} texture - The texture.
  41435. */
  41436. destroyTexture( texture ) {
  41437. const backend = this.backend;
  41438. const textureData = backend.get( texture );
  41439. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  41440. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  41441. backend.delete( texture );
  41442. }
  41443. /**
  41444. * Destroys the GPU sampler for the given texture.
  41445. *
  41446. * @param {Texture} texture - The texture to destroy the sampler for.
  41447. */
  41448. destroySampler( texture ) {
  41449. const backend = this.backend;
  41450. const textureData = backend.get( texture );
  41451. delete textureData.sampler;
  41452. }
  41453. /**
  41454. * Generates mipmaps for the given texture.
  41455. *
  41456. * @param {Texture} texture - The texture.
  41457. */
  41458. generateMipmaps( texture ) {
  41459. const textureData = this.backend.get( texture );
  41460. if ( texture.isCubeTexture ) {
  41461. for ( let i = 0; i < 6; i ++ ) {
  41462. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41463. }
  41464. } else {
  41465. const depth = texture.image.depth || 1;
  41466. for ( let i = 0; i < depth; i ++ ) {
  41467. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41468. }
  41469. }
  41470. }
  41471. /**
  41472. * Returns the color buffer representing the color
  41473. * attachment of the default framebuffer.
  41474. *
  41475. * @return {GPUTexture} The color buffer.
  41476. */
  41477. getColorBuffer() {
  41478. if ( this.colorBuffer ) this.colorBuffer.destroy();
  41479. const backend = this.backend;
  41480. const { width, height } = backend.getDrawingBufferSize();
  41481. this.colorBuffer = backend.device.createTexture( {
  41482. label: 'colorBuffer',
  41483. size: {
  41484. width: width,
  41485. height: height,
  41486. depthOrArrayLayers: 1
  41487. },
  41488. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  41489. format: backend.utils.getPreferredCanvasFormat(),
  41490. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  41491. } );
  41492. return this.colorBuffer;
  41493. }
  41494. /**
  41495. * Returns the depth buffer representing the depth
  41496. * attachment of the default framebuffer.
  41497. *
  41498. * @param {Boolean} [depth=true] - Whether depth is enabled or not.
  41499. * @param {Boolean} [stencil=false] - Whether stencil is enabled or not.
  41500. * @return {GPUTexture} The depth buffer.
  41501. */
  41502. getDepthBuffer( depth = true, stencil = false ) {
  41503. const backend = this.backend;
  41504. const { width, height } = backend.getDrawingBufferSize();
  41505. const depthTexture = this.depthTexture;
  41506. const depthTextureGPU = backend.get( depthTexture ).texture;
  41507. let format, type;
  41508. if ( stencil ) {
  41509. format = DepthStencilFormat;
  41510. type = UnsignedInt248Type;
  41511. } else if ( depth ) {
  41512. format = DepthFormat;
  41513. type = UnsignedIntType;
  41514. }
  41515. if ( depthTextureGPU !== undefined ) {
  41516. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  41517. return depthTextureGPU;
  41518. }
  41519. this.destroyTexture( depthTexture );
  41520. }
  41521. depthTexture.name = 'depthBuffer';
  41522. depthTexture.format = format;
  41523. depthTexture.type = type;
  41524. depthTexture.image.width = width;
  41525. depthTexture.image.height = height;
  41526. this.createTexture( depthTexture, { width, height } );
  41527. return backend.get( depthTexture ).texture;
  41528. }
  41529. /**
  41530. * Uploads the updated texture data to the GPU.
  41531. *
  41532. * @param {Texture} texture - The texture.
  41533. * @param {Object} [options={}] - Optional configuration parameter.
  41534. */
  41535. updateTexture( texture, options ) {
  41536. const textureData = this.backend.get( texture );
  41537. const { textureDescriptorGPU } = textureData;
  41538. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  41539. return;
  41540. // transfer texture data
  41541. if ( texture.isDataTexture ) {
  41542. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41543. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  41544. for ( let i = 0; i < options.image.depth; i ++ ) {
  41545. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  41546. }
  41547. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  41548. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  41549. } else if ( texture.isCubeTexture ) {
  41550. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  41551. } else if ( texture.isVideoTexture ) {
  41552. const video = texture.source.data;
  41553. textureData.externalTexture = video;
  41554. } else {
  41555. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41556. }
  41557. //
  41558. textureData.version = texture.version;
  41559. if ( texture.onUpdate ) texture.onUpdate( texture );
  41560. }
  41561. /**
  41562. * Returns texture data as a typed array.
  41563. *
  41564. * @async
  41565. * @param {Texture} texture - The texture to copy.
  41566. * @param {Number} x - The x coordinate of the copy origin.
  41567. * @param {Number} y - The y coordinate of the copy origin.
  41568. * @param {Number} width - The width of the copy.
  41569. * @param {Number} height - The height of the copy.
  41570. * @param {Number} faceIndex - The face index.
  41571. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  41572. */
  41573. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41574. const device = this.backend.device;
  41575. const textureData = this.backend.get( texture );
  41576. const textureGPU = textureData.texture;
  41577. const format = textureData.textureDescriptorGPU.format;
  41578. const bytesPerTexel = this._getBytesPerTexel( format );
  41579. let bytesPerRow = width * bytesPerTexel;
  41580. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  41581. const readBuffer = device.createBuffer(
  41582. {
  41583. size: width * height * bytesPerTexel,
  41584. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41585. }
  41586. );
  41587. const encoder = device.createCommandEncoder();
  41588. encoder.copyTextureToBuffer(
  41589. {
  41590. texture: textureGPU,
  41591. origin: { x, y, z: faceIndex },
  41592. },
  41593. {
  41594. buffer: readBuffer,
  41595. bytesPerRow: bytesPerRow
  41596. },
  41597. {
  41598. width: width,
  41599. height: height
  41600. }
  41601. );
  41602. const typedArrayType = this._getTypedArrayType( format );
  41603. device.queue.submit( [ encoder.finish() ] );
  41604. await readBuffer.mapAsync( GPUMapMode.READ );
  41605. const buffer = readBuffer.getMappedRange();
  41606. return new typedArrayType( buffer );
  41607. }
  41608. /**
  41609. * Returns `true` if the given texture is an environment map.
  41610. *
  41611. * @private
  41612. * @param {Texture} texture - The texture.
  41613. * @return {Boolean} Whether the given texture is an environment map or not.
  41614. */
  41615. _isEnvironmentTexture( texture ) {
  41616. const mapping = texture.mapping;
  41617. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  41618. }
  41619. /**
  41620. * Returns the default GPU texture for the given format.
  41621. *
  41622. * @private
  41623. * @param {String} format - The GPU format.
  41624. * @return {GPUTexture} The GPU texture.
  41625. */
  41626. _getDefaultTextureGPU( format ) {
  41627. let defaultTexture = this.defaultTexture[ format ];
  41628. if ( defaultTexture === undefined ) {
  41629. const texture = new Texture();
  41630. texture.minFilter = NearestFilter;
  41631. texture.magFilter = NearestFilter;
  41632. this.createTexture( texture, { width: 1, height: 1, format } );
  41633. this.defaultTexture[ format ] = defaultTexture = texture;
  41634. }
  41635. return this.backend.get( defaultTexture ).texture;
  41636. }
  41637. /**
  41638. * Returns the default GPU cube texture for the given format.
  41639. *
  41640. * @private
  41641. * @param {String} format - The GPU format.
  41642. * @return {GPUTexture} The GPU texture.
  41643. */
  41644. _getDefaultCubeTextureGPU( format ) {
  41645. let defaultCubeTexture = this.defaultTexture[ format ];
  41646. if ( defaultCubeTexture === undefined ) {
  41647. const texture = new CubeTexture();
  41648. texture.minFilter = NearestFilter;
  41649. texture.magFilter = NearestFilter;
  41650. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  41651. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  41652. }
  41653. return this.backend.get( defaultCubeTexture ).texture;
  41654. }
  41655. /**
  41656. * Returns the default video frame used as default data in context of video textures.
  41657. *
  41658. * @private
  41659. * @return {VideoFrame} The video frame.
  41660. */
  41661. _getDefaultVideoFrame() {
  41662. let defaultVideoFrame = this.defaultVideoFrame;
  41663. if ( defaultVideoFrame === null ) {
  41664. const init = {
  41665. timestamp: 0,
  41666. codedWidth: 1,
  41667. codedHeight: 1,
  41668. format: 'RGBA',
  41669. };
  41670. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  41671. }
  41672. return defaultVideoFrame;
  41673. }
  41674. /**
  41675. * Uploads cube texture image data to the GPU memory.
  41676. *
  41677. * @private
  41678. * @param {Array} images - The cube image data.
  41679. * @param {GPUTexture} textureGPU - The GPU texture.
  41680. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  41681. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  41682. */
  41683. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  41684. for ( let i = 0; i < 6; i ++ ) {
  41685. const image = images[ i ];
  41686. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  41687. if ( image.isDataTexture ) {
  41688. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  41689. } else {
  41690. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  41691. }
  41692. }
  41693. }
  41694. /**
  41695. * Uploads texture image data to the GPU memory.
  41696. *
  41697. * @private
  41698. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  41699. * @param {GPUTexture} textureGPU - The GPU texture.
  41700. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  41701. * @param {Number} originDepth - The origin depth.
  41702. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  41703. */
  41704. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  41705. const device = this.backend.device;
  41706. device.queue.copyExternalImageToTexture(
  41707. {
  41708. source: image,
  41709. flipY: flipY
  41710. }, {
  41711. texture: textureGPU,
  41712. mipLevel: 0,
  41713. origin: { x: 0, y: 0, z: originDepth }
  41714. }, {
  41715. width: image.width,
  41716. height: image.height,
  41717. depthOrArrayLayers: 1
  41718. }
  41719. );
  41720. }
  41721. /**
  41722. * Returns the pass utils singleton.
  41723. *
  41724. * @private
  41725. * @return {WebGPUTexturePassUtils} The utils instance.
  41726. */
  41727. _getPassUtils() {
  41728. let passUtils = this._passUtils;
  41729. if ( passUtils === null ) {
  41730. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  41731. }
  41732. return passUtils;
  41733. }
  41734. /**
  41735. * Generates mipmaps for the given GPU texture.
  41736. *
  41737. * @private
  41738. * @param {GPUTexture} textureGPU - The GPU texture object.
  41739. * @param {Object} textureDescriptorGPU - The texture descriptor.
  41740. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  41741. */
  41742. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  41743. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  41744. }
  41745. /**
  41746. * Flip the contents of the given GPU texture along its vertical axis.
  41747. *
  41748. * @private
  41749. * @param {GPUTexture} textureGPU - The GPU texture object.
  41750. * @param {Object} textureDescriptorGPU - The texture descriptor.
  41751. * @param {Number} [originDepth=0] - The origin depth.
  41752. */
  41753. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  41754. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  41755. }
  41756. /**
  41757. * Uploads texture buffer data to the GPU memory.
  41758. *
  41759. * @private
  41760. * @param {Object} image - An object defining the image buffer data.
  41761. * @param {GPUTexture} textureGPU - The GPU texture.
  41762. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  41763. * @param {Number} originDepth - The origin depth.
  41764. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  41765. * @param {Number} [depth=0] - TODO.
  41766. */
  41767. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  41768. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  41769. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  41770. const device = this.backend.device;
  41771. const data = image.data;
  41772. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  41773. const bytesPerRow = image.width * bytesPerTexel;
  41774. device.queue.writeTexture(
  41775. {
  41776. texture: textureGPU,
  41777. mipLevel: 0,
  41778. origin: { x: 0, y: 0, z: originDepth }
  41779. },
  41780. data,
  41781. {
  41782. offset: image.width * image.height * bytesPerTexel * depth,
  41783. bytesPerRow
  41784. },
  41785. {
  41786. width: image.width,
  41787. height: image.height,
  41788. depthOrArrayLayers: 1
  41789. } );
  41790. if ( flipY === true ) {
  41791. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  41792. }
  41793. }
  41794. /**
  41795. * Uploads compressed texture data to the GPU memory.
  41796. *
  41797. * @private
  41798. * @param {Array<Object>} mipmaps - An array with mipmap data.
  41799. * @param {GPUTexture} textureGPU - The GPU texture.
  41800. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  41801. */
  41802. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  41803. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  41804. const device = this.backend.device;
  41805. const blockData = this._getBlockData( textureDescriptorGPU.format );
  41806. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  41807. for ( let i = 0; i < mipmaps.length; i ++ ) {
  41808. const mipmap = mipmaps[ i ];
  41809. const width = mipmap.width;
  41810. const height = mipmap.height;
  41811. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  41812. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  41813. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  41814. for ( let j = 0; j < depth; j ++ ) {
  41815. device.queue.writeTexture(
  41816. {
  41817. texture: textureGPU,
  41818. mipLevel: i,
  41819. origin: { x: 0, y: 0, z: j }
  41820. },
  41821. mipmap.data,
  41822. {
  41823. offset: j * bytesPerImage,
  41824. bytesPerRow,
  41825. rowsPerImage: Math.ceil( height / blockData.height )
  41826. },
  41827. {
  41828. width: Math.ceil( width / blockData.width ) * blockData.width,
  41829. height: Math.ceil( height / blockData.height ) * blockData.height,
  41830. depthOrArrayLayers: 1
  41831. }
  41832. );
  41833. }
  41834. }
  41835. }
  41836. /**
  41837. * This method is only relevant for compressed texture formats. It returns a block
  41838. * data descriptor for the given GPU compressed texture format.
  41839. *
  41840. * @private
  41841. * @param {String} format - The GPU compressed texture format.
  41842. * @return {Object} The block data descriptor.
  41843. */
  41844. _getBlockData( format ) {
  41845. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  41846. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  41847. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  41848. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  41849. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  41850. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  41851. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  41852. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  41853. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  41854. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  41855. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  41856. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  41857. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  41858. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  41859. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  41860. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  41861. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  41862. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  41863. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  41864. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  41865. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  41866. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  41867. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  41868. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  41869. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  41870. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  41871. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  41872. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  41873. }
  41874. /**
  41875. * Converts the three.js uv wrapping constants to GPU address mode constants.
  41876. *
  41877. * @private
  41878. * @param {Number} value - The three.js constant defining a uv wrapping mode.
  41879. * @return {String} The GPU address mode.
  41880. */
  41881. _convertAddressMode( value ) {
  41882. let addressMode = GPUAddressMode.ClampToEdge;
  41883. if ( value === RepeatWrapping ) {
  41884. addressMode = GPUAddressMode.Repeat;
  41885. } else if ( value === MirroredRepeatWrapping ) {
  41886. addressMode = GPUAddressMode.MirrorRepeat;
  41887. }
  41888. return addressMode;
  41889. }
  41890. /**
  41891. * Converts the three.js filter constants to GPU filter constants.
  41892. *
  41893. * @private
  41894. * @param {Number} value - The three.js constant defining a filter mode.
  41895. * @return {String} The GPU filter mode.
  41896. */
  41897. _convertFilterMode( value ) {
  41898. let filterMode = GPUFilterMode.Linear;
  41899. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  41900. filterMode = GPUFilterMode.Nearest;
  41901. }
  41902. return filterMode;
  41903. }
  41904. /**
  41905. * Returns the bytes-per-texel value for the given GPU texture format.
  41906. *
  41907. * @private
  41908. * @param {String} format - The GPU texture format.
  41909. * @return {Number} The bytes-per-texel.
  41910. */
  41911. _getBytesPerTexel( format ) {
  41912. // 8-bit formats
  41913. if ( format === GPUTextureFormat.R8Unorm ||
  41914. format === GPUTextureFormat.R8Snorm ||
  41915. format === GPUTextureFormat.R8Uint ||
  41916. format === GPUTextureFormat.R8Sint ) return 1;
  41917. // 16-bit formats
  41918. if ( format === GPUTextureFormat.R16Uint ||
  41919. format === GPUTextureFormat.R16Sint ||
  41920. format === GPUTextureFormat.R16Float ||
  41921. format === GPUTextureFormat.RG8Unorm ||
  41922. format === GPUTextureFormat.RG8Snorm ||
  41923. format === GPUTextureFormat.RG8Uint ||
  41924. format === GPUTextureFormat.RG8Sint ) return 2;
  41925. // 32-bit formats
  41926. if ( format === GPUTextureFormat.R32Uint ||
  41927. format === GPUTextureFormat.R32Sint ||
  41928. format === GPUTextureFormat.R32Float ||
  41929. format === GPUTextureFormat.RG16Uint ||
  41930. format === GPUTextureFormat.RG16Sint ||
  41931. format === GPUTextureFormat.RG16Float ||
  41932. format === GPUTextureFormat.RGBA8Unorm ||
  41933. format === GPUTextureFormat.RGBA8UnormSRGB ||
  41934. format === GPUTextureFormat.RGBA8Snorm ||
  41935. format === GPUTextureFormat.RGBA8Uint ||
  41936. format === GPUTextureFormat.RGBA8Sint ||
  41937. format === GPUTextureFormat.BGRA8Unorm ||
  41938. format === GPUTextureFormat.BGRA8UnormSRGB ||
  41939. // Packed 32-bit formats
  41940. format === GPUTextureFormat.RGB9E5UFloat ||
  41941. format === GPUTextureFormat.RGB10A2Unorm ||
  41942. format === GPUTextureFormat.RG11B10UFloat ||
  41943. format === GPUTextureFormat.Depth32Float ||
  41944. format === GPUTextureFormat.Depth24Plus ||
  41945. format === GPUTextureFormat.Depth24PlusStencil8 ||
  41946. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  41947. // 64-bit formats
  41948. if ( format === GPUTextureFormat.RG32Uint ||
  41949. format === GPUTextureFormat.RG32Sint ||
  41950. format === GPUTextureFormat.RG32Float ||
  41951. format === GPUTextureFormat.RGBA16Uint ||
  41952. format === GPUTextureFormat.RGBA16Sint ||
  41953. format === GPUTextureFormat.RGBA16Float ) return 8;
  41954. // 128-bit formats
  41955. if ( format === GPUTextureFormat.RGBA32Uint ||
  41956. format === GPUTextureFormat.RGBA32Sint ||
  41957. format === GPUTextureFormat.RGBA32Float ) return 16;
  41958. }
  41959. /**
  41960. * Returns the corresponding typed array type for the given GPU texture format.
  41961. *
  41962. * @private
  41963. * @param {String} format - The GPU texture format.
  41964. * @return {TypedArray.constructor} The typed array type.
  41965. */
  41966. _getTypedArrayType( format ) {
  41967. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  41968. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  41969. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  41970. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  41971. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  41972. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  41973. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  41974. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  41975. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  41976. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  41977. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  41978. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  41979. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  41980. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  41981. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  41982. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  41983. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  41984. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  41985. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  41986. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  41987. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  41988. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  41989. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  41990. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  41991. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  41992. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  41993. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  41994. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  41995. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  41996. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  41997. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  41998. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  41999. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  42000. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  42001. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  42002. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  42003. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  42004. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  42005. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  42006. }
  42007. /**
  42008. * Returns the GPU dimensions for the given texture.
  42009. *
  42010. * @private
  42011. * @param {Texture} texture - The texture.
  42012. * @return {String} The GPU dimension.
  42013. */
  42014. _getDimension( texture ) {
  42015. let dimension;
  42016. if ( texture.isData3DTexture ) {
  42017. dimension = GPUTextureDimension.ThreeD;
  42018. } else {
  42019. dimension = GPUTextureDimension.TwoD;
  42020. }
  42021. return dimension;
  42022. }
  42023. }
  42024. /**
  42025. * Returns the GPU format for the given texture.
  42026. *
  42027. * @param {Texture} texture - The texture.
  42028. * @param {GPUDevice?} [device=null] - The GPU device which is used for feature detection.
  42029. * It is not necessary to apply the device for most formats.
  42030. * @return {String} The GPU format.
  42031. */
  42032. function getFormat( texture, device = null ) {
  42033. const format = texture.format;
  42034. const type = texture.type;
  42035. const colorSpace = texture.colorSpace;
  42036. let formatGPU;
  42037. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  42038. switch ( format ) {
  42039. case RGBA_S3TC_DXT1_Format:
  42040. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  42041. break;
  42042. case RGBA_S3TC_DXT3_Format:
  42043. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  42044. break;
  42045. case RGBA_S3TC_DXT5_Format:
  42046. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  42047. break;
  42048. case RGB_ETC2_Format:
  42049. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  42050. break;
  42051. case RGBA_ETC2_EAC_Format:
  42052. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  42053. break;
  42054. case RGBA_ASTC_4x4_Format:
  42055. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  42056. break;
  42057. case RGBA_ASTC_5x4_Format:
  42058. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  42059. break;
  42060. case RGBA_ASTC_5x5_Format:
  42061. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  42062. break;
  42063. case RGBA_ASTC_6x5_Format:
  42064. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  42065. break;
  42066. case RGBA_ASTC_6x6_Format:
  42067. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  42068. break;
  42069. case RGBA_ASTC_8x5_Format:
  42070. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  42071. break;
  42072. case RGBA_ASTC_8x6_Format:
  42073. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  42074. break;
  42075. case RGBA_ASTC_8x8_Format:
  42076. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  42077. break;
  42078. case RGBA_ASTC_10x5_Format:
  42079. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  42080. break;
  42081. case RGBA_ASTC_10x6_Format:
  42082. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  42083. break;
  42084. case RGBA_ASTC_10x8_Format:
  42085. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  42086. break;
  42087. case RGBA_ASTC_10x10_Format:
  42088. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  42089. break;
  42090. case RGBA_ASTC_12x10_Format:
  42091. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  42092. break;
  42093. case RGBA_ASTC_12x12_Format:
  42094. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  42095. break;
  42096. case RGBAFormat:
  42097. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  42098. break;
  42099. default:
  42100. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42101. }
  42102. } else {
  42103. switch ( format ) {
  42104. case RGBAFormat:
  42105. switch ( type ) {
  42106. case ByteType:
  42107. formatGPU = GPUTextureFormat.RGBA8Snorm;
  42108. break;
  42109. case ShortType:
  42110. formatGPU = GPUTextureFormat.RGBA16Sint;
  42111. break;
  42112. case UnsignedShortType:
  42113. formatGPU = GPUTextureFormat.RGBA16Uint;
  42114. break;
  42115. case UnsignedIntType:
  42116. formatGPU = GPUTextureFormat.RGBA32Uint;
  42117. break;
  42118. case IntType:
  42119. formatGPU = GPUTextureFormat.RGBA32Sint;
  42120. break;
  42121. case UnsignedByteType:
  42122. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  42123. break;
  42124. case HalfFloatType:
  42125. formatGPU = GPUTextureFormat.RGBA16Float;
  42126. break;
  42127. case FloatType:
  42128. formatGPU = GPUTextureFormat.RGBA32Float;
  42129. break;
  42130. default:
  42131. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  42132. }
  42133. break;
  42134. case RGBFormat:
  42135. switch ( type ) {
  42136. case UnsignedInt5999Type:
  42137. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  42138. break;
  42139. default:
  42140. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  42141. }
  42142. break;
  42143. case RedFormat:
  42144. switch ( type ) {
  42145. case ByteType:
  42146. formatGPU = GPUTextureFormat.R8Snorm;
  42147. break;
  42148. case ShortType:
  42149. formatGPU = GPUTextureFormat.R16Sint;
  42150. break;
  42151. case UnsignedShortType:
  42152. formatGPU = GPUTextureFormat.R16Uint;
  42153. break;
  42154. case UnsignedIntType:
  42155. formatGPU = GPUTextureFormat.R32Uint;
  42156. break;
  42157. case IntType:
  42158. formatGPU = GPUTextureFormat.R32Sint;
  42159. break;
  42160. case UnsignedByteType:
  42161. formatGPU = GPUTextureFormat.R8Unorm;
  42162. break;
  42163. case HalfFloatType:
  42164. formatGPU = GPUTextureFormat.R16Float;
  42165. break;
  42166. case FloatType:
  42167. formatGPU = GPUTextureFormat.R32Float;
  42168. break;
  42169. default:
  42170. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  42171. }
  42172. break;
  42173. case RGFormat:
  42174. switch ( type ) {
  42175. case ByteType:
  42176. formatGPU = GPUTextureFormat.RG8Snorm;
  42177. break;
  42178. case ShortType:
  42179. formatGPU = GPUTextureFormat.RG16Sint;
  42180. break;
  42181. case UnsignedShortType:
  42182. formatGPU = GPUTextureFormat.RG16Uint;
  42183. break;
  42184. case UnsignedIntType:
  42185. formatGPU = GPUTextureFormat.RG32Uint;
  42186. break;
  42187. case IntType:
  42188. formatGPU = GPUTextureFormat.RG32Sint;
  42189. break;
  42190. case UnsignedByteType:
  42191. formatGPU = GPUTextureFormat.RG8Unorm;
  42192. break;
  42193. case HalfFloatType:
  42194. formatGPU = GPUTextureFormat.RG16Float;
  42195. break;
  42196. case FloatType:
  42197. formatGPU = GPUTextureFormat.RG32Float;
  42198. break;
  42199. default:
  42200. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  42201. }
  42202. break;
  42203. case DepthFormat:
  42204. switch ( type ) {
  42205. case UnsignedShortType:
  42206. formatGPU = GPUTextureFormat.Depth16Unorm;
  42207. break;
  42208. case UnsignedIntType:
  42209. formatGPU = GPUTextureFormat.Depth24Plus;
  42210. break;
  42211. case FloatType:
  42212. formatGPU = GPUTextureFormat.Depth32Float;
  42213. break;
  42214. default:
  42215. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  42216. }
  42217. break;
  42218. case DepthStencilFormat:
  42219. switch ( type ) {
  42220. case UnsignedInt248Type:
  42221. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  42222. break;
  42223. case FloatType:
  42224. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  42225. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  42226. }
  42227. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  42228. break;
  42229. default:
  42230. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  42231. }
  42232. break;
  42233. case RedIntegerFormat:
  42234. switch ( type ) {
  42235. case IntType:
  42236. formatGPU = GPUTextureFormat.R32Sint;
  42237. break;
  42238. case UnsignedIntType:
  42239. formatGPU = GPUTextureFormat.R32Uint;
  42240. break;
  42241. default:
  42242. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  42243. }
  42244. break;
  42245. case RGIntegerFormat:
  42246. switch ( type ) {
  42247. case IntType:
  42248. formatGPU = GPUTextureFormat.RG32Sint;
  42249. break;
  42250. case UnsignedIntType:
  42251. formatGPU = GPUTextureFormat.RG32Uint;
  42252. break;
  42253. default:
  42254. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  42255. }
  42256. break;
  42257. case RGBAIntegerFormat:
  42258. switch ( type ) {
  42259. case IntType:
  42260. formatGPU = GPUTextureFormat.RGBA32Sint;
  42261. break;
  42262. case UnsignedIntType:
  42263. formatGPU = GPUTextureFormat.RGBA32Uint;
  42264. break;
  42265. default:
  42266. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  42267. }
  42268. break;
  42269. default:
  42270. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42271. }
  42272. }
  42273. return formatGPU;
  42274. }
  42275. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  42276. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  42277. const wgslTypeLib$1 = {
  42278. 'f32': 'float',
  42279. 'i32': 'int',
  42280. 'u32': 'uint',
  42281. 'bool': 'bool',
  42282. 'vec2<f32>': 'vec2',
  42283. 'vec2<i32>': 'ivec2',
  42284. 'vec2<u32>': 'uvec2',
  42285. 'vec2<bool>': 'bvec2',
  42286. 'vec2f': 'vec2',
  42287. 'vec2i': 'ivec2',
  42288. 'vec2u': 'uvec2',
  42289. 'vec2b': 'bvec2',
  42290. 'vec3<f32>': 'vec3',
  42291. 'vec3<i32>': 'ivec3',
  42292. 'vec3<u32>': 'uvec3',
  42293. 'vec3<bool>': 'bvec3',
  42294. 'vec3f': 'vec3',
  42295. 'vec3i': 'ivec3',
  42296. 'vec3u': 'uvec3',
  42297. 'vec3b': 'bvec3',
  42298. 'vec4<f32>': 'vec4',
  42299. 'vec4<i32>': 'ivec4',
  42300. 'vec4<u32>': 'uvec4',
  42301. 'vec4<bool>': 'bvec4',
  42302. 'vec4f': 'vec4',
  42303. 'vec4i': 'ivec4',
  42304. 'vec4u': 'uvec4',
  42305. 'vec4b': 'bvec4',
  42306. 'mat2x2<f32>': 'mat2',
  42307. 'mat2x2f': 'mat2',
  42308. 'mat3x3<f32>': 'mat3',
  42309. 'mat3x3f': 'mat3',
  42310. 'mat4x4<f32>': 'mat4',
  42311. 'mat4x4f': 'mat4',
  42312. 'sampler': 'sampler',
  42313. 'texture_1d': 'texture',
  42314. 'texture_2d': 'texture',
  42315. 'texture_2d_array': 'texture',
  42316. 'texture_multisampled_2d': 'cubeTexture',
  42317. 'texture_depth_2d': 'depthTexture',
  42318. 'texture_depth_multisampled_2d': 'depthTexture',
  42319. 'texture_3d': 'texture3D',
  42320. 'texture_cube': 'cubeTexture',
  42321. 'texture_cube_array': 'cubeTexture',
  42322. 'texture_storage_1d': 'storageTexture',
  42323. 'texture_storage_2d': 'storageTexture',
  42324. 'texture_storage_2d_array': 'storageTexture',
  42325. 'texture_storage_3d': 'storageTexture'
  42326. };
  42327. const parse = ( source ) => {
  42328. source = source.trim();
  42329. const declaration = source.match( declarationRegexp );
  42330. if ( declaration !== null && declaration.length === 4 ) {
  42331. const inputsCode = declaration[ 2 ];
  42332. const propsMatches = [];
  42333. let match = null;
  42334. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  42335. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  42336. }
  42337. // Process matches to correctly pair names and types
  42338. const inputs = [];
  42339. for ( let i = 0; i < propsMatches.length; i ++ ) {
  42340. const { name, type } = propsMatches[ i ];
  42341. let resolvedType = type;
  42342. if ( resolvedType.startsWith( 'ptr' ) ) {
  42343. resolvedType = 'pointer';
  42344. } else {
  42345. if ( resolvedType.startsWith( 'texture' ) ) {
  42346. resolvedType = type.split( '<' )[ 0 ];
  42347. }
  42348. resolvedType = wgslTypeLib$1[ resolvedType ];
  42349. }
  42350. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  42351. }
  42352. const blockCode = source.substring( declaration[ 0 ].length );
  42353. const outputType = declaration[ 3 ] || 'void';
  42354. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  42355. const type = wgslTypeLib$1[ outputType ] || outputType;
  42356. return {
  42357. type,
  42358. inputs,
  42359. name,
  42360. inputsCode,
  42361. blockCode,
  42362. outputType
  42363. };
  42364. } else {
  42365. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  42366. }
  42367. };
  42368. /**
  42369. * This class represents a WSL node function.
  42370. *
  42371. * @augments NodeFunction
  42372. */
  42373. class WGSLNodeFunction extends NodeFunction {
  42374. /**
  42375. * Constructs a new WGSL node function.
  42376. *
  42377. * @param {String} source - The WGSL source.
  42378. */
  42379. constructor( source ) {
  42380. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  42381. super( type, inputs, name );
  42382. this.inputsCode = inputsCode;
  42383. this.blockCode = blockCode;
  42384. this.outputType = outputType;
  42385. }
  42386. /**
  42387. * This method returns the WGSL code of the node function.
  42388. *
  42389. * @param {String} [name=this.name] - The function's name.
  42390. * @return {String} The shader code.
  42391. */
  42392. getCode( name = this.name ) {
  42393. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  42394. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  42395. }
  42396. }
  42397. /**
  42398. * A WGSL node parser.
  42399. *
  42400. * @augments NodeParser
  42401. */
  42402. class WGSLNodeParser extends NodeParser {
  42403. /**
  42404. * The method parses the given WGSL code an returns a node function.
  42405. *
  42406. * @param {String} source - The WGSL code.
  42407. * @return {WGSLNodeFunction} A node function.
  42408. */
  42409. parseFunction( source ) {
  42410. return new WGSLNodeFunction( source );
  42411. }
  42412. }
  42413. // GPUShaderStage is not defined in browsers not supporting WebGPU
  42414. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  42415. const accessNames = {
  42416. [ NodeAccess.READ_ONLY ]: 'read',
  42417. [ NodeAccess.WRITE_ONLY ]: 'write',
  42418. [ NodeAccess.READ_WRITE ]: 'read_write'
  42419. };
  42420. const wrapNames = {
  42421. [ RepeatWrapping ]: 'repeat',
  42422. [ ClampToEdgeWrapping ]: 'clamp',
  42423. [ MirroredRepeatWrapping ]: 'mirror'
  42424. };
  42425. const gpuShaderStageLib = {
  42426. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  42427. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  42428. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  42429. };
  42430. const supports = {
  42431. instance: true,
  42432. swizzleAssign: false,
  42433. storageBuffer: true
  42434. };
  42435. const wgslFnOpLib = {
  42436. '^^': 'tsl_xor'
  42437. };
  42438. const wgslTypeLib = {
  42439. float: 'f32',
  42440. int: 'i32',
  42441. uint: 'u32',
  42442. bool: 'bool',
  42443. color: 'vec3<f32>',
  42444. vec2: 'vec2<f32>',
  42445. ivec2: 'vec2<i32>',
  42446. uvec2: 'vec2<u32>',
  42447. bvec2: 'vec2<bool>',
  42448. vec3: 'vec3<f32>',
  42449. ivec3: 'vec3<i32>',
  42450. uvec3: 'vec3<u32>',
  42451. bvec3: 'vec3<bool>',
  42452. vec4: 'vec4<f32>',
  42453. ivec4: 'vec4<i32>',
  42454. uvec4: 'vec4<u32>',
  42455. bvec4: 'vec4<bool>',
  42456. mat2: 'mat2x2<f32>',
  42457. mat3: 'mat3x3<f32>',
  42458. mat4: 'mat4x4<f32>'
  42459. };
  42460. const wgslCodeCache = {};
  42461. const wgslPolyfill = {
  42462. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  42463. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  42464. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  42465. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  42466. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  42467. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  42468. 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 ); }' ),
  42469. 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 ); }' ),
  42470. 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 ); }' ),
  42471. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  42472. 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 ); }' ),
  42473. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  42474. biquadraticTexture: new CodeNode( /* wgsl */`
  42475. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  42476. let res = vec2f( iRes );
  42477. let uvScaled = coord * res;
  42478. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  42479. // https://www.shadertoy.com/view/WtyXRy
  42480. let uv = uvWrapping - 0.5;
  42481. let iuv = floor( uv );
  42482. let f = fract( uv );
  42483. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  42484. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  42485. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  42486. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  42487. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  42488. }
  42489. ` )
  42490. };
  42491. const wgslMethods = {
  42492. dFdx: 'dpdx',
  42493. dFdy: '- dpdy',
  42494. mod_float: 'tsl_mod_float',
  42495. mod_vec2: 'tsl_mod_vec2',
  42496. mod_vec3: 'tsl_mod_vec3',
  42497. mod_vec4: 'tsl_mod_vec4',
  42498. equals_bool: 'tsl_equals_bool',
  42499. equals_bvec2: 'tsl_equals_bvec2',
  42500. equals_bvec3: 'tsl_equals_bvec3',
  42501. equals_bvec4: 'tsl_equals_bvec4',
  42502. inversesqrt: 'inverseSqrt',
  42503. bitcast: 'bitcast<f32>'
  42504. };
  42505. // WebGPU issue: does not support pow() with negative base on Windows
  42506. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  42507. 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 ); }' );
  42508. 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 ] );
  42509. 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 ] );
  42510. 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 ] );
  42511. wgslMethods.pow_float = 'tsl_pow_float';
  42512. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  42513. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  42514. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  42515. }
  42516. //
  42517. let diagnostics = '';
  42518. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  42519. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  42520. }
  42521. /**
  42522. * A node builder targeting WGSL.
  42523. *
  42524. * This module generates WGSL shader code from node materials and also
  42525. * generates the respective bindings and vertex buffer definitions. These
  42526. * data are later used by the renderer to create render and compute pipelines
  42527. * for render objects.
  42528. *
  42529. * @augments NodeBuilder
  42530. */
  42531. class WGSLNodeBuilder extends NodeBuilder {
  42532. /**
  42533. * Constructs a new WGSL node builder renderer.
  42534. *
  42535. * @param {Object3D} object - The 3D object.
  42536. * @param {Renderer} renderer - The renderer.
  42537. */
  42538. constructor( object, renderer ) {
  42539. super( object, renderer, new WGSLNodeParser() );
  42540. /**
  42541. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  42542. * another dictionary which manages UBOs per group ('render','frame','object').
  42543. *
  42544. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  42545. */
  42546. this.uniformGroups = {};
  42547. /**
  42548. * A dictionary that holds for each shader stage a Map of builtins.
  42549. *
  42550. * @type {Object<String,Map<String,Object>>}
  42551. */
  42552. this.builtins = {};
  42553. /**
  42554. * A dictionary that holds for each shader stage a Set of directives.
  42555. *
  42556. * @type {Object<String,Set<String>>}
  42557. */
  42558. this.directives = {};
  42559. /**
  42560. * A map for managing scope arrays. Only relevant for when using
  42561. * {@link module:WorkgroupInfoNode} in context of compute shaders.
  42562. *
  42563. * @type {Map<String,Object>}
  42564. */
  42565. this.scopedArrays = new Map();
  42566. }
  42567. /**
  42568. * Checks if the given texture requires a manual conversion to the working color space.
  42569. *
  42570. * @param {Texture} texture - The texture to check.
  42571. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  42572. */
  42573. needsToWorkingColorSpace( texture ) {
  42574. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42575. }
  42576. /**
  42577. * Generates the WGSL snippet for sampled textures.
  42578. *
  42579. * @private
  42580. * @param {Texture} texture - The texture.
  42581. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42582. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42583. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42584. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42585. * @return {String} The WGSL snippet.
  42586. */
  42587. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42588. if ( shaderStage === 'fragment' ) {
  42589. if ( depthSnippet ) {
  42590. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  42591. } else {
  42592. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  42593. }
  42594. } else if ( this.isFilteredTexture( texture ) ) {
  42595. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  42596. } else {
  42597. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  42598. }
  42599. }
  42600. /**
  42601. * Generates the WGSL snippet when sampling video textures.
  42602. *
  42603. * @private
  42604. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  42605. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42606. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42607. * @return {String} The WGSL snippet.
  42608. */
  42609. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  42610. if ( shaderStage === 'fragment' ) {
  42611. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  42612. } else {
  42613. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  42614. }
  42615. }
  42616. /**
  42617. * Generates the WGSL snippet when sampling textures with explicit mip level.
  42618. *
  42619. * @private
  42620. * @param {Texture} texture - The texture.
  42621. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42622. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42623. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42624. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42625. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42626. * @return {String} The WGSL snippet.
  42627. */
  42628. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42629. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  42630. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  42631. } else if ( this.isFilteredTexture( texture ) ) {
  42632. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  42633. } else {
  42634. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  42635. }
  42636. }
  42637. /**
  42638. * Generates a wrap function used in context of textures.
  42639. *
  42640. * @param {Texture} texture - The texture to generate the function for.
  42641. * @return {String} The name of the generated function.
  42642. */
  42643. generateWrapFunction( texture ) {
  42644. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  42645. let nodeCode = wgslCodeCache[ functionName ];
  42646. if ( nodeCode === undefined ) {
  42647. const includes = [];
  42648. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  42649. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  42650. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  42651. const addWrapSnippet = ( wrap, axis ) => {
  42652. if ( wrap === RepeatWrapping ) {
  42653. includes.push( wgslPolyfill.repeatWrapping_float );
  42654. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  42655. } else if ( wrap === ClampToEdgeWrapping ) {
  42656. includes.push( wgslPolyfill.clampWrapping_float );
  42657. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  42658. } else if ( wrap === MirroredRepeatWrapping ) {
  42659. includes.push( wgslPolyfill.mirrorWrapping_float );
  42660. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  42661. } else {
  42662. code += `\t\tcoord.${ axis }`;
  42663. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  42664. }
  42665. };
  42666. addWrapSnippet( texture.wrapS, 'x' );
  42667. code += ',\n';
  42668. addWrapSnippet( texture.wrapT, 'y' );
  42669. if ( texture.isData3DTexture ) {
  42670. code += ',\n';
  42671. addWrapSnippet( texture.wrapR, 'z' );
  42672. }
  42673. code += '\n\t);\n\n}\n';
  42674. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  42675. }
  42676. nodeCode.build( this );
  42677. return functionName;
  42678. }
  42679. /**
  42680. * Generates a WGSL variable that holds the texture dimension of the given texture.
  42681. * It also returns information about the the number of layers (elements) of an arrayed
  42682. * texture as well as the cube face count of cube textures.
  42683. *
  42684. * @param {Texture} texture - The texture to generate the function for.
  42685. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  42686. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42687. * @return {String} The name of the dimension variable.
  42688. */
  42689. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  42690. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  42691. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  42692. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  42693. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  42694. let textureDimensionsParams;
  42695. let dimensionType;
  42696. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  42697. const isMultisampled = primarySamples > 1;
  42698. if ( texture.isData3DTexture ) {
  42699. dimensionType = 'vec3<u32>';
  42700. } else {
  42701. // Regular 2D textures, depth textures, etc.
  42702. dimensionType = 'vec2<u32>';
  42703. }
  42704. // Build parameters string based on texture type and multisampling
  42705. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  42706. textureDimensionsParams = textureProperty;
  42707. } else {
  42708. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  42709. }
  42710. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  42711. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  42712. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  42713. textureData.arrayLayerCount = new VarNode(
  42714. new ExpressionNode(
  42715. `textureNumLayers(${textureProperty})`,
  42716. 'u32'
  42717. )
  42718. );
  42719. }
  42720. // For cube textures, we know it's always 6 faces
  42721. if ( texture.isTextureCube ) {
  42722. textureData.cubeFaceCount = new VarNode(
  42723. new ExpressionNode( '6u', 'u32' )
  42724. );
  42725. }
  42726. }
  42727. return textureDimensionNode.build( this );
  42728. }
  42729. /**
  42730. * Generates the WGSL snippet for a manual filtered texture.
  42731. *
  42732. * @param {Texture} texture - The texture.
  42733. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42734. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42735. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42736. * @return {String} The WGSL snippet.
  42737. */
  42738. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  42739. this._include( 'biquadraticTexture' );
  42740. const wrapFunction = this.generateWrapFunction( texture );
  42741. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  42742. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  42743. }
  42744. /**
  42745. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  42746. * Since it's a lookup, no sampling or filtering is applied.
  42747. *
  42748. * @param {Texture} texture - The texture.
  42749. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42750. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42751. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42752. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42753. * @return {String} The WGSL snippet.
  42754. */
  42755. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  42756. const wrapFunction = this.generateWrapFunction( texture );
  42757. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  42758. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  42759. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  42760. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  42761. }
  42762. /**
  42763. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  42764. *
  42765. * @param {Texture} texture - The texture.
  42766. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42767. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42768. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42769. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42770. * @return {String} The WGSL snippet.
  42771. */
  42772. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  42773. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  42774. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  42775. } else if ( depthSnippet ) {
  42776. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  42777. } else {
  42778. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  42779. }
  42780. }
  42781. /**
  42782. * Generates the WGSL snippet that writes a single texel to a texture.
  42783. *
  42784. * @param {Texture} texture - The texture.
  42785. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42786. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42787. * @param {String} valueSnippet - A WGSL snippet that represent the new texel value.
  42788. * @return {String} The WGSL snippet.
  42789. */
  42790. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  42791. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  42792. }
  42793. /**
  42794. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  42795. *
  42796. * @param {Texture} texture - The texture.
  42797. * @return {Boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  42798. */
  42799. isSampleCompare( texture ) {
  42800. return texture.isDepthTexture === true && texture.compareFunction !== null;
  42801. }
  42802. /**
  42803. * Returns `true` if the given texture is unfilterable.
  42804. *
  42805. * @param {Texture} texture - The texture.
  42806. * @return {Boolean} Whether the given texture is unfilterable or not.
  42807. */
  42808. isUnfilterable( texture ) {
  42809. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  42810. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  42811. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  42812. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  42813. }
  42814. /**
  42815. * Generates the WGSL snippet for sampling/loading the given texture.
  42816. *
  42817. * @param {Texture} texture - The texture.
  42818. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42819. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42820. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42821. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42822. * @return {String} The WGSL snippet.
  42823. */
  42824. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42825. let snippet = null;
  42826. if ( texture.isVideoTexture === true ) {
  42827. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42828. } else if ( this.isUnfilterable( texture ) ) {
  42829. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  42830. } else {
  42831. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  42832. }
  42833. return snippet;
  42834. }
  42835. /**
  42836. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  42837. *
  42838. * @param {Texture} texture - The texture.
  42839. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42840. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42841. * @param {Array<String>} gradSnippet - An array holding both gradient WGSL snippets.
  42842. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42843. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42844. * @return {String} The WGSL snippet.
  42845. */
  42846. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42847. if ( shaderStage === 'fragment' ) {
  42848. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  42849. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  42850. } else {
  42851. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  42852. }
  42853. }
  42854. /**
  42855. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  42856. * against a reference value.
  42857. *
  42858. * @param {Texture} texture - The texture.
  42859. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42860. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42861. * @param {String} compareSnippet - A WGSL snippet that represents the reference value.
  42862. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42863. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42864. * @return {String} The WGSL snippet.
  42865. */
  42866. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42867. if ( shaderStage === 'fragment' ) {
  42868. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  42869. } else {
  42870. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  42871. }
  42872. }
  42873. /**
  42874. * Generates the WGSL snippet when sampling textures with explicit mip level.
  42875. *
  42876. * @param {Texture} texture - The texture.
  42877. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42878. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42879. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42880. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42881. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42882. * @return {String} The WGSL snippet.
  42883. */
  42884. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42885. let snippet = null;
  42886. if ( texture.isVideoTexture === true ) {
  42887. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42888. } else {
  42889. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  42890. }
  42891. return snippet;
  42892. }
  42893. /**
  42894. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  42895. *
  42896. * @param {Texture} texture - The texture.
  42897. * @param {String} textureProperty - The name of the texture uniform in the shader.
  42898. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  42899. * @param {String} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  42900. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  42901. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42902. * @return {String} The WGSL snippet.
  42903. */
  42904. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42905. if ( shaderStage === 'fragment' ) {
  42906. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  42907. } else {
  42908. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  42909. }
  42910. }
  42911. /**
  42912. * Returns a WGSL snippet that represents the property name of the given node.
  42913. *
  42914. * @param {Node} node - The node.
  42915. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42916. * @return {String} The property name.
  42917. */
  42918. getPropertyName( node, shaderStage = this.shaderStage ) {
  42919. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  42920. if ( shaderStage === 'vertex' ) {
  42921. return `varyings.${ node.name }`;
  42922. }
  42923. } else if ( node.isNodeUniform === true ) {
  42924. const name = node.name;
  42925. const type = node.type;
  42926. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42927. return name;
  42928. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  42929. return `NodeBuffer_${ node.id }.${name}`;
  42930. } else {
  42931. return node.groupNode.name + '.' + name;
  42932. }
  42933. }
  42934. return super.getPropertyName( node );
  42935. }
  42936. /**
  42937. * Returns the output struct name.
  42938. *
  42939. * @return {String} The name of the output struct.
  42940. */
  42941. getOutputStructName() {
  42942. return 'output';
  42943. }
  42944. /**
  42945. * Returns uniforms group count for the given shader stage.
  42946. *
  42947. * @private
  42948. * @param {String} shaderStage - The shader stage.
  42949. * @return {Number} The uniforms group count for the given shader stage.
  42950. */
  42951. _getUniformGroupCount( shaderStage ) {
  42952. return Object.keys( this.uniforms[ shaderStage ] ).length;
  42953. }
  42954. /**
  42955. * Returns the native shader operator name for a given generic name.
  42956. *
  42957. * @param {String} op - The operator name to resolve.
  42958. * @return {String} The resolved operator name.
  42959. */
  42960. getFunctionOperator( op ) {
  42961. const fnOp = wgslFnOpLib[ op ];
  42962. if ( fnOp !== undefined ) {
  42963. this._include( fnOp );
  42964. return fnOp;
  42965. }
  42966. return null;
  42967. }
  42968. /**
  42969. * Returns the node access for the given node and shader stage.
  42970. *
  42971. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  42972. * @param {String} shaderStage - The shader stage.
  42973. * @return {String} The node access.
  42974. */
  42975. getNodeAccess( node, shaderStage ) {
  42976. if ( shaderStage !== 'compute' )
  42977. return NodeAccess.READ_ONLY;
  42978. return node.access;
  42979. }
  42980. /**
  42981. * Returns A WGSL snippet representing the storage access.
  42982. *
  42983. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  42984. * @param {String} shaderStage - The shader stage.
  42985. * @return {String} The WGSL snippet representing the storage access.
  42986. */
  42987. getStorageAccess( node, shaderStage ) {
  42988. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  42989. }
  42990. /**
  42991. * This method is one of the more important ones since it's responsible
  42992. * for generating a matching binding instance for the given uniform node.
  42993. *
  42994. * These bindings are later used in the renderer to create bind groups
  42995. * and layouts.
  42996. *
  42997. * @param {UniformNode} node - The uniform node.
  42998. * @param {String} type - The node data type.
  42999. * @param {String} shaderStage - The shader stage.
  43000. * @param {String?} [name=null] - An optional uniform name.
  43001. * @return {NodeUniform} The node uniform object.
  43002. */
  43003. getUniformFromNode( node, type, shaderStage, name = null ) {
  43004. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  43005. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  43006. if ( nodeData.uniformGPU === undefined ) {
  43007. let uniformGPU;
  43008. const group = node.groupNode;
  43009. const groupName = group.name;
  43010. const bindings = this.getBindGroupArray( groupName, shaderStage );
  43011. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43012. let texture = null;
  43013. const access = this.getNodeAccess( node, shaderStage );
  43014. if ( type === 'texture' || type === 'storageTexture' ) {
  43015. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  43016. } else if ( type === 'cubeTexture' ) {
  43017. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  43018. } else if ( type === 'texture3D' ) {
  43019. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  43020. }
  43021. texture.store = node.isStorageTextureNode === true;
  43022. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43023. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  43024. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  43025. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43026. bindings.push( sampler, texture );
  43027. uniformGPU = [ sampler, texture ];
  43028. } else {
  43029. bindings.push( texture );
  43030. uniformGPU = [ texture ];
  43031. }
  43032. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  43033. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  43034. const buffer = new bufferClass( node, group );
  43035. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43036. bindings.push( buffer );
  43037. uniformGPU = buffer;
  43038. } else {
  43039. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  43040. let uniformsGroup = uniformsStage[ groupName ];
  43041. if ( uniformsGroup === undefined ) {
  43042. uniformsGroup = new NodeUniformsGroup( groupName, group );
  43043. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43044. uniformsStage[ groupName ] = uniformsGroup;
  43045. bindings.push( uniformsGroup );
  43046. }
  43047. uniformGPU = this.getNodeUniform( uniformNode, type );
  43048. uniformsGroup.addUniform( uniformGPU );
  43049. }
  43050. nodeData.uniformGPU = uniformGPU;
  43051. }
  43052. return uniformNode;
  43053. }
  43054. /**
  43055. * This method should be used whenever builtins are required in nodes.
  43056. * The internal builtins data structure will make sure builtins are
  43057. * defined in the WGSL source.
  43058. *
  43059. * @param {String} name - The builtin name.
  43060. * @param {String} property - The property name.
  43061. * @param {String} type - The node data type.
  43062. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43063. * @return {String} The property name.
  43064. */
  43065. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  43066. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  43067. if ( map.has( name ) === false ) {
  43068. map.set( name, {
  43069. name,
  43070. property,
  43071. type
  43072. } );
  43073. }
  43074. return property;
  43075. }
  43076. /**
  43077. * Returns `true` if the given builtin is defined in the given shader stage.
  43078. *
  43079. * @param {String} name - The builtin name.
  43080. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43081. * @return {String} Whether the given builtin is defined in the given shader stage or not.
  43082. */
  43083. hasBuiltin( name, shaderStage = this.shaderStage ) {
  43084. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  43085. }
  43086. /**
  43087. * Returns the vertex index builtin.
  43088. *
  43089. * @return {String} The vertex index.
  43090. */
  43091. getVertexIndex() {
  43092. if ( this.shaderStage === 'vertex' ) {
  43093. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  43094. }
  43095. return 'vertexIndex';
  43096. }
  43097. /**
  43098. * Builds the given shader node.
  43099. *
  43100. * @param {ShaderNodeInternal} shaderNode - The shader node.
  43101. * @return {String} The WGSL function code.
  43102. */
  43103. buildFunctionCode( shaderNode ) {
  43104. const layout = shaderNode.layout;
  43105. const flowData = this.flowShaderNode( shaderNode );
  43106. const parameters = [];
  43107. for ( const input of layout.inputs ) {
  43108. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  43109. }
  43110. //
  43111. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  43112. ${ flowData.vars }
  43113. ${ flowData.code }
  43114. `;
  43115. if ( flowData.result ) {
  43116. code += `\treturn ${ flowData.result };\n`;
  43117. }
  43118. code += '\n}\n';
  43119. //
  43120. return code;
  43121. }
  43122. /**
  43123. * Returns the instance index builtin.
  43124. *
  43125. * @return {String} The instance index.
  43126. */
  43127. getInstanceIndex() {
  43128. if ( this.shaderStage === 'vertex' ) {
  43129. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  43130. }
  43131. return 'instanceIndex';
  43132. }
  43133. /**
  43134. * Returns the invocation local index builtin.
  43135. *
  43136. * @return {String} The invocation local index.
  43137. */
  43138. getInvocationLocalIndex() {
  43139. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  43140. }
  43141. /**
  43142. * Returns the subgroup size builtin.
  43143. *
  43144. * @return {String} The subgroup size.
  43145. */
  43146. getSubgroupSize() {
  43147. this.enableSubGroups();
  43148. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43149. }
  43150. /**
  43151. * Returns the invocation subgroup index builtin.
  43152. *
  43153. * @return {String} The invocation subgroup index.
  43154. */
  43155. getInvocationSubgroupIndex() {
  43156. this.enableSubGroups();
  43157. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  43158. }
  43159. /**
  43160. * Returns the subgroup index builtin.
  43161. *
  43162. * @return {String} The subgroup index.
  43163. */
  43164. getSubgroupIndex() {
  43165. this.enableSubGroups();
  43166. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  43167. }
  43168. /**
  43169. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  43170. *
  43171. * @return {null} Null.
  43172. */
  43173. getDrawIndex() {
  43174. return null;
  43175. }
  43176. /**
  43177. * Returns the front facing builtin.
  43178. *
  43179. * @return {String} The front facing builtin.
  43180. */
  43181. getFrontFacing() {
  43182. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  43183. }
  43184. /**
  43185. * Returns the frag coord builtin.
  43186. *
  43187. * @return {String} The frag coord builtin.
  43188. */
  43189. getFragCoord() {
  43190. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  43191. }
  43192. /**
  43193. * Returns the frag depth builtin.
  43194. *
  43195. * @return {String} The frag depth builtin.
  43196. */
  43197. getFragDepth() {
  43198. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  43199. }
  43200. /**
  43201. * Returns the clip distances builtin.
  43202. *
  43203. * @return {String} The clip distances builtin.
  43204. */
  43205. getClipDistance() {
  43206. return 'varyings.hw_clip_distances';
  43207. }
  43208. /**
  43209. * Whether to flip texture data along its vertical axis or not.
  43210. *
  43211. * @return {Boolean} Returns always `false` in context of WGSL.
  43212. */
  43213. isFlipY() {
  43214. return false;
  43215. }
  43216. /**
  43217. * Enables the given directive for the given shader stage.
  43218. *
  43219. * @param {String} name - The directive name.
  43220. * @param {String} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  43221. */
  43222. enableDirective( name, shaderStage = this.shaderStage ) {
  43223. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  43224. stage.add( name );
  43225. }
  43226. /**
  43227. * Returns the directives of the given shader stage as a WGSL string.
  43228. *
  43229. * @param {String} shaderStage - The shader stage.
  43230. * @return {String} A WGSL snippet that enables the directives of the given stage.
  43231. */
  43232. getDirectives( shaderStage ) {
  43233. const snippets = [];
  43234. const directives = this.directives[ shaderStage ];
  43235. if ( directives !== undefined ) {
  43236. for ( const directive of directives ) {
  43237. snippets.push( `enable ${directive};` );
  43238. }
  43239. }
  43240. return snippets.join( '\n' );
  43241. }
  43242. /**
  43243. * Enables the 'subgroups' directive.
  43244. */
  43245. enableSubGroups() {
  43246. this.enableDirective( 'subgroups' );
  43247. }
  43248. /**
  43249. * Enables the 'subgroups-f16' directive.
  43250. */
  43251. enableSubgroupsF16() {
  43252. this.enableDirective( 'subgroups-f16' );
  43253. }
  43254. /**
  43255. * Enables the 'clip_distances' directive.
  43256. */
  43257. enableClipDistances() {
  43258. this.enableDirective( 'clip_distances' );
  43259. }
  43260. /**
  43261. * Enables the 'f16' directive.
  43262. */
  43263. enableShaderF16() {
  43264. this.enableDirective( 'f16' );
  43265. }
  43266. /**
  43267. * Enables the 'dual_source_blending' directive.
  43268. */
  43269. enableDualSourceBlending() {
  43270. this.enableDirective( 'dual_source_blending' );
  43271. }
  43272. /**
  43273. * Enables hardware clipping.
  43274. *
  43275. * @param {String} planeCount - The clipping plane count.
  43276. */
  43277. enableHardwareClipping( planeCount ) {
  43278. this.enableClipDistances();
  43279. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  43280. }
  43281. /**
  43282. * Returns the builtins of the given shader stage as a WGSL string.
  43283. *
  43284. * @param {String} shaderStage - The shader stage.
  43285. * @return {String} A WGSL snippet that represents the builtins of the given stage.
  43286. */
  43287. getBuiltins( shaderStage ) {
  43288. const snippets = [];
  43289. const builtins = this.builtins[ shaderStage ];
  43290. if ( builtins !== undefined ) {
  43291. for ( const { name, property, type } of builtins.values() ) {
  43292. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  43293. }
  43294. }
  43295. return snippets.join( ',\n\t' );
  43296. }
  43297. /**
  43298. * This method should be used when a new scoped buffer is used in context of
  43299. * compute shaders. It adds the array to the internal data structure which is
  43300. * later used to generate the respective WGSL.
  43301. *
  43302. * @param {String} name - The array name.
  43303. * @param {String} scope - The scope.
  43304. * @param {String} bufferType - The buffer type.
  43305. * @param {String} bufferCount - The buffer count.
  43306. * @return {String} The array name.
  43307. */
  43308. getScopedArray( name, scope, bufferType, bufferCount ) {
  43309. if ( this.scopedArrays.has( name ) === false ) {
  43310. this.scopedArrays.set( name, {
  43311. name,
  43312. scope,
  43313. bufferType,
  43314. bufferCount
  43315. } );
  43316. }
  43317. return name;
  43318. }
  43319. /**
  43320. * Returns the scoped arrays of the given shader stage as a WGSL string.
  43321. *
  43322. * @param {String} shaderStage - The shader stage.
  43323. * @return {String|undefined} The WGSL snippet that defines the scoped arrays.
  43324. * Returns `undefined` when used in the vertex or fragment stage.
  43325. */
  43326. getScopedArrays( shaderStage ) {
  43327. if ( shaderStage !== 'compute' ) {
  43328. return;
  43329. }
  43330. const snippets = [];
  43331. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  43332. const type = this.getType( bufferType );
  43333. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  43334. }
  43335. return snippets.join( '\n' );
  43336. }
  43337. /**
  43338. * Returns the shader attributes of the given shader stage as a WGSL string.
  43339. *
  43340. * @param {String} shaderStage - The shader stage.
  43341. * @return {String} The WGSL snippet that defines the shader attributes.
  43342. */
  43343. getAttributes( shaderStage ) {
  43344. const snippets = [];
  43345. if ( shaderStage === 'compute' ) {
  43346. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  43347. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  43348. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  43349. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  43350. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  43351. this.enableDirective( 'subgroups', shaderStage );
  43352. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43353. }
  43354. }
  43355. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43356. const builtins = this.getBuiltins( 'attribute' );
  43357. if ( builtins ) snippets.push( builtins );
  43358. const attributes = this.getAttributesArray();
  43359. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  43360. const attribute = attributes[ index ];
  43361. const name = attribute.name;
  43362. const type = this.getType( attribute.type );
  43363. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  43364. }
  43365. }
  43366. return snippets.join( ',\n\t' );
  43367. }
  43368. /**
  43369. * Returns the members of the given struct type node as a WGSL string.
  43370. *
  43371. * @param {StructTypeNode} struct - The struct type node.
  43372. * @return {String} The WGSL snippet that defines the struct members.
  43373. */
  43374. getStructMembers( struct ) {
  43375. const snippets = [];
  43376. const members = struct.getMemberTypes();
  43377. for ( let i = 0; i < members.length; i ++ ) {
  43378. const member = members[ i ];
  43379. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  43380. }
  43381. const builtins = this.getBuiltins( 'output' );
  43382. if ( builtins ) snippets.push( '\t' + builtins );
  43383. return snippets.join( ',\n' );
  43384. }
  43385. /**
  43386. * Returns the structs of the given shader stage as a WGSL string.
  43387. *
  43388. * @param {String} shaderStage - The shader stage.
  43389. * @return {String} The WGSL snippet that defines the structs.
  43390. */
  43391. getStructs( shaderStage ) {
  43392. const snippets = [];
  43393. const structs = this.structs[ shaderStage ];
  43394. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  43395. const struct = structs[ index ];
  43396. const name = struct.name;
  43397. let snippet = `\struct ${ name } {\n`;
  43398. snippet += this.getStructMembers( struct );
  43399. snippet += '\n}';
  43400. snippets.push( snippet );
  43401. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  43402. }
  43403. return snippets.join( '\n\n' );
  43404. }
  43405. /**
  43406. * Returns a WGSL string representing a variable.
  43407. *
  43408. * @param {String} type - The variable's type.
  43409. * @param {String} name - The variable's name.
  43410. * @return {String} The WGSL snippet that defines a variable.
  43411. */
  43412. getVar( type, name ) {
  43413. return `var ${ name } : ${ this.getType( type ) }`;
  43414. }
  43415. /**
  43416. * Returns the variables of the given shader stage as a WGSL string.
  43417. *
  43418. * @param {String} shaderStage - The shader stage.
  43419. * @return {String} The WGSL snippet that defines the variables.
  43420. */
  43421. getVars( shaderStage ) {
  43422. const snippets = [];
  43423. const vars = this.vars[ shaderStage ];
  43424. if ( vars !== undefined ) {
  43425. for ( const variable of vars ) {
  43426. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  43427. }
  43428. }
  43429. return `\n${ snippets.join( '\n' ) }\n`;
  43430. }
  43431. /**
  43432. * Returns the varyings of the given shader stage as a WGSL string.
  43433. *
  43434. * @param {String} shaderStage - The shader stage.
  43435. * @return {String} The WGSL snippet that defines the varyings.
  43436. */
  43437. getVaryings( shaderStage ) {
  43438. const snippets = [];
  43439. if ( shaderStage === 'vertex' ) {
  43440. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  43441. }
  43442. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  43443. const varyings = this.varyings;
  43444. const vars = this.vars[ shaderStage ];
  43445. for ( let index = 0; index < varyings.length; index ++ ) {
  43446. const varying = varyings[ index ];
  43447. if ( varying.needsInterpolation ) {
  43448. let attributesSnippet = `@location( ${index} )`;
  43449. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  43450. attributesSnippet += ' @interpolate( flat )';
  43451. }
  43452. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  43453. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  43454. vars.push( varying );
  43455. }
  43456. }
  43457. }
  43458. const builtins = this.getBuiltins( shaderStage );
  43459. if ( builtins ) snippets.push( builtins );
  43460. const code = snippets.join( ',\n\t' );
  43461. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  43462. }
  43463. /**
  43464. * Returns the uniforms of the given shader stage as a WGSL string.
  43465. *
  43466. * @param {String} shaderStage - The shader stage.
  43467. * @return {String} The WGSL snippet that defines the uniforms.
  43468. */
  43469. getUniforms( shaderStage ) {
  43470. const uniforms = this.uniforms[ shaderStage ];
  43471. const bindingSnippets = [];
  43472. const bufferSnippets = [];
  43473. const structSnippets = [];
  43474. const uniformGroups = {};
  43475. for ( const uniform of uniforms ) {
  43476. const groupName = uniform.groupNode.name;
  43477. const uniformIndexes = this.bindingsIndexes[ groupName ];
  43478. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  43479. const texture = uniform.node.value;
  43480. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  43481. if ( this.isSampleCompare( texture ) ) {
  43482. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  43483. } else {
  43484. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  43485. }
  43486. }
  43487. let textureType;
  43488. let multisampled = '';
  43489. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  43490. if ( primarySamples > 1 ) {
  43491. multisampled = '_multisampled';
  43492. }
  43493. if ( texture.isCubeTexture === true ) {
  43494. textureType = 'texture_cube<f32>';
  43495. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43496. textureType = 'texture_2d_array<f32>';
  43497. } else if ( texture.isDepthTexture === true ) {
  43498. textureType = `texture_depth${multisampled}_2d`;
  43499. } else if ( texture.isVideoTexture === true ) {
  43500. textureType = 'texture_external';
  43501. } else if ( texture.isData3DTexture === true ) {
  43502. textureType = 'texture_3d<f32>';
  43503. } else if ( uniform.node.isStorageTextureNode === true ) {
  43504. const format = getFormat( texture );
  43505. const access = this.getStorageAccess( uniform.node, shaderStage );
  43506. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  43507. } else {
  43508. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  43509. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  43510. }
  43511. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  43512. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  43513. const bufferNode = uniform.node;
  43514. const bufferType = this.getType( bufferNode.bufferType );
  43515. const bufferCount = bufferNode.bufferCount;
  43516. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  43517. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  43518. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  43519. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  43520. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  43521. } else {
  43522. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  43523. const groupName = uniform.groupNode.name;
  43524. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  43525. index: uniformIndexes.binding ++,
  43526. id: uniformIndexes.group,
  43527. snippets: []
  43528. } );
  43529. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  43530. }
  43531. }
  43532. for ( const name in uniformGroups ) {
  43533. const group = uniformGroups[ name ];
  43534. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  43535. }
  43536. let code = bindingSnippets.join( '\n' );
  43537. code += bufferSnippets.join( '\n' );
  43538. code += structSnippets.join( '\n' );
  43539. return code;
  43540. }
  43541. /**
  43542. * Controls the code build of the shader stages.
  43543. */
  43544. buildCode() {
  43545. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43546. this.sortBindingGroups();
  43547. for ( const shaderStage in shadersData ) {
  43548. const stageData = shadersData[ shaderStage ];
  43549. stageData.uniforms = this.getUniforms( shaderStage );
  43550. stageData.attributes = this.getAttributes( shaderStage );
  43551. stageData.varyings = this.getVaryings( shaderStage );
  43552. stageData.structs = this.getStructs( shaderStage );
  43553. stageData.vars = this.getVars( shaderStage );
  43554. stageData.codes = this.getCodes( shaderStage );
  43555. stageData.directives = this.getDirectives( shaderStage );
  43556. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  43557. //
  43558. let flow = '// code\n\n';
  43559. flow += this.flowCode[ shaderStage ];
  43560. const flowNodes = this.flowNodes[ shaderStage ];
  43561. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43562. const outputNode = mainNode.outputNode;
  43563. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  43564. for ( const node of flowNodes ) {
  43565. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43566. const slotName = node.name;
  43567. if ( slotName ) {
  43568. if ( flow.length > 0 ) flow += '\n';
  43569. flow += `\t// flow -> ${ slotName }\n`;
  43570. }
  43571. flow += `${ flowSlotData.code }\n\t`;
  43572. if ( node === mainNode && shaderStage !== 'compute' ) {
  43573. flow += '// result\n\n\t';
  43574. if ( shaderStage === 'vertex' ) {
  43575. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  43576. } else if ( shaderStage === 'fragment' ) {
  43577. if ( isOutputStruct ) {
  43578. stageData.returnType = outputNode.nodeType;
  43579. flow += `return ${ flowSlotData.result };`;
  43580. } else {
  43581. let structSnippet = '\t@location(0) color: vec4<f32>';
  43582. const builtins = this.getBuiltins( 'output' );
  43583. if ( builtins ) structSnippet += ',\n\t' + builtins;
  43584. stageData.returnType = 'OutputStruct';
  43585. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  43586. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  43587. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  43588. }
  43589. }
  43590. }
  43591. }
  43592. stageData.flow = flow;
  43593. }
  43594. if ( this.material !== null ) {
  43595. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  43596. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  43597. } else {
  43598. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  43599. }
  43600. }
  43601. /**
  43602. * Returns the native shader method name for a given generic name.
  43603. *
  43604. * @param {String} method - The method name to resolve.
  43605. * @param {String} [output=null] - An optional output.
  43606. * @return {String} The resolved WGSL method name.
  43607. */
  43608. getMethod( method, output = null ) {
  43609. let wgslMethod;
  43610. if ( output !== null ) {
  43611. wgslMethod = this._getWGSLMethod( method + '_' + output );
  43612. }
  43613. if ( wgslMethod === undefined ) {
  43614. wgslMethod = this._getWGSLMethod( method );
  43615. }
  43616. return wgslMethod || method;
  43617. }
  43618. /**
  43619. * Returns the WGSL type of the given node data type.
  43620. *
  43621. * @param {String} type - The node data type.
  43622. * @return {String} The WGSL type.
  43623. */
  43624. getType( type ) {
  43625. return wgslTypeLib[ type ] || type;
  43626. }
  43627. /**
  43628. * Whether the requested feature is available or not.
  43629. *
  43630. * @param {String} name - The requested feature.
  43631. * @return {Boolean} Whether the requested feature is supported or not.
  43632. */
  43633. isAvailable( name ) {
  43634. let result = supports[ name ];
  43635. if ( result === undefined ) {
  43636. if ( name === 'float32Filterable' ) {
  43637. result = this.renderer.hasFeature( 'float32-filterable' );
  43638. } else if ( name === 'clipDistance' ) {
  43639. result = this.renderer.hasFeature( 'clip-distances' );
  43640. }
  43641. supports[ name ] = result;
  43642. }
  43643. return result;
  43644. }
  43645. /**
  43646. * Returns the native shader method name for a given generic name.
  43647. *
  43648. * @private
  43649. * @param {String} method - The method name to resolve.
  43650. * @return {String} The resolved WGSL method name.
  43651. */
  43652. _getWGSLMethod( method ) {
  43653. if ( wgslPolyfill[ method ] !== undefined ) {
  43654. this._include( method );
  43655. }
  43656. return wgslMethods[ method ];
  43657. }
  43658. /**
  43659. * Includes the given method name into the current
  43660. * function node.
  43661. *
  43662. * @private
  43663. * @param {String} name - The method name to include.
  43664. * @return {CodeNode} The respective code node.
  43665. */
  43666. _include( name ) {
  43667. const codeNode = wgslPolyfill[ name ];
  43668. codeNode.build( this );
  43669. if ( this.currentFunctionNode !== null ) {
  43670. this.currentFunctionNode.includes.push( codeNode );
  43671. }
  43672. return codeNode;
  43673. }
  43674. /**
  43675. * Returns a WGSL vertex shader based on the given shader data.
  43676. *
  43677. * @private
  43678. * @param {Object} shaderData - The shader data.
  43679. * @return {String} The vertex shader.
  43680. */
  43681. _getWGSLVertexCode( shaderData ) {
  43682. return `${ this.getSignature() }
  43683. // directives
  43684. ${shaderData.directives}
  43685. // uniforms
  43686. ${shaderData.uniforms}
  43687. // varyings
  43688. ${shaderData.varyings}
  43689. var<private> varyings : VaryingsStruct;
  43690. // codes
  43691. ${shaderData.codes}
  43692. @vertex
  43693. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  43694. // vars
  43695. ${shaderData.vars}
  43696. // flow
  43697. ${shaderData.flow}
  43698. return varyings;
  43699. }
  43700. `;
  43701. }
  43702. /**
  43703. * Returns a WGSL fragment shader based on the given shader data.
  43704. *
  43705. * @private
  43706. * @param {Object} shaderData - The shader data.
  43707. * @return {String} The vertex shader.
  43708. */
  43709. _getWGSLFragmentCode( shaderData ) {
  43710. return `${ this.getSignature() }
  43711. // global
  43712. ${ diagnostics }
  43713. // uniforms
  43714. ${shaderData.uniforms}
  43715. // structs
  43716. ${shaderData.structs}
  43717. // codes
  43718. ${shaderData.codes}
  43719. @fragment
  43720. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  43721. // vars
  43722. ${shaderData.vars}
  43723. // flow
  43724. ${shaderData.flow}
  43725. }
  43726. `;
  43727. }
  43728. /**
  43729. * Returns a WGSL compute shader based on the given shader data.
  43730. *
  43731. * @private
  43732. * @param {Object} shaderData - The shader data.
  43733. * @param {String} workgroupSize - The workgroup size.
  43734. * @return {String} The vertex shader.
  43735. */
  43736. _getWGSLComputeCode( shaderData, workgroupSize ) {
  43737. return `${ this.getSignature() }
  43738. // directives
  43739. ${shaderData.directives}
  43740. // system
  43741. var<private> instanceIndex : u32;
  43742. // locals
  43743. ${shaderData.scopedArrays}
  43744. // uniforms
  43745. ${shaderData.uniforms}
  43746. // codes
  43747. ${shaderData.codes}
  43748. @compute @workgroup_size( ${workgroupSize} )
  43749. fn main( ${shaderData.attributes} ) {
  43750. // system
  43751. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  43752. // vars
  43753. ${shaderData.vars}
  43754. // flow
  43755. ${shaderData.flow}
  43756. }
  43757. `;
  43758. }
  43759. /**
  43760. * Returns a WGSL struct based on the given name and variables.
  43761. *
  43762. * @private
  43763. * @param {String} name - The struct name.
  43764. * @param {String} vars - The struct variables.
  43765. * @return {String} The WGSL snippet representing a struct.
  43766. */
  43767. _getWGSLStruct( name, vars ) {
  43768. return `
  43769. struct ${name} {
  43770. ${vars}
  43771. };`;
  43772. }
  43773. /**
  43774. * Returns a WGSL struct binding.
  43775. *
  43776. * @private
  43777. * @param {String} name - The struct name.
  43778. * @param {String} vars - The struct variables.
  43779. * @param {String} access - The access.
  43780. * @param {Number} [binding=0] - The binding index.
  43781. * @param {Number} [group=0] - The group index.
  43782. * @return {String} The WGSL snippet representing a struct binding.
  43783. */
  43784. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  43785. const structName = name + 'Struct';
  43786. const structSnippet = this._getWGSLStruct( structName, vars );
  43787. return `${structSnippet}
  43788. @binding( ${binding} ) @group( ${group} )
  43789. var<${access}> ${name} : ${structName};`;
  43790. }
  43791. }
  43792. /**
  43793. * A WebGPU backend utility module with common helpers.
  43794. *
  43795. * @private
  43796. */
  43797. class WebGPUUtils {
  43798. /**
  43799. * Constructs a new utility object.
  43800. *
  43801. * @param {WebGPUBackend} backend - The WebGPU backend.
  43802. */
  43803. constructor( backend ) {
  43804. /**
  43805. * A reference to the WebGPU backend.
  43806. *
  43807. * @type {WebGPUBackend}
  43808. */
  43809. this.backend = backend;
  43810. }
  43811. /**
  43812. * Returns the depth/stencil GPU format for the given render context.
  43813. *
  43814. * @param {RenderContext} renderContext - The render context.
  43815. * @return {String} The depth/stencil GPU texture format.
  43816. */
  43817. getCurrentDepthStencilFormat( renderContext ) {
  43818. let format;
  43819. if ( renderContext.depthTexture !== null ) {
  43820. format = this.getTextureFormatGPU( renderContext.depthTexture );
  43821. } else if ( renderContext.depth && renderContext.stencil ) {
  43822. format = GPUTextureFormat.Depth24PlusStencil8;
  43823. } else if ( renderContext.depth ) {
  43824. format = GPUTextureFormat.Depth24Plus;
  43825. }
  43826. return format;
  43827. }
  43828. /**
  43829. * Returns the GPU format for the given texture.
  43830. *
  43831. * @param {Texture} texture - The texture.
  43832. * @return {String} The GPU texture format.
  43833. */
  43834. getTextureFormatGPU( texture ) {
  43835. return this.backend.get( texture ).format;
  43836. }
  43837. /**
  43838. * Returns an object that defines the multi-sampling state of the given texture.
  43839. *
  43840. * @param {Texture} texture - The texture.
  43841. * @return {Object} The multi-sampling state.
  43842. */
  43843. getTextureSampleData( texture ) {
  43844. let samples;
  43845. if ( texture.isFramebufferTexture ) {
  43846. samples = 1;
  43847. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  43848. const renderer = this.backend.renderer;
  43849. const renderTarget = renderer.getRenderTarget();
  43850. samples = renderTarget ? renderTarget.samples : renderer.samples;
  43851. } else if ( texture.renderTarget ) {
  43852. samples = texture.renderTarget.samples;
  43853. }
  43854. samples = samples || 1;
  43855. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  43856. const primarySamples = isMSAA ? 1 : samples;
  43857. return { samples, primarySamples, isMSAA };
  43858. }
  43859. /**
  43860. * Returns the default color attachment's GPU format of the current render context.
  43861. *
  43862. * @param {RenderContext} renderContext - The render context.
  43863. * @return {String} The GPU texture format of the default color attachment.
  43864. */
  43865. getCurrentColorFormat( renderContext ) {
  43866. let format;
  43867. if ( renderContext.textures !== null ) {
  43868. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  43869. } else {
  43870. format = this.getPreferredCanvasFormat(); // default context format
  43871. }
  43872. return format;
  43873. }
  43874. /**
  43875. * Returns the output color space of the current render context.
  43876. *
  43877. * @param {RenderContext} renderContext - The render context.
  43878. * @return {String} The output color space.
  43879. */
  43880. getCurrentColorSpace( renderContext ) {
  43881. if ( renderContext.textures !== null ) {
  43882. return renderContext.textures[ 0 ].colorSpace;
  43883. }
  43884. return this.backend.renderer.outputColorSpace;
  43885. }
  43886. /**
  43887. * Returns GPU primitive topology for the given object and material.
  43888. *
  43889. * @param {Object3D} object - The 3D object.
  43890. * @param {Material} material - The material.
  43891. * @return {String} The GPU primitive topology.
  43892. */
  43893. getPrimitiveTopology( object, material ) {
  43894. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  43895. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  43896. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  43897. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  43898. }
  43899. /**
  43900. * Returns a modified sample count from the given sample count value.
  43901. *
  43902. * That is required since WebGPU does not support arbitrary sample counts.
  43903. *
  43904. * @param {Number} sampleCount - The input sample count.
  43905. * @return {Number} The (potentially updated) output sample count.
  43906. */
  43907. getSampleCount( sampleCount ) {
  43908. let count = 1;
  43909. if ( sampleCount > 1 ) {
  43910. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  43911. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  43912. if ( count === 2 ) {
  43913. count = 4;
  43914. }
  43915. }
  43916. return count;
  43917. }
  43918. /**
  43919. * Returns the sample count of the given render context.
  43920. *
  43921. * @param {RenderContext} renderContext - The render context.
  43922. * @return {Number} The sample count.
  43923. */
  43924. getSampleCountRenderContext( renderContext ) {
  43925. if ( renderContext.textures !== null ) {
  43926. return this.getSampleCount( renderContext.sampleCount );
  43927. }
  43928. return this.getSampleCount( this.backend.renderer.samples );
  43929. }
  43930. /**
  43931. * Returns the preferred canvas format.
  43932. *
  43933. * There is a separate method for this so it's possible to
  43934. * honor edge cases for specific devices.
  43935. *
  43936. * @return {String} The GPU texture format of the canvas.
  43937. */
  43938. getPreferredCanvasFormat() {
  43939. // TODO: Remove this check when Quest 34.5 is out
  43940. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  43941. if ( navigator.userAgent.includes( 'Quest' ) ) {
  43942. return GPUTextureFormat.BGRA8Unorm;
  43943. } else {
  43944. return navigator.gpu.getPreferredCanvasFormat();
  43945. }
  43946. }
  43947. }
  43948. const typedArraysToVertexFormatPrefix = new Map( [
  43949. [ Int8Array, [ 'sint8', 'snorm8' ]],
  43950. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  43951. [ Int16Array, [ 'sint16', 'snorm16' ]],
  43952. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  43953. [ Int32Array, [ 'sint32', 'snorm32' ]],
  43954. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  43955. [ Float32Array, [ 'float32', ]],
  43956. ] );
  43957. const typedAttributeToVertexFormatPrefix = new Map( [
  43958. [ Float16BufferAttribute, [ 'float16', ]],
  43959. ] );
  43960. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  43961. [ Int32Array, 'sint32' ],
  43962. [ Int16Array, 'sint32' ], // patch for INT16
  43963. [ Uint32Array, 'uint32' ],
  43964. [ Uint16Array, 'uint32' ], // patch for UINT16
  43965. [ Float32Array, 'float32' ]
  43966. ] );
  43967. /**
  43968. * A WebGPU backend utility module for managing shader attributes.
  43969. *
  43970. * @private
  43971. */
  43972. class WebGPUAttributeUtils {
  43973. /**
  43974. * Constructs a new utility object.
  43975. *
  43976. * @param {WebGPUBackend} backend - The WebGPU backend.
  43977. */
  43978. constructor( backend ) {
  43979. /**
  43980. * A reference to the WebGPU backend.
  43981. *
  43982. * @type {WebGPUBackend}
  43983. */
  43984. this.backend = backend;
  43985. }
  43986. /**
  43987. * Creates the GPU buffer for the given buffer attribute.
  43988. *
  43989. * @param {BufferAttribute} attribute - The buffer attribute.
  43990. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  43991. */
  43992. createAttribute( attribute, usage ) {
  43993. const bufferAttribute = this._getBufferAttribute( attribute );
  43994. const backend = this.backend;
  43995. const bufferData = backend.get( bufferAttribute );
  43996. let buffer = bufferData.buffer;
  43997. if ( buffer === undefined ) {
  43998. const device = backend.device;
  43999. let array = bufferAttribute.array;
  44000. // patch for INT16 and UINT16
  44001. if ( attribute.normalized === false ) {
  44002. if ( array.constructor === Int16Array ) {
  44003. array = new Int32Array( array );
  44004. } else if ( array.constructor === Uint16Array ) {
  44005. array = new Uint32Array( array );
  44006. if ( usage & GPUBufferUsage.INDEX ) {
  44007. for ( let i = 0; i < array.length; i ++ ) {
  44008. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  44009. }
  44010. }
  44011. }
  44012. }
  44013. bufferAttribute.array = array;
  44014. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  44015. array = new array.constructor( bufferAttribute.count * 4 );
  44016. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  44017. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  44018. }
  44019. // Update BufferAttribute
  44020. bufferAttribute.itemSize = 4;
  44021. bufferAttribute.array = array;
  44022. }
  44023. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  44024. buffer = device.createBuffer( {
  44025. label: bufferAttribute.name,
  44026. size: size,
  44027. usage: usage,
  44028. mappedAtCreation: true
  44029. } );
  44030. new array.constructor( buffer.getMappedRange() ).set( array );
  44031. buffer.unmap();
  44032. bufferData.buffer = buffer;
  44033. }
  44034. }
  44035. /**
  44036. * Updates the GPU buffer of the given buffer attribute.
  44037. *
  44038. * @param {BufferAttribute} attribute - The buffer attribute.
  44039. */
  44040. updateAttribute( attribute ) {
  44041. const bufferAttribute = this._getBufferAttribute( attribute );
  44042. const backend = this.backend;
  44043. const device = backend.device;
  44044. const buffer = backend.get( bufferAttribute ).buffer;
  44045. const array = bufferAttribute.array;
  44046. const isTypedArray = this._isTypedArray( array );
  44047. const updateRanges = bufferAttribute.updateRanges;
  44048. if ( updateRanges.length === 0 ) {
  44049. // Not using update ranges
  44050. device.queue.writeBuffer(
  44051. buffer,
  44052. 0,
  44053. array,
  44054. 0
  44055. );
  44056. } else {
  44057. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  44058. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  44059. const range = updateRanges[ i ];
  44060. const dataOffset = range.start * byteOffsetFactor;
  44061. const size = range.count * byteOffsetFactor;
  44062. device.queue.writeBuffer(
  44063. buffer,
  44064. 0,
  44065. array,
  44066. dataOffset,
  44067. size
  44068. );
  44069. }
  44070. bufferAttribute.clearUpdateRanges();
  44071. }
  44072. }
  44073. /**
  44074. * This method creates the vertex buffer layout data which are
  44075. * require when creating a render pipeline for the given render object.
  44076. *
  44077. * @param {RenderObject} renderObject - The render object.
  44078. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  44079. */
  44080. createShaderVertexBuffers( renderObject ) {
  44081. const attributes = renderObject.getAttributes();
  44082. const vertexBuffers = new Map();
  44083. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  44084. const geometryAttribute = attributes[ slot ];
  44085. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  44086. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  44087. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  44088. if ( vertexBufferLayout === undefined ) {
  44089. let arrayStride, stepMode;
  44090. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  44091. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  44092. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  44093. } else {
  44094. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  44095. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  44096. }
  44097. // patch for INT16 and UINT16
  44098. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  44099. arrayStride = 4;
  44100. }
  44101. vertexBufferLayout = {
  44102. arrayStride,
  44103. attributes: [],
  44104. stepMode
  44105. };
  44106. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  44107. }
  44108. const format = this._getVertexFormat( geometryAttribute );
  44109. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  44110. vertexBufferLayout.attributes.push( {
  44111. shaderLocation: slot,
  44112. offset,
  44113. format
  44114. } );
  44115. }
  44116. return Array.from( vertexBuffers.values() );
  44117. }
  44118. /**
  44119. * Destroys the GPU buffer of the given buffer attribute.
  44120. *
  44121. * @param {BufferAttribute} attribute - The buffer attribute.
  44122. */
  44123. destroyAttribute( attribute ) {
  44124. const backend = this.backend;
  44125. const data = backend.get( this._getBufferAttribute( attribute ) );
  44126. data.buffer.destroy();
  44127. backend.delete( attribute );
  44128. }
  44129. /**
  44130. * This method performs a readback operation by moving buffer data from
  44131. * a storage buffer attribute from the GPU to the CPU.
  44132. *
  44133. * @async
  44134. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44135. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44136. */
  44137. async getArrayBufferAsync( attribute ) {
  44138. const backend = this.backend;
  44139. const device = backend.device;
  44140. const data = backend.get( this._getBufferAttribute( attribute ) );
  44141. const bufferGPU = data.buffer;
  44142. const size = bufferGPU.size;
  44143. const readBufferGPU = device.createBuffer( {
  44144. label: `${ attribute.name }_readback`,
  44145. size,
  44146. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44147. } );
  44148. const cmdEncoder = device.createCommandEncoder( {
  44149. label: `readback_encoder_${ attribute.name }`
  44150. } );
  44151. cmdEncoder.copyBufferToBuffer(
  44152. bufferGPU,
  44153. 0,
  44154. readBufferGPU,
  44155. 0,
  44156. size
  44157. );
  44158. const gpuCommands = cmdEncoder.finish();
  44159. device.queue.submit( [ gpuCommands ] );
  44160. await readBufferGPU.mapAsync( GPUMapMode.READ );
  44161. const arrayBuffer = readBufferGPU.getMappedRange();
  44162. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  44163. readBufferGPU.unmap();
  44164. return dstBuffer.buffer;
  44165. }
  44166. /**
  44167. * Returns the vertex format of the given buffer attribute.
  44168. *
  44169. * @private
  44170. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  44171. * @return {String} The vertex format (e.g. 'float32x3').
  44172. */
  44173. _getVertexFormat( geometryAttribute ) {
  44174. const { itemSize, normalized } = geometryAttribute;
  44175. const ArrayType = geometryAttribute.array.constructor;
  44176. const AttributeType = geometryAttribute.constructor;
  44177. let format;
  44178. if ( itemSize === 1 ) {
  44179. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  44180. } else {
  44181. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  44182. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  44183. if ( prefix ) {
  44184. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  44185. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  44186. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  44187. if ( paddedItemSize % 1 ) {
  44188. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  44189. }
  44190. format = `${prefix}x${paddedItemSize}`;
  44191. }
  44192. }
  44193. if ( ! format ) {
  44194. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  44195. }
  44196. return format;
  44197. }
  44198. /**
  44199. * Returns `true` if the given array is a typed array.
  44200. *
  44201. * @private
  44202. * @param {Any} array - The array.
  44203. * @return {Boolean} Whether the given array is a typed array or not.
  44204. */
  44205. _isTypedArray( array ) {
  44206. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  44207. }
  44208. /**
  44209. * Utility method for handling interleaved buffer attributes correctly.
  44210. * To process them, their `InterleavedBuffer` is returned.
  44211. *
  44212. * @private
  44213. * @param {BufferAttribute} attribute - The attribute.
  44214. * @return {BufferAttribute|InterleavedBuffer}
  44215. */
  44216. _getBufferAttribute( attribute ) {
  44217. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  44218. return attribute;
  44219. }
  44220. }
  44221. /**
  44222. * A WebGPU backend utility module for managing bindings.
  44223. *
  44224. * When reading the documentation it's helpful to keep in mind that
  44225. * all class definitions starting with 'GPU*' are modules from the
  44226. * WebGPU API. So for example `BindGroup` is a class from the engine
  44227. * whereas `GPUBindGroup` is a class from WebGPU.
  44228. *
  44229. * @private
  44230. */
  44231. class WebGPUBindingUtils {
  44232. /**
  44233. * Constructs a new utility object.
  44234. *
  44235. * @param {WebGPUBackend} backend - The WebGPU backend.
  44236. */
  44237. constructor( backend ) {
  44238. /**
  44239. * A reference to the WebGPU backend.
  44240. *
  44241. * @type {WebGPUBackend}
  44242. */
  44243. this.backend = backend;
  44244. /**
  44245. * A cache for managing bind group layouts.
  44246. *
  44247. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  44248. */
  44249. this.bindGroupLayoutCache = new WeakMap();
  44250. }
  44251. /**
  44252. * Creates a GPU bind group layout for the given bind group.
  44253. *
  44254. * @param {BindGroup} bindGroup - The bind group.
  44255. * @return {GPUBindGroupLayout} The GPU bind group layout.
  44256. */
  44257. createBindingsLayout( bindGroup ) {
  44258. const backend = this.backend;
  44259. const device = backend.device;
  44260. const entries = [];
  44261. let index = 0;
  44262. for ( const binding of bindGroup.bindings ) {
  44263. const bindingGPU = {
  44264. binding: index ++,
  44265. visibility: binding.visibility
  44266. };
  44267. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  44268. const buffer = {}; // GPUBufferBindingLayout
  44269. if ( binding.isStorageBuffer ) {
  44270. if ( binding.visibility & 4 ) {
  44271. // compute
  44272. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  44273. buffer.type = GPUBufferBindingType.Storage;
  44274. } else {
  44275. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  44276. }
  44277. } else {
  44278. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  44279. }
  44280. }
  44281. bindingGPU.buffer = buffer;
  44282. } else if ( binding.isSampler ) {
  44283. const sampler = {}; // GPUSamplerBindingLayout
  44284. if ( binding.texture.isDepthTexture ) {
  44285. if ( binding.texture.compareFunction !== null ) {
  44286. sampler.type = 'comparison';
  44287. }
  44288. }
  44289. bindingGPU.sampler = sampler;
  44290. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  44291. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  44292. } else if ( binding.isSampledTexture && binding.store ) {
  44293. const storageTexture = {}; // GPUStorageTextureBindingLayout
  44294. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  44295. const access = binding.access;
  44296. if ( access === NodeAccess.READ_WRITE ) {
  44297. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  44298. } else if ( access === NodeAccess.WRITE_ONLY ) {
  44299. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  44300. } else {
  44301. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  44302. }
  44303. bindingGPU.storageTexture = storageTexture;
  44304. } else if ( binding.isSampledTexture ) {
  44305. const texture = {}; // GPUTextureBindingLayout
  44306. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  44307. if ( primarySamples > 1 ) {
  44308. texture.multisampled = true;
  44309. if ( ! binding.texture.isDepthTexture ) {
  44310. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  44311. }
  44312. }
  44313. if ( binding.texture.isDepthTexture ) {
  44314. texture.sampleType = GPUTextureSampleType.Depth;
  44315. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  44316. const type = binding.texture.type;
  44317. if ( type === IntType ) {
  44318. texture.sampleType = GPUTextureSampleType.SInt;
  44319. } else if ( type === UnsignedIntType ) {
  44320. texture.sampleType = GPUTextureSampleType.UInt;
  44321. } else if ( type === FloatType ) {
  44322. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  44323. texture.sampleType = GPUTextureSampleType.Float;
  44324. } else {
  44325. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  44326. }
  44327. }
  44328. }
  44329. if ( binding.isSampledCubeTexture ) {
  44330. texture.viewDimension = GPUTextureViewDimension.Cube;
  44331. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44332. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  44333. } else if ( binding.isSampledTexture3D ) {
  44334. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  44335. }
  44336. bindingGPU.texture = texture;
  44337. } else {
  44338. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  44339. }
  44340. entries.push( bindingGPU );
  44341. }
  44342. return device.createBindGroupLayout( { entries } );
  44343. }
  44344. /**
  44345. * Creates bindings from the given bind group definition.
  44346. *
  44347. * @param {BindGroup} bindGroup - The bind group.
  44348. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44349. * @param {Number} cacheIndex - The cache index.
  44350. * @param {Number} version - The version.
  44351. */
  44352. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  44353. const { backend, bindGroupLayoutCache } = this;
  44354. const bindingsData = backend.get( bindGroup );
  44355. // setup (static) binding layout and (dynamic) binding group
  44356. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  44357. if ( bindLayoutGPU === undefined ) {
  44358. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  44359. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  44360. }
  44361. let bindGroupGPU;
  44362. if ( cacheIndex > 0 ) {
  44363. if ( bindingsData.groups === undefined ) {
  44364. bindingsData.groups = [];
  44365. bindingsData.versions = [];
  44366. }
  44367. if ( bindingsData.versions[ cacheIndex ] === version ) {
  44368. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  44369. }
  44370. }
  44371. if ( bindGroupGPU === undefined ) {
  44372. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  44373. if ( cacheIndex > 0 ) {
  44374. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  44375. bindingsData.versions[ cacheIndex ] = version;
  44376. }
  44377. }
  44378. bindingsData.group = bindGroupGPU;
  44379. bindingsData.layout = bindLayoutGPU;
  44380. }
  44381. /**
  44382. * Updates a buffer binding.
  44383. *
  44384. * @param {Buffer} binding - The buffer binding to update.
  44385. */
  44386. updateBinding( binding ) {
  44387. const backend = this.backend;
  44388. const device = backend.device;
  44389. const buffer = binding.buffer;
  44390. const bufferGPU = backend.get( binding ).buffer;
  44391. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  44392. }
  44393. /**
  44394. * Creates a GPU bind group for the given bind group and GPU layout.
  44395. *
  44396. * @param {BindGroup} bindGroup - The bind group.
  44397. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  44398. * @return {GPUBindGroup} The GPU bind group.
  44399. */
  44400. createBindGroup( bindGroup, layoutGPU ) {
  44401. const backend = this.backend;
  44402. const device = backend.device;
  44403. let bindingPoint = 0;
  44404. const entriesGPU = [];
  44405. for ( const binding of bindGroup.bindings ) {
  44406. if ( binding.isUniformBuffer ) {
  44407. const bindingData = backend.get( binding );
  44408. if ( bindingData.buffer === undefined ) {
  44409. const byteLength = binding.byteLength;
  44410. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  44411. const bufferGPU = device.createBuffer( {
  44412. label: 'bindingBuffer_' + binding.name,
  44413. size: byteLength,
  44414. usage: usage
  44415. } );
  44416. bindingData.buffer = bufferGPU;
  44417. }
  44418. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44419. } else if ( binding.isStorageBuffer ) {
  44420. const bindingData = backend.get( binding );
  44421. if ( bindingData.buffer === undefined ) {
  44422. const attribute = binding.attribute;
  44423. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  44424. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  44425. bindingData.buffer = backend.get( attribute ).buffer;
  44426. }
  44427. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44428. } else if ( binding.isSampler ) {
  44429. const textureGPU = backend.get( binding.texture );
  44430. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  44431. } else if ( binding.isSampledTexture ) {
  44432. const textureData = backend.get( binding.texture );
  44433. let resourceGPU;
  44434. if ( textureData.externalTexture !== undefined ) {
  44435. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  44436. } else {
  44437. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  44438. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  44439. resourceGPU = textureData[ propertyName ];
  44440. if ( resourceGPU === undefined ) {
  44441. const aspectGPU = GPUTextureAspect.All;
  44442. let dimensionViewGPU;
  44443. if ( binding.isSampledCubeTexture ) {
  44444. dimensionViewGPU = GPUTextureViewDimension.Cube;
  44445. } else if ( binding.isSampledTexture3D ) {
  44446. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  44447. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44448. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  44449. } else {
  44450. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  44451. }
  44452. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  44453. }
  44454. }
  44455. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  44456. }
  44457. bindingPoint ++;
  44458. }
  44459. return device.createBindGroup( {
  44460. label: 'bindGroup_' + bindGroup.name,
  44461. layout: layoutGPU,
  44462. entries: entriesGPU
  44463. } );
  44464. }
  44465. }
  44466. /**
  44467. * A WebGPU backend utility module for managing pipelines.
  44468. *
  44469. * @private
  44470. */
  44471. class WebGPUPipelineUtils {
  44472. /**
  44473. * Constructs a new utility object.
  44474. *
  44475. * @param {WebGPUBackend} backend - The WebGPU backend.
  44476. */
  44477. constructor( backend ) {
  44478. /**
  44479. * A reference to the WebGPU backend.
  44480. *
  44481. * @type {WebGPUBackend}
  44482. */
  44483. this.backend = backend;
  44484. }
  44485. /**
  44486. * Returns the sample count derived from the given render context.
  44487. *
  44488. * @private
  44489. * @param {RenderContext} renderContext - The render context.
  44490. * @return {Number} The sample count.
  44491. */
  44492. _getSampleCount( renderContext ) {
  44493. return this.backend.utils.getSampleCountRenderContext( renderContext );
  44494. }
  44495. /**
  44496. * Creates a render pipeline for the given render object.
  44497. *
  44498. * @param {RenderObject} renderObject - The render object.
  44499. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  44500. */
  44501. createRenderPipeline( renderObject, promises ) {
  44502. const { object, material, geometry, pipeline } = renderObject;
  44503. const { vertexProgram, fragmentProgram } = pipeline;
  44504. const backend = this.backend;
  44505. const device = backend.device;
  44506. const utils = backend.utils;
  44507. const pipelineData = backend.get( pipeline );
  44508. // bind group layouts
  44509. const bindGroupLayouts = [];
  44510. for ( const bindGroup of renderObject.getBindings() ) {
  44511. const bindingsData = backend.get( bindGroup );
  44512. bindGroupLayouts.push( bindingsData.layout );
  44513. }
  44514. // vertex buffers
  44515. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  44516. // blending
  44517. let blending;
  44518. if ( material.transparent === true && material.blending !== NoBlending ) {
  44519. blending = this._getBlending( material );
  44520. }
  44521. // stencil
  44522. let stencilFront = {};
  44523. if ( material.stencilWrite === true ) {
  44524. stencilFront = {
  44525. compare: this._getStencilCompare( material ),
  44526. failOp: this._getStencilOperation( material.stencilFail ),
  44527. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  44528. passOp: this._getStencilOperation( material.stencilZPass )
  44529. };
  44530. }
  44531. const colorWriteMask = this._getColorWriteMask( material );
  44532. const targets = [];
  44533. if ( renderObject.context.textures !== null ) {
  44534. const textures = renderObject.context.textures;
  44535. for ( let i = 0; i < textures.length; i ++ ) {
  44536. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  44537. targets.push( {
  44538. format: colorFormat,
  44539. blend: blending,
  44540. writeMask: colorWriteMask
  44541. } );
  44542. }
  44543. } else {
  44544. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44545. targets.push( {
  44546. format: colorFormat,
  44547. blend: blending,
  44548. writeMask: colorWriteMask
  44549. } );
  44550. }
  44551. const vertexModule = backend.get( vertexProgram ).module;
  44552. const fragmentModule = backend.get( fragmentProgram ).module;
  44553. const primitiveState = this._getPrimitiveState( object, geometry, material );
  44554. const depthCompare = this._getDepthCompare( material );
  44555. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44556. const sampleCount = this._getSampleCount( renderObject.context );
  44557. const pipelineDescriptor = {
  44558. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  44559. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  44560. fragment: Object.assign( {}, fragmentModule, { targets } ),
  44561. primitive: primitiveState,
  44562. multisample: {
  44563. count: sampleCount,
  44564. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  44565. },
  44566. layout: device.createPipelineLayout( {
  44567. bindGroupLayouts
  44568. } )
  44569. };
  44570. const depthStencil = {};
  44571. const renderDepth = renderObject.context.depth;
  44572. const renderStencil = renderObject.context.stencil;
  44573. if ( renderDepth === true || renderStencil === true ) {
  44574. if ( renderDepth === true ) {
  44575. depthStencil.format = depthStencilFormat;
  44576. depthStencil.depthWriteEnabled = material.depthWrite;
  44577. depthStencil.depthCompare = depthCompare;
  44578. }
  44579. if ( renderStencil === true ) {
  44580. depthStencil.stencilFront = stencilFront;
  44581. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  44582. depthStencil.stencilReadMask = material.stencilFuncMask;
  44583. depthStencil.stencilWriteMask = material.stencilWriteMask;
  44584. }
  44585. pipelineDescriptor.depthStencil = depthStencil;
  44586. }
  44587. if ( promises === null ) {
  44588. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  44589. } else {
  44590. const p = new Promise( ( resolve /*, reject*/ ) => {
  44591. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  44592. pipelineData.pipeline = pipeline;
  44593. resolve();
  44594. } );
  44595. } );
  44596. promises.push( p );
  44597. }
  44598. }
  44599. /**
  44600. * Creates GPU render bundle encoder for the given render context.
  44601. *
  44602. * @param {RenderContext} renderContext - The render context.
  44603. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  44604. */
  44605. createBundleEncoder( renderContext ) {
  44606. const backend = this.backend;
  44607. const { utils, device } = backend;
  44608. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  44609. const colorFormat = utils.getCurrentColorFormat( renderContext );
  44610. const sampleCount = this._getSampleCount( renderContext );
  44611. const descriptor = {
  44612. label: 'renderBundleEncoder',
  44613. colorFormats: [ colorFormat ],
  44614. depthStencilFormat,
  44615. sampleCount
  44616. };
  44617. return device.createRenderBundleEncoder( descriptor );
  44618. }
  44619. /**
  44620. * Creates a compute pipeline for the given compute node.
  44621. *
  44622. * @param {ComputePipeline} pipeline - The compute pipeline.
  44623. * @param {Array<BindGroup>} bindings - The bindings.
  44624. */
  44625. createComputePipeline( pipeline, bindings ) {
  44626. const backend = this.backend;
  44627. const device = backend.device;
  44628. const computeProgram = backend.get( pipeline.computeProgram ).module;
  44629. const pipelineGPU = backend.get( pipeline );
  44630. // bind group layouts
  44631. const bindGroupLayouts = [];
  44632. for ( const bindingsGroup of bindings ) {
  44633. const bindingsData = backend.get( bindingsGroup );
  44634. bindGroupLayouts.push( bindingsData.layout );
  44635. }
  44636. pipelineGPU.pipeline = device.createComputePipeline( {
  44637. compute: computeProgram,
  44638. layout: device.createPipelineLayout( {
  44639. bindGroupLayouts
  44640. } )
  44641. } );
  44642. }
  44643. /**
  44644. * Returns the blending state as a descriptor object required
  44645. * for the pipeline creation.
  44646. *
  44647. * @private
  44648. * @param {Material} material - The material.
  44649. * @return {Object} The blending state.
  44650. */
  44651. _getBlending( material ) {
  44652. let color, alpha;
  44653. const blending = material.blending;
  44654. const blendSrc = material.blendSrc;
  44655. const blendDst = material.blendDst;
  44656. const blendEquation = material.blendEquation;
  44657. if ( blending === CustomBlending ) {
  44658. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  44659. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  44660. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  44661. color = {
  44662. srcFactor: this._getBlendFactor( blendSrc ),
  44663. dstFactor: this._getBlendFactor( blendDst ),
  44664. operation: this._getBlendOperation( blendEquation )
  44665. };
  44666. alpha = {
  44667. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  44668. dstFactor: this._getBlendFactor( blendDstAlpha ),
  44669. operation: this._getBlendOperation( blendEquationAlpha )
  44670. };
  44671. } else {
  44672. const premultipliedAlpha = material.premultipliedAlpha;
  44673. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  44674. color = {
  44675. srcFactor: srcRGB,
  44676. dstFactor: dstRGB,
  44677. operation: GPUBlendOperation.Add
  44678. };
  44679. alpha = {
  44680. srcFactor: srcAlpha,
  44681. dstFactor: dstAlpha,
  44682. operation: GPUBlendOperation.Add
  44683. };
  44684. };
  44685. if ( premultipliedAlpha ) {
  44686. switch ( blending ) {
  44687. case NormalBlending:
  44688. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44689. break;
  44690. case AdditiveBlending:
  44691. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  44692. break;
  44693. case SubtractiveBlending:
  44694. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44695. break;
  44696. case MultiplyBlending:
  44697. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  44698. break;
  44699. }
  44700. } else {
  44701. switch ( blending ) {
  44702. case NormalBlending:
  44703. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44704. break;
  44705. case AdditiveBlending:
  44706. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  44707. break;
  44708. case SubtractiveBlending:
  44709. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44710. break;
  44711. case MultiplyBlending:
  44712. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  44713. break;
  44714. }
  44715. }
  44716. }
  44717. if ( color !== undefined && alpha !== undefined ) {
  44718. return { color, alpha };
  44719. } else {
  44720. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  44721. }
  44722. }
  44723. /**
  44724. * Returns the GPU blend factor which is required for the pipeline creation.
  44725. *
  44726. * @private
  44727. * @param {Number} blend - The blend factor as a three.js constant.
  44728. * @return {String} The GPU blend factor.
  44729. */
  44730. _getBlendFactor( blend ) {
  44731. let blendFactor;
  44732. switch ( blend ) {
  44733. case ZeroFactor:
  44734. blendFactor = GPUBlendFactor.Zero;
  44735. break;
  44736. case OneFactor:
  44737. blendFactor = GPUBlendFactor.One;
  44738. break;
  44739. case SrcColorFactor:
  44740. blendFactor = GPUBlendFactor.Src;
  44741. break;
  44742. case OneMinusSrcColorFactor:
  44743. blendFactor = GPUBlendFactor.OneMinusSrc;
  44744. break;
  44745. case SrcAlphaFactor:
  44746. blendFactor = GPUBlendFactor.SrcAlpha;
  44747. break;
  44748. case OneMinusSrcAlphaFactor:
  44749. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  44750. break;
  44751. case DstColorFactor:
  44752. blendFactor = GPUBlendFactor.Dst;
  44753. break;
  44754. case OneMinusDstColorFactor:
  44755. blendFactor = GPUBlendFactor.OneMinusDstColor;
  44756. break;
  44757. case DstAlphaFactor:
  44758. blendFactor = GPUBlendFactor.DstAlpha;
  44759. break;
  44760. case OneMinusDstAlphaFactor:
  44761. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  44762. break;
  44763. case SrcAlphaSaturateFactor:
  44764. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  44765. break;
  44766. case BlendColorFactor:
  44767. blendFactor = GPUBlendFactor.Constant;
  44768. break;
  44769. case OneMinusBlendColorFactor:
  44770. blendFactor = GPUBlendFactor.OneMinusConstant;
  44771. break;
  44772. default:
  44773. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  44774. }
  44775. return blendFactor;
  44776. }
  44777. /**
  44778. * Returns the GPU stencil compare function which is required for the pipeline creation.
  44779. *
  44780. * @private
  44781. * @param {Material} material - The material.
  44782. * @return {String} The GPU stencil compare function.
  44783. */
  44784. _getStencilCompare( material ) {
  44785. let stencilCompare;
  44786. const stencilFunc = material.stencilFunc;
  44787. switch ( stencilFunc ) {
  44788. case NeverStencilFunc:
  44789. stencilCompare = GPUCompareFunction.Never;
  44790. break;
  44791. case AlwaysStencilFunc:
  44792. stencilCompare = GPUCompareFunction.Always;
  44793. break;
  44794. case LessStencilFunc:
  44795. stencilCompare = GPUCompareFunction.Less;
  44796. break;
  44797. case LessEqualStencilFunc:
  44798. stencilCompare = GPUCompareFunction.LessEqual;
  44799. break;
  44800. case EqualStencilFunc:
  44801. stencilCompare = GPUCompareFunction.Equal;
  44802. break;
  44803. case GreaterEqualStencilFunc:
  44804. stencilCompare = GPUCompareFunction.GreaterEqual;
  44805. break;
  44806. case GreaterStencilFunc:
  44807. stencilCompare = GPUCompareFunction.Greater;
  44808. break;
  44809. case NotEqualStencilFunc:
  44810. stencilCompare = GPUCompareFunction.NotEqual;
  44811. break;
  44812. default:
  44813. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  44814. }
  44815. return stencilCompare;
  44816. }
  44817. /**
  44818. * Returns the GPU stencil operation which is required for the pipeline creation.
  44819. *
  44820. * @private
  44821. * @param {Number} op - A three.js constant defining the stencil operation.
  44822. * @return {String} The GPU stencil operation.
  44823. */
  44824. _getStencilOperation( op ) {
  44825. let stencilOperation;
  44826. switch ( op ) {
  44827. case KeepStencilOp:
  44828. stencilOperation = GPUStencilOperation.Keep;
  44829. break;
  44830. case ZeroStencilOp:
  44831. stencilOperation = GPUStencilOperation.Zero;
  44832. break;
  44833. case ReplaceStencilOp:
  44834. stencilOperation = GPUStencilOperation.Replace;
  44835. break;
  44836. case InvertStencilOp:
  44837. stencilOperation = GPUStencilOperation.Invert;
  44838. break;
  44839. case IncrementStencilOp:
  44840. stencilOperation = GPUStencilOperation.IncrementClamp;
  44841. break;
  44842. case DecrementStencilOp:
  44843. stencilOperation = GPUStencilOperation.DecrementClamp;
  44844. break;
  44845. case IncrementWrapStencilOp:
  44846. stencilOperation = GPUStencilOperation.IncrementWrap;
  44847. break;
  44848. case DecrementWrapStencilOp:
  44849. stencilOperation = GPUStencilOperation.DecrementWrap;
  44850. break;
  44851. default:
  44852. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  44853. }
  44854. return stencilOperation;
  44855. }
  44856. /**
  44857. * Returns the GPU blend operation which is required for the pipeline creation.
  44858. *
  44859. * @private
  44860. * @param {Number} blendEquation - A three.js constant defining the blend equation.
  44861. * @return {String} The GPU blend operation.
  44862. */
  44863. _getBlendOperation( blendEquation ) {
  44864. let blendOperation;
  44865. switch ( blendEquation ) {
  44866. case AddEquation:
  44867. blendOperation = GPUBlendOperation.Add;
  44868. break;
  44869. case SubtractEquation:
  44870. blendOperation = GPUBlendOperation.Subtract;
  44871. break;
  44872. case ReverseSubtractEquation:
  44873. blendOperation = GPUBlendOperation.ReverseSubtract;
  44874. break;
  44875. case MinEquation:
  44876. blendOperation = GPUBlendOperation.Min;
  44877. break;
  44878. case MaxEquation:
  44879. blendOperation = GPUBlendOperation.Max;
  44880. break;
  44881. default:
  44882. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  44883. }
  44884. return blendOperation;
  44885. }
  44886. /**
  44887. * Returns the primitive state as a descriptor object required
  44888. * for the pipeline creation.
  44889. *
  44890. * @private
  44891. * @param {Object3D} object - The 3D object.
  44892. * @param {BufferGeometry} geometry - The geometry.
  44893. * @param {Material} material - The material.
  44894. * @return {Object} The primitive state.
  44895. */
  44896. _getPrimitiveState( object, geometry, material ) {
  44897. const descriptor = {};
  44898. const utils = this.backend.utils;
  44899. descriptor.topology = utils.getPrimitiveTopology( object, material );
  44900. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  44901. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44902. }
  44903. switch ( material.side ) {
  44904. case FrontSide:
  44905. descriptor.frontFace = GPUFrontFace.CCW;
  44906. descriptor.cullMode = GPUCullMode.Back;
  44907. break;
  44908. case BackSide:
  44909. descriptor.frontFace = GPUFrontFace.CCW;
  44910. descriptor.cullMode = GPUCullMode.Front;
  44911. break;
  44912. case DoubleSide:
  44913. descriptor.frontFace = GPUFrontFace.CCW;
  44914. descriptor.cullMode = GPUCullMode.None;
  44915. break;
  44916. default:
  44917. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  44918. break;
  44919. }
  44920. return descriptor;
  44921. }
  44922. /**
  44923. * Returns the GPU color write mask which is required for the pipeline creation.
  44924. *
  44925. * @private
  44926. * @param {Material} material - The material.
  44927. * @return {String} The GPU color write mask.
  44928. */
  44929. _getColorWriteMask( material ) {
  44930. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  44931. }
  44932. /**
  44933. * Returns the GPU depth compare function which is required for the pipeline creation.
  44934. *
  44935. * @private
  44936. * @param {Material} material - The material.
  44937. * @return {String} The GPU depth compare function.
  44938. */
  44939. _getDepthCompare( material ) {
  44940. let depthCompare;
  44941. if ( material.depthTest === false ) {
  44942. depthCompare = GPUCompareFunction.Always;
  44943. } else {
  44944. const depthFunc = material.depthFunc;
  44945. switch ( depthFunc ) {
  44946. case NeverDepth:
  44947. depthCompare = GPUCompareFunction.Never;
  44948. break;
  44949. case AlwaysDepth:
  44950. depthCompare = GPUCompareFunction.Always;
  44951. break;
  44952. case LessDepth:
  44953. depthCompare = GPUCompareFunction.Less;
  44954. break;
  44955. case LessEqualDepth:
  44956. depthCompare = GPUCompareFunction.LessEqual;
  44957. break;
  44958. case EqualDepth:
  44959. depthCompare = GPUCompareFunction.Equal;
  44960. break;
  44961. case GreaterEqualDepth:
  44962. depthCompare = GPUCompareFunction.GreaterEqual;
  44963. break;
  44964. case GreaterDepth:
  44965. depthCompare = GPUCompareFunction.Greater;
  44966. break;
  44967. case NotEqualDepth:
  44968. depthCompare = GPUCompareFunction.NotEqual;
  44969. break;
  44970. default:
  44971. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  44972. }
  44973. }
  44974. return depthCompare;
  44975. }
  44976. }
  44977. /*// debugger tools
  44978. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  44979. //*/
  44980. /**
  44981. * A backend implementation targeting WebGPU.
  44982. *
  44983. * @private
  44984. * @augments Backend
  44985. */
  44986. class WebGPUBackend extends Backend {
  44987. /**
  44988. * Constructs a new WebGPU backend.
  44989. *
  44990. * @param {Object} parameters - The configuration parameter.
  44991. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  44992. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  44993. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  44994. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  44995. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  44996. * @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.
  44997. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  44998. * @param {Boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  44999. * @param {String} [parameters.powerPreference=undefined] - The power preference.
  45000. * @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.
  45001. * @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.
  45002. */
  45003. constructor( parameters = {} ) {
  45004. super( parameters );
  45005. /**
  45006. * This flag can be used for type testing.
  45007. *
  45008. * @type {Boolean}
  45009. * @readonly
  45010. * @default true
  45011. */
  45012. this.isWebGPUBackend = true;
  45013. // some parameters require default values other than "undefined"
  45014. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  45015. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  45016. /**
  45017. * Whether to track timestamps with a Timestamp Query API or not.
  45018. *
  45019. * @type {Boolean}
  45020. * @default false
  45021. */
  45022. this.trackTimestamp = ( parameters.trackTimestamp === true );
  45023. /**
  45024. * A reference to the device.
  45025. *
  45026. * @type {GPUDevice?}
  45027. * @default null
  45028. */
  45029. this.device = null;
  45030. /**
  45031. * A reference to the context.
  45032. *
  45033. * @type {GPUCanvasContext?}
  45034. * @default null
  45035. */
  45036. this.context = null;
  45037. /**
  45038. * A reference to the color attachment of the default framebuffer.
  45039. *
  45040. * @type {GPUTexture?}
  45041. * @default null
  45042. */
  45043. this.colorBuffer = null;
  45044. /**
  45045. * A reference to the default render pass descriptor.
  45046. *
  45047. * @type {Object?}
  45048. * @default null
  45049. */
  45050. this.defaultRenderPassdescriptor = null;
  45051. /**
  45052. * A reference to a backend module holding common utility functions.
  45053. *
  45054. * @type {WebGPUUtils}
  45055. */
  45056. this.utils = new WebGPUUtils( this );
  45057. /**
  45058. * A reference to a backend module holding shader attribute-related
  45059. * utility functions.
  45060. *
  45061. * @type {WebGPUAttributeUtils}
  45062. */
  45063. this.attributeUtils = new WebGPUAttributeUtils( this );
  45064. /**
  45065. * A reference to a backend module holding shader binding-related
  45066. * utility functions.
  45067. *
  45068. * @type {WebGPUBindingUtils}
  45069. */
  45070. this.bindingUtils = new WebGPUBindingUtils( this );
  45071. /**
  45072. * A reference to a backend module holding shader pipeline-related
  45073. * utility functions.
  45074. *
  45075. * @type {WebGPUPipelineUtils}
  45076. */
  45077. this.pipelineUtils = new WebGPUPipelineUtils( this );
  45078. /**
  45079. * A reference to a backend module holding shader texture-related
  45080. * utility functions.
  45081. *
  45082. * @type {WebGPUTextureUtils}
  45083. */
  45084. this.textureUtils = new WebGPUTextureUtils( this );
  45085. /**
  45086. * A map that manages the resolve buffers for occlusion queries.
  45087. *
  45088. * @type {Map<Number,GPUBuffer>}
  45089. */
  45090. this.occludedResolveCache = new Map();
  45091. }
  45092. /**
  45093. * Initializes the backend so it is ready for usage.
  45094. *
  45095. * @async
  45096. * @param {Renderer} renderer - The renderer.
  45097. * @return {Promise} A Promise that resolves when the backend has been initialized.
  45098. */
  45099. async init( renderer ) {
  45100. await super.init( renderer );
  45101. //
  45102. const parameters = this.parameters;
  45103. // create the device if it is not passed with parameters
  45104. let device;
  45105. if ( parameters.device === undefined ) {
  45106. const adapterOptions = {
  45107. powerPreference: parameters.powerPreference
  45108. };
  45109. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  45110. if ( adapter === null ) {
  45111. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  45112. }
  45113. // feature support
  45114. const features = Object.values( GPUFeatureName );
  45115. const supportedFeatures = [];
  45116. for ( const name of features ) {
  45117. if ( adapter.features.has( name ) ) {
  45118. supportedFeatures.push( name );
  45119. }
  45120. }
  45121. const deviceDescriptor = {
  45122. requiredFeatures: supportedFeatures,
  45123. requiredLimits: parameters.requiredLimits
  45124. };
  45125. device = await adapter.requestDevice( deviceDescriptor );
  45126. } else {
  45127. device = parameters.device;
  45128. }
  45129. device.lost.then( ( info ) => {
  45130. const deviceLossInfo = {
  45131. api: 'WebGPU',
  45132. message: info.message || 'Unknown reason',
  45133. reason: info.reason || null,
  45134. originalEvent: info
  45135. };
  45136. renderer.onDeviceLost( deviceLossInfo );
  45137. } );
  45138. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  45139. this.device = device;
  45140. this.context = context;
  45141. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  45142. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  45143. this.context.configure( {
  45144. device: this.device,
  45145. format: this.utils.getPreferredCanvasFormat(),
  45146. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  45147. alphaMode: alphaMode
  45148. } );
  45149. this.updateSize();
  45150. }
  45151. /**
  45152. * The coordinate system of the backend.
  45153. *
  45154. * @type {Number}
  45155. * @readonly
  45156. */
  45157. get coordinateSystem() {
  45158. return WebGPUCoordinateSystem;
  45159. }
  45160. /**
  45161. * This method performs a readback operation by moving buffer data from
  45162. * a storage buffer attribute from the GPU to the CPU.
  45163. *
  45164. * @async
  45165. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45166. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45167. */
  45168. async getArrayBufferAsync( attribute ) {
  45169. return await this.attributeUtils.getArrayBufferAsync( attribute );
  45170. }
  45171. /**
  45172. * Returns the backend's rendering context.
  45173. *
  45174. * @return {GPUCanvasContext} The rendering context.
  45175. */
  45176. getContext() {
  45177. return this.context;
  45178. }
  45179. /**
  45180. * Returns the default render pass descriptor.
  45181. *
  45182. * In WebGPU, the default framebuffer must be configured
  45183. * like custom framebuffers so the backend needs a render
  45184. * pass descriptor even when rendering directly to screen.
  45185. *
  45186. * @private
  45187. * @return {Object} The render pass descriptor.
  45188. */
  45189. _getDefaultRenderPassDescriptor() {
  45190. let descriptor = this.defaultRenderPassdescriptor;
  45191. if ( descriptor === null ) {
  45192. const renderer = this.renderer;
  45193. descriptor = {
  45194. colorAttachments: [ {
  45195. view: null
  45196. } ],
  45197. };
  45198. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  45199. descriptor.depthStencilAttachment = {
  45200. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  45201. };
  45202. }
  45203. const colorAttachment = descriptor.colorAttachments[ 0 ];
  45204. if ( this.renderer.samples > 0 ) {
  45205. colorAttachment.view = this.colorBuffer.createView();
  45206. } else {
  45207. colorAttachment.resolveTarget = undefined;
  45208. }
  45209. this.defaultRenderPassdescriptor = descriptor;
  45210. }
  45211. const colorAttachment = descriptor.colorAttachments[ 0 ];
  45212. if ( this.renderer.samples > 0 ) {
  45213. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  45214. } else {
  45215. colorAttachment.view = this.context.getCurrentTexture().createView();
  45216. }
  45217. return descriptor;
  45218. }
  45219. /**
  45220. * Returns the render pass descriptor for the given render context.
  45221. *
  45222. * @private
  45223. * @param {RenderContext} renderContext - The render context.
  45224. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  45225. * @return {Object} The render pass descriptor.
  45226. */
  45227. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  45228. const renderTarget = renderContext.renderTarget;
  45229. const renderTargetData = this.get( renderTarget );
  45230. let descriptors = renderTargetData.descriptors;
  45231. if ( descriptors === undefined ||
  45232. renderTargetData.width !== renderTarget.width ||
  45233. renderTargetData.height !== renderTarget.height ||
  45234. renderTargetData.dimensions !== renderTarget.dimensions ||
  45235. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  45236. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  45237. renderTargetData.samples !== renderTarget.samples ||
  45238. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  45239. ) {
  45240. descriptors = {};
  45241. renderTargetData.descriptors = descriptors;
  45242. // dispose
  45243. const onDispose = () => {
  45244. renderTarget.removeEventListener( 'dispose', onDispose );
  45245. this.delete( renderTarget );
  45246. };
  45247. renderTarget.addEventListener( 'dispose', onDispose );
  45248. }
  45249. const cacheKey = renderContext.getCacheKey();
  45250. let descriptor = descriptors[ cacheKey ];
  45251. if ( descriptor === undefined ) {
  45252. const textures = renderContext.textures;
  45253. const colorAttachments = [];
  45254. let sliceIndex;
  45255. for ( let i = 0; i < textures.length; i ++ ) {
  45256. const textureData = this.get( textures[ i ] );
  45257. const viewDescriptor = {
  45258. label: `colorAttachment_${ i }`,
  45259. baseMipLevel: renderContext.activeMipmapLevel,
  45260. mipLevelCount: 1,
  45261. baseArrayLayer: renderContext.activeCubeFace,
  45262. arrayLayerCount: 1,
  45263. dimension: GPUTextureViewDimension.TwoD
  45264. };
  45265. if ( renderTarget.isRenderTarget3D ) {
  45266. sliceIndex = renderContext.activeCubeFace;
  45267. viewDescriptor.baseArrayLayer = 0;
  45268. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  45269. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  45270. } else if ( renderTarget.isRenderTargetArray ) {
  45271. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  45272. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  45273. }
  45274. const textureView = textureData.texture.createView( viewDescriptor );
  45275. let view, resolveTarget;
  45276. if ( textureData.msaaTexture !== undefined ) {
  45277. view = textureData.msaaTexture.createView();
  45278. resolveTarget = textureView;
  45279. } else {
  45280. view = textureView;
  45281. resolveTarget = undefined;
  45282. }
  45283. colorAttachments.push( {
  45284. view,
  45285. depthSlice: sliceIndex,
  45286. resolveTarget,
  45287. loadOp: GPULoadOp.Load,
  45288. storeOp: GPUStoreOp.Store,
  45289. ...colorAttachmentsConfig
  45290. } );
  45291. }
  45292. descriptor = {
  45293. colorAttachments,
  45294. };
  45295. if ( renderContext.depth ) {
  45296. const depthTextureData = this.get( renderContext.depthTexture );
  45297. const depthStencilAttachment = {
  45298. view: depthTextureData.texture.createView()
  45299. };
  45300. descriptor.depthStencilAttachment = depthStencilAttachment;
  45301. }
  45302. descriptors[ cacheKey ] = descriptor;
  45303. renderTargetData.width = renderTarget.width;
  45304. renderTargetData.height = renderTarget.height;
  45305. renderTargetData.samples = renderTarget.samples;
  45306. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  45307. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  45308. renderTargetData.dimensions = renderTarget.dimensions;
  45309. renderTargetData.depthSlice = sliceIndex;
  45310. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  45311. }
  45312. return descriptor;
  45313. }
  45314. /**
  45315. * This method is executed at the beginning of a render call and prepares
  45316. * the WebGPU state for upcoming render calls
  45317. *
  45318. * @param {RenderContext} renderContext - The render context.
  45319. */
  45320. beginRender( renderContext ) {
  45321. const renderContextData = this.get( renderContext );
  45322. const device = this.device;
  45323. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45324. let occlusionQuerySet;
  45325. if ( occlusionQueryCount > 0 ) {
  45326. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  45327. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  45328. // Get a reference to the array of objects with queries. The renderContextData property
  45329. // can be changed by another render pass before the buffer.mapAsyc() completes.
  45330. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  45331. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  45332. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  45333. //
  45334. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  45335. renderContextData.occlusionQuerySet = occlusionQuerySet;
  45336. renderContextData.occlusionQueryIndex = 0;
  45337. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  45338. renderContextData.lastOcclusionObject = null;
  45339. }
  45340. let descriptor;
  45341. if ( renderContext.textures === null ) {
  45342. descriptor = this._getDefaultRenderPassDescriptor();
  45343. } else {
  45344. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  45345. }
  45346. this.initTimestampQuery( renderContext, descriptor );
  45347. descriptor.occlusionQuerySet = occlusionQuerySet;
  45348. const depthStencilAttachment = descriptor.depthStencilAttachment;
  45349. if ( renderContext.textures !== null ) {
  45350. const colorAttachments = descriptor.colorAttachments;
  45351. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  45352. const colorAttachment = colorAttachments[ i ];
  45353. if ( renderContext.clearColor ) {
  45354. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  45355. colorAttachment.loadOp = GPULoadOp.Clear;
  45356. colorAttachment.storeOp = GPUStoreOp.Store;
  45357. } else {
  45358. colorAttachment.loadOp = GPULoadOp.Load;
  45359. colorAttachment.storeOp = GPUStoreOp.Store;
  45360. }
  45361. }
  45362. } else {
  45363. const colorAttachment = descriptor.colorAttachments[ 0 ];
  45364. if ( renderContext.clearColor ) {
  45365. colorAttachment.clearValue = renderContext.clearColorValue;
  45366. colorAttachment.loadOp = GPULoadOp.Clear;
  45367. colorAttachment.storeOp = GPUStoreOp.Store;
  45368. } else {
  45369. colorAttachment.loadOp = GPULoadOp.Load;
  45370. colorAttachment.storeOp = GPUStoreOp.Store;
  45371. }
  45372. }
  45373. //
  45374. if ( renderContext.depth ) {
  45375. if ( renderContext.clearDepth ) {
  45376. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  45377. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  45378. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45379. } else {
  45380. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45381. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45382. }
  45383. }
  45384. if ( renderContext.stencil ) {
  45385. if ( renderContext.clearStencil ) {
  45386. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  45387. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  45388. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45389. } else {
  45390. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45391. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45392. }
  45393. }
  45394. //
  45395. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  45396. const currentPass = encoder.beginRenderPass( descriptor );
  45397. //
  45398. renderContextData.descriptor = descriptor;
  45399. renderContextData.encoder = encoder;
  45400. renderContextData.currentPass = currentPass;
  45401. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45402. renderContextData.renderBundles = [];
  45403. //
  45404. if ( renderContext.viewport ) {
  45405. this.updateViewport( renderContext );
  45406. }
  45407. if ( renderContext.scissor ) {
  45408. const { x, y, width, height } = renderContext.scissorValue;
  45409. currentPass.setScissorRect( x, y, width, height );
  45410. }
  45411. }
  45412. /**
  45413. * This method is executed at the end of a render call and finalizes work
  45414. * after draw calls.
  45415. *
  45416. * @param {RenderContext} renderContext - The render context.
  45417. */
  45418. finishRender( renderContext ) {
  45419. const renderContextData = this.get( renderContext );
  45420. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45421. if ( renderContextData.renderBundles.length > 0 ) {
  45422. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  45423. }
  45424. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  45425. renderContextData.currentPass.endOcclusionQuery();
  45426. }
  45427. renderContextData.currentPass.end();
  45428. if ( occlusionQueryCount > 0 ) {
  45429. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  45430. //
  45431. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  45432. if ( queryResolveBuffer === undefined ) {
  45433. queryResolveBuffer = this.device.createBuffer(
  45434. {
  45435. size: bufferSize,
  45436. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  45437. }
  45438. );
  45439. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  45440. }
  45441. //
  45442. const readBuffer = this.device.createBuffer(
  45443. {
  45444. size: bufferSize,
  45445. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  45446. }
  45447. );
  45448. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  45449. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  45450. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  45451. renderContextData.occlusionQueryBuffer = readBuffer;
  45452. //
  45453. this.resolveOccludedAsync( renderContext );
  45454. }
  45455. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  45456. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  45457. //
  45458. if ( renderContext.textures !== null ) {
  45459. const textures = renderContext.textures;
  45460. for ( let i = 0; i < textures.length; i ++ ) {
  45461. const texture = textures[ i ];
  45462. if ( texture.generateMipmaps === true ) {
  45463. this.textureUtils.generateMipmaps( texture );
  45464. }
  45465. }
  45466. }
  45467. }
  45468. /**
  45469. * Returns `true` if the given 3D object is fully occluded by other
  45470. * 3D objects in the scene.
  45471. *
  45472. * @param {RenderContext} renderContext - The render context.
  45473. * @param {Object3D} object - The 3D object to test.
  45474. * @return {Boolean} Whether the 3D object is fully occluded or not.
  45475. */
  45476. isOccluded( renderContext, object ) {
  45477. const renderContextData = this.get( renderContext );
  45478. return renderContextData.occluded && renderContextData.occluded.has( object );
  45479. }
  45480. /**
  45481. * This method processes the result of occlusion queries and writes it
  45482. * into render context data.
  45483. *
  45484. * @async
  45485. * @param {RenderContext} renderContext - The render context.
  45486. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  45487. */
  45488. async resolveOccludedAsync( renderContext ) {
  45489. const renderContextData = this.get( renderContext );
  45490. // handle occlusion query results
  45491. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  45492. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  45493. const occluded = new WeakSet();
  45494. renderContextData.currentOcclusionQueryObjects = null;
  45495. renderContextData.currentOcclusionQueryBuffer = null;
  45496. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  45497. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  45498. const results = new BigUint64Array( buffer );
  45499. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  45500. if ( results[ i ] === BigInt( 0 ) ) {
  45501. occluded.add( currentOcclusionQueryObjects[ i ] );
  45502. }
  45503. }
  45504. currentOcclusionQueryBuffer.destroy();
  45505. renderContextData.occluded = occluded;
  45506. }
  45507. }
  45508. /**
  45509. * Updates the viewport with the values from the given render context.
  45510. *
  45511. * @param {RenderContext} renderContext - The render context.
  45512. */
  45513. updateViewport( renderContext ) {
  45514. const { currentPass } = this.get( renderContext );
  45515. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  45516. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  45517. }
  45518. /**
  45519. * Performs a clear operation.
  45520. *
  45521. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  45522. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  45523. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  45524. * @param {RenderContext?} [renderTargetContext=null] - The render context of the current set render target.
  45525. */
  45526. clear( color, depth, stencil, renderTargetContext = null ) {
  45527. const device = this.device;
  45528. const renderer = this.renderer;
  45529. let colorAttachments = [];
  45530. let depthStencilAttachment;
  45531. let clearValue;
  45532. let supportsDepth;
  45533. let supportsStencil;
  45534. if ( color ) {
  45535. const clearColor = this.getClearColor();
  45536. if ( this.renderer.alpha === true ) {
  45537. // premultiply alpha
  45538. const a = clearColor.a;
  45539. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  45540. } else {
  45541. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  45542. }
  45543. }
  45544. if ( renderTargetContext === null ) {
  45545. supportsDepth = renderer.depth;
  45546. supportsStencil = renderer.stencil;
  45547. const descriptor = this._getDefaultRenderPassDescriptor();
  45548. if ( color ) {
  45549. colorAttachments = descriptor.colorAttachments;
  45550. const colorAttachment = colorAttachments[ 0 ];
  45551. colorAttachment.clearValue = clearValue;
  45552. colorAttachment.loadOp = GPULoadOp.Clear;
  45553. colorAttachment.storeOp = GPUStoreOp.Store;
  45554. }
  45555. if ( supportsDepth || supportsStencil ) {
  45556. depthStencilAttachment = descriptor.depthStencilAttachment;
  45557. }
  45558. } else {
  45559. supportsDepth = renderTargetContext.depth;
  45560. supportsStencil = renderTargetContext.stencil;
  45561. if ( color ) {
  45562. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear, clearValue } );
  45563. colorAttachments = descriptor.colorAttachments;
  45564. }
  45565. if ( supportsDepth || supportsStencil ) {
  45566. const depthTextureData = this.get( renderTargetContext.depthTexture );
  45567. depthStencilAttachment = {
  45568. view: depthTextureData.texture.createView()
  45569. };
  45570. }
  45571. }
  45572. //
  45573. if ( supportsDepth ) {
  45574. if ( depth ) {
  45575. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  45576. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  45577. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45578. } else {
  45579. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45580. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45581. }
  45582. }
  45583. //
  45584. if ( supportsStencil ) {
  45585. if ( stencil ) {
  45586. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  45587. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  45588. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45589. } else {
  45590. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45591. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45592. }
  45593. }
  45594. //
  45595. const encoder = device.createCommandEncoder( { label: 'clear' } );
  45596. const currentPass = encoder.beginRenderPass( {
  45597. colorAttachments,
  45598. depthStencilAttachment
  45599. } );
  45600. currentPass.end();
  45601. device.queue.submit( [ encoder.finish() ] );
  45602. }
  45603. // compute
  45604. /**
  45605. * This method is executed at the beginning of a compute call and
  45606. * prepares the state for upcoming compute tasks.
  45607. *
  45608. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45609. */
  45610. beginCompute( computeGroup ) {
  45611. const groupGPU = this.get( computeGroup );
  45612. const descriptor = {
  45613. label: 'computeGroup_' + computeGroup.id
  45614. };
  45615. this.initTimestampQuery( computeGroup, descriptor );
  45616. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  45617. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  45618. }
  45619. /**
  45620. * Executes a compute command for the given compute node.
  45621. *
  45622. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  45623. * @param {Node} computeNode - The compute node.
  45624. * @param {Array<BindGroup>} bindings - The bindings.
  45625. * @param {ComputePipeline} pipeline - The compute pipeline.
  45626. */
  45627. compute( computeGroup, computeNode, bindings, pipeline ) {
  45628. const { passEncoderGPU } = this.get( computeGroup );
  45629. // pipeline
  45630. const pipelineGPU = this.get( pipeline ).pipeline;
  45631. passEncoderGPU.setPipeline( pipelineGPU );
  45632. // bind groups
  45633. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45634. const bindGroup = bindings[ i ];
  45635. const bindingsData = this.get( bindGroup );
  45636. passEncoderGPU.setBindGroup( i, bindingsData.group );
  45637. }
  45638. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  45639. const computeNodeData = this.get( computeNode );
  45640. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  45641. const { dispatchSize } = computeNodeData;
  45642. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  45643. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  45644. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  45645. } else {
  45646. dispatchSize.x = computeNode.dispatchCount;
  45647. }
  45648. passEncoderGPU.dispatchWorkgroups(
  45649. dispatchSize.x,
  45650. dispatchSize.y,
  45651. dispatchSize.z
  45652. );
  45653. }
  45654. /**
  45655. * This method is executed at the end of a compute call and
  45656. * finalizes work after compute tasks.
  45657. *
  45658. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45659. */
  45660. finishCompute( computeGroup ) {
  45661. const groupData = this.get( computeGroup );
  45662. groupData.passEncoderGPU.end();
  45663. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  45664. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  45665. }
  45666. /**
  45667. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  45668. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  45669. *
  45670. * @async
  45671. * @return {Promise} A Promise that resolves when synchronization has been finished.
  45672. */
  45673. async waitForGPU() {
  45674. await this.device.queue.onSubmittedWorkDone();
  45675. }
  45676. // render object
  45677. /**
  45678. * Executes a draw command for the given render object.
  45679. *
  45680. * @param {RenderObject} renderObject - The render object to draw.
  45681. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  45682. */
  45683. draw( renderObject, info ) {
  45684. const { object, context, pipeline } = renderObject;
  45685. const bindings = renderObject.getBindings();
  45686. const renderContextData = this.get( context );
  45687. const pipelineGPU = this.get( pipeline ).pipeline;
  45688. const currentSets = renderContextData.currentSets;
  45689. const passEncoderGPU = renderContextData.currentPass;
  45690. const drawParams = renderObject.getDrawParameters();
  45691. if ( drawParams === null ) return;
  45692. // pipeline
  45693. if ( currentSets.pipeline !== pipelineGPU ) {
  45694. passEncoderGPU.setPipeline( pipelineGPU );
  45695. currentSets.pipeline = pipelineGPU;
  45696. }
  45697. // bind groups
  45698. const currentBindingGroups = currentSets.bindingGroups;
  45699. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45700. const bindGroup = bindings[ i ];
  45701. const bindingsData = this.get( bindGroup );
  45702. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  45703. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  45704. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  45705. }
  45706. }
  45707. // attributes
  45708. const index = renderObject.getIndex();
  45709. const hasIndex = ( index !== null );
  45710. // index
  45711. if ( hasIndex === true ) {
  45712. if ( currentSets.index !== index ) {
  45713. const buffer = this.get( index ).buffer;
  45714. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  45715. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  45716. currentSets.index = index;
  45717. }
  45718. }
  45719. // vertex buffers
  45720. const vertexBuffers = renderObject.getVertexBuffers();
  45721. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  45722. const vertexBuffer = vertexBuffers[ i ];
  45723. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  45724. const buffer = this.get( vertexBuffer ).buffer;
  45725. passEncoderGPU.setVertexBuffer( i, buffer );
  45726. currentSets.attributes[ i ] = vertexBuffer;
  45727. }
  45728. }
  45729. // occlusion queries - handle multiple consecutive draw calls for an object
  45730. if ( renderContextData.occlusionQuerySet !== undefined ) {
  45731. const lastObject = renderContextData.lastOcclusionObject;
  45732. if ( lastObject !== object ) {
  45733. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  45734. passEncoderGPU.endOcclusionQuery();
  45735. renderContextData.occlusionQueryIndex ++;
  45736. }
  45737. if ( object.occlusionTest === true ) {
  45738. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  45739. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  45740. }
  45741. renderContextData.lastOcclusionObject = object;
  45742. }
  45743. }
  45744. // draw
  45745. if ( object.isBatchedMesh === true ) {
  45746. const starts = object._multiDrawStarts;
  45747. const counts = object._multiDrawCounts;
  45748. const drawCount = object._multiDrawCount;
  45749. const drawInstances = object._multiDrawInstances;
  45750. for ( let i = 0; i < drawCount; i ++ ) {
  45751. const count = drawInstances ? drawInstances[ i ] : 1;
  45752. const firstInstance = count > 1 ? 0 : i;
  45753. if ( hasIndex === true ) {
  45754. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  45755. } else {
  45756. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  45757. }
  45758. }
  45759. } else if ( hasIndex === true ) {
  45760. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  45761. const indirect = renderObject.getIndirect();
  45762. if ( indirect !== null ) {
  45763. const buffer = this.get( indirect ).buffer;
  45764. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  45765. } else {
  45766. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  45767. }
  45768. info.update( object, indexCount, instanceCount );
  45769. } else {
  45770. const { vertexCount, instanceCount, firstVertex } = drawParams;
  45771. const indirect = renderObject.getIndirect();
  45772. if ( indirect !== null ) {
  45773. const buffer = this.get( indirect ).buffer;
  45774. passEncoderGPU.drawIndirect( buffer, 0 );
  45775. } else {
  45776. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  45777. }
  45778. info.update( object, vertexCount, instanceCount );
  45779. }
  45780. }
  45781. // cache key
  45782. /**
  45783. * Returns `true` if the render pipeline requires an update.
  45784. *
  45785. * @param {RenderObject} renderObject - The render object.
  45786. * @return {Boolean} Whether the render pipeline requires an update or not.
  45787. */
  45788. needsRenderUpdate( renderObject ) {
  45789. const data = this.get( renderObject );
  45790. const { object, material } = renderObject;
  45791. const utils = this.utils;
  45792. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  45793. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  45794. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  45795. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  45796. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  45797. let needsUpdate = false;
  45798. if ( data.material !== material || data.materialVersion !== material.version ||
  45799. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  45800. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  45801. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  45802. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  45803. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  45804. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  45805. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  45806. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  45807. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  45808. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  45809. data.primitiveTopology !== primitiveTopology ||
  45810. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  45811. ) {
  45812. data.material = material; data.materialVersion = material.version;
  45813. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  45814. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  45815. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  45816. data.colorWrite = material.colorWrite;
  45817. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  45818. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  45819. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  45820. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  45821. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  45822. data.sampleCount = sampleCount;
  45823. data.colorSpace = colorSpace;
  45824. data.colorFormat = colorFormat;
  45825. data.depthStencilFormat = depthStencilFormat;
  45826. data.primitiveTopology = primitiveTopology;
  45827. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  45828. needsUpdate = true;
  45829. }
  45830. return needsUpdate;
  45831. }
  45832. /**
  45833. * Returns a cache key that is used to identify render pipelines.
  45834. *
  45835. * @param {RenderObject} renderObject - The render object.
  45836. * @return {String} The cache key.
  45837. */
  45838. getRenderCacheKey( renderObject ) {
  45839. const { object, material } = renderObject;
  45840. const utils = this.utils;
  45841. const renderContext = renderObject.context;
  45842. return [
  45843. material.transparent, material.blending, material.premultipliedAlpha,
  45844. material.blendSrc, material.blendDst, material.blendEquation,
  45845. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  45846. material.colorWrite,
  45847. material.depthWrite, material.depthTest, material.depthFunc,
  45848. material.stencilWrite, material.stencilFunc,
  45849. material.stencilFail, material.stencilZFail, material.stencilZPass,
  45850. material.stencilFuncMask, material.stencilWriteMask,
  45851. material.side,
  45852. utils.getSampleCountRenderContext( renderContext ),
  45853. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  45854. utils.getPrimitiveTopology( object, material ),
  45855. renderObject.getGeometryCacheKey(),
  45856. renderObject.clippingContextCacheKey
  45857. ].join();
  45858. }
  45859. // textures
  45860. /**
  45861. * Creates a GPU sampler for the given texture.
  45862. *
  45863. * @param {Texture} texture - The texture to create the sampler for.
  45864. */
  45865. createSampler( texture ) {
  45866. this.textureUtils.createSampler( texture );
  45867. }
  45868. /**
  45869. * Destroys the GPU sampler for the given texture.
  45870. *
  45871. * @param {Texture} texture - The texture to destroy the sampler for.
  45872. */
  45873. destroySampler( texture ) {
  45874. this.textureUtils.destroySampler( texture );
  45875. }
  45876. /**
  45877. * Creates a default texture for the given texture that can be used
  45878. * as a placeholder until the actual texture is ready for usage.
  45879. *
  45880. * @param {Texture} texture - The texture to create a default texture for.
  45881. */
  45882. createDefaultTexture( texture ) {
  45883. this.textureUtils.createDefaultTexture( texture );
  45884. }
  45885. /**
  45886. * Defines a texture on the GPU for the given texture object.
  45887. *
  45888. * @param {Texture} texture - The texture.
  45889. * @param {Object} [options={}] - Optional configuration parameter.
  45890. */
  45891. createTexture( texture, options ) {
  45892. this.textureUtils.createTexture( texture, options );
  45893. }
  45894. /**
  45895. * Uploads the updated texture data to the GPU.
  45896. *
  45897. * @param {Texture} texture - The texture.
  45898. * @param {Object} [options={}] - Optional configuration parameter.
  45899. */
  45900. updateTexture( texture, options ) {
  45901. this.textureUtils.updateTexture( texture, options );
  45902. }
  45903. /**
  45904. * Generates mipmaps for the given texture.
  45905. *
  45906. * @param {Texture} texture - The texture.
  45907. */
  45908. generateMipmaps( texture ) {
  45909. this.textureUtils.generateMipmaps( texture );
  45910. }
  45911. /**
  45912. * Destroys the GPU data for the given texture object.
  45913. *
  45914. * @param {Texture} texture - The texture.
  45915. */
  45916. destroyTexture( texture ) {
  45917. this.textureUtils.destroyTexture( texture );
  45918. }
  45919. /**
  45920. * Returns texture data as a typed array.
  45921. *
  45922. * @async
  45923. * @param {Texture} texture - The texture to copy.
  45924. * @param {Number} x - The x coordinate of the copy origin.
  45925. * @param {Number} y - The y coordinate of the copy origin.
  45926. * @param {Number} width - The width of the copy.
  45927. * @param {Number} height - The height of the copy.
  45928. * @param {Number} faceIndex - The face index.
  45929. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45930. */
  45931. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  45932. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  45933. }
  45934. /**
  45935. * Inits a time stamp query for the given render context.
  45936. *
  45937. * @param {RenderContext} renderContext - The render context.
  45938. * @param {Object} descriptor - The query descriptor.
  45939. */
  45940. initTimestampQuery( renderContext, descriptor ) {
  45941. if ( ! this.trackTimestamp ) return;
  45942. const renderContextData = this.get( renderContext );
  45943. // init query set if not exists
  45944. if ( ! renderContextData.timestampQuerySet ) {
  45945. const type = renderContext.isComputeNode ? 'compute' : 'render';
  45946. renderContextData.timestampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  45947. }
  45948. // augment descriptor
  45949. descriptor.timestampWrites = {
  45950. querySet: renderContextData.timestampQuerySet,
  45951. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  45952. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  45953. };
  45954. }
  45955. /**
  45956. * Prepares the timestamp buffer.
  45957. *
  45958. * @param {RenderContext} renderContext - The render context.
  45959. * @param {GPUCommandEncoder} encoder - The command encoder.
  45960. */
  45961. prepareTimestampBuffer( renderContext, encoder ) {
  45962. if ( ! this.trackTimestamp ) return;
  45963. const renderContextData = this.get( renderContext );
  45964. const size = 2 * BigUint64Array.BYTES_PER_ELEMENT;
  45965. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  45966. renderContextData.currentTimestampQueryBuffers = {
  45967. resolveBuffer: this.device.createBuffer( {
  45968. label: 'timestamp resolve buffer',
  45969. size: size,
  45970. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  45971. } ),
  45972. resultBuffer: this.device.createBuffer( {
  45973. label: 'timestamp result buffer',
  45974. size: size,
  45975. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  45976. } )
  45977. };
  45978. }
  45979. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  45980. encoder.resolveQuerySet( renderContextData.timestampQuerySet, 0, 2, resolveBuffer, 0 );
  45981. if ( resultBuffer.mapState === 'unmapped' ) {
  45982. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  45983. }
  45984. }
  45985. /**
  45986. * Resolves the time stamp for the given render context and type.
  45987. *
  45988. * @async
  45989. * @param {RenderContext} renderContext - The render context.
  45990. * @param {String} type - The render context.
  45991. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  45992. */
  45993. async resolveTimestampAsync( renderContext, type = 'render' ) {
  45994. if ( ! this.trackTimestamp ) return;
  45995. const renderContextData = this.get( renderContext );
  45996. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  45997. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  45998. if ( resultBuffer.mapState === 'unmapped' ) {
  45999. await resultBuffer.mapAsync( GPUMapMode.READ );
  46000. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  46001. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  46002. this.renderer.info.updateTimestamp( type, duration );
  46003. resultBuffer.unmap();
  46004. }
  46005. }
  46006. // node builder
  46007. /**
  46008. * Returns a node builder for the given render object.
  46009. *
  46010. * @param {RenderObject} object - The render object.
  46011. * @param {Renderer} renderer - The renderer.
  46012. * @return {WGSLNodeBuilder} The node builder.
  46013. */
  46014. createNodeBuilder( object, renderer ) {
  46015. return new WGSLNodeBuilder( object, renderer );
  46016. }
  46017. // program
  46018. /**
  46019. * Creates a shader program from the given programmable stage.
  46020. *
  46021. * @param {ProgrammableStage} program - The programmable stage.
  46022. */
  46023. createProgram( program ) {
  46024. const programGPU = this.get( program );
  46025. programGPU.module = {
  46026. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  46027. entryPoint: 'main'
  46028. };
  46029. }
  46030. /**
  46031. * Destroys the shader program of the given programmable stage.
  46032. *
  46033. * @param {ProgrammableStage} program - The programmable stage.
  46034. */
  46035. destroyProgram( program ) {
  46036. this.delete( program );
  46037. }
  46038. // pipelines
  46039. /**
  46040. * Creates a render pipeline for the given render object.
  46041. *
  46042. * @param {RenderObject} renderObject - The render object.
  46043. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  46044. */
  46045. createRenderPipeline( renderObject, promises ) {
  46046. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  46047. }
  46048. /**
  46049. * Creates a compute pipeline for the given compute node.
  46050. *
  46051. * @param {ComputePipeline} computePipeline - The compute pipeline.
  46052. * @param {Array<BindGroup>} bindings - The bindings.
  46053. */
  46054. createComputePipeline( computePipeline, bindings ) {
  46055. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  46056. }
  46057. /**
  46058. * Prepares the state for encoding render bundles.
  46059. *
  46060. * @param {RenderContext} renderContext - The render context.
  46061. */
  46062. beginBundle( renderContext ) {
  46063. const renderContextData = this.get( renderContext );
  46064. renderContextData._currentPass = renderContextData.currentPass;
  46065. renderContextData._currentSets = renderContextData.currentSets;
  46066. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  46067. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  46068. }
  46069. /**
  46070. * After processing render bundles this method finalizes related work.
  46071. *
  46072. * @param {RenderContext} renderContext - The render context.
  46073. * @param {RenderBundle} bundle - The render bundle.
  46074. */
  46075. finishBundle( renderContext, bundle ) {
  46076. const renderContextData = this.get( renderContext );
  46077. const bundleEncoder = renderContextData.currentPass;
  46078. const bundleGPU = bundleEncoder.finish();
  46079. this.get( bundle ).bundleGPU = bundleGPU;
  46080. // restore render pass state
  46081. renderContextData.currentSets = renderContextData._currentSets;
  46082. renderContextData.currentPass = renderContextData._currentPass;
  46083. }
  46084. /**
  46085. * Adds a render bundle to the render context data.
  46086. *
  46087. * @param {RenderContext} renderContext - The render context.
  46088. * @param {RenderBundle} bundle - The render bundle to add.
  46089. */
  46090. addBundle( renderContext, bundle ) {
  46091. const renderContextData = this.get( renderContext );
  46092. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  46093. }
  46094. // bindings
  46095. /**
  46096. * Creates bindings from the given bind group definition.
  46097. *
  46098. * @param {BindGroup} bindGroup - The bind group.
  46099. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46100. * @param {Number} cacheIndex - The cache index.
  46101. * @param {Number} version - The version.
  46102. */
  46103. createBindings( bindGroup, bindings, cacheIndex, version ) {
  46104. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  46105. }
  46106. /**
  46107. * Updates the given bind group definition.
  46108. *
  46109. * @param {BindGroup} bindGroup - The bind group.
  46110. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46111. * @param {Number} cacheIndex - The cache index.
  46112. * @param {Number} version - The version.
  46113. */
  46114. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  46115. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  46116. }
  46117. /**
  46118. * Updates a buffer binding.
  46119. *
  46120. * @param {Buffer} binding - The buffer binding to update.
  46121. */
  46122. updateBinding( binding ) {
  46123. this.bindingUtils.updateBinding( binding );
  46124. }
  46125. // attributes
  46126. /**
  46127. * Creates the buffer of an indexed shader attribute.
  46128. *
  46129. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  46130. */
  46131. createIndexAttribute( attribute ) {
  46132. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  46133. }
  46134. /**
  46135. * Creates the GPU buffer of a shader attribute.
  46136. *
  46137. * @param {BufferAttribute} attribute - The buffer attribute.
  46138. */
  46139. createAttribute( attribute ) {
  46140. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  46141. }
  46142. /**
  46143. * Creates the GPU buffer of a storage attribute.
  46144. *
  46145. * @param {BufferAttribute} attribute - The buffer attribute.
  46146. */
  46147. createStorageAttribute( attribute ) {
  46148. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  46149. }
  46150. /**
  46151. * Creates the GPU buffer of an indirect storage attribute.
  46152. *
  46153. * @param {BufferAttribute} attribute - The buffer attribute.
  46154. */
  46155. createIndirectStorageAttribute( attribute ) {
  46156. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  46157. }
  46158. /**
  46159. * Updates the GPU buffer of a shader attribute.
  46160. *
  46161. * @param {BufferAttribute} attribute - The buffer attribute to update.
  46162. */
  46163. updateAttribute( attribute ) {
  46164. this.attributeUtils.updateAttribute( attribute );
  46165. }
  46166. /**
  46167. * Destroys the GPU buffer of a shader attribute.
  46168. *
  46169. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  46170. */
  46171. destroyAttribute( attribute ) {
  46172. this.attributeUtils.destroyAttribute( attribute );
  46173. }
  46174. // canvas
  46175. /**
  46176. * Triggers an update of the default render pass descriptor.
  46177. */
  46178. updateSize() {
  46179. this.colorBuffer = this.textureUtils.getColorBuffer();
  46180. this.defaultRenderPassdescriptor = null;
  46181. }
  46182. // utils public
  46183. /**
  46184. * Returns the maximum anisotropy texture filtering value.
  46185. *
  46186. * @return {Number} The maximum anisotropy texture filtering value.
  46187. */
  46188. getMaxAnisotropy() {
  46189. return 16;
  46190. }
  46191. /**
  46192. * Checks if the given feature is supported by the backend.
  46193. *
  46194. * @param {String} name - The feature's name.
  46195. * @return {Boolean} Whether the feature is supported or not.
  46196. */
  46197. hasFeature( name ) {
  46198. return this.device.features.has( name );
  46199. }
  46200. /**
  46201. * Copies data of the given source texture to the given destination texture.
  46202. *
  46203. * @param {Texture} srcTexture - The source texture.
  46204. * @param {Texture} dstTexture - The destination texture.
  46205. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  46206. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  46207. * @param {Number} [level=0] - The mip level to copy.
  46208. */
  46209. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  46210. let dstX = 0;
  46211. let dstY = 0;
  46212. let dstLayer = 0;
  46213. let srcX = 0;
  46214. let srcY = 0;
  46215. let srcLayer = 0;
  46216. let srcWidth = srcTexture.image.width;
  46217. let srcHeight = srcTexture.image.height;
  46218. if ( srcRegion !== null ) {
  46219. srcX = srcRegion.x;
  46220. srcY = srcRegion.y;
  46221. srcLayer = srcRegion.z || 0;
  46222. srcWidth = srcRegion.width;
  46223. srcHeight = srcRegion.height;
  46224. }
  46225. if ( dstPosition !== null ) {
  46226. dstX = dstPosition.x;
  46227. dstY = dstPosition.y;
  46228. dstLayer = dstPosition.z || 0;
  46229. }
  46230. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  46231. const sourceGPU = this.get( srcTexture ).texture;
  46232. const destinationGPU = this.get( dstTexture ).texture;
  46233. encoder.copyTextureToTexture(
  46234. {
  46235. texture: sourceGPU,
  46236. mipLevel: level,
  46237. origin: { x: srcX, y: srcY, z: srcLayer }
  46238. },
  46239. {
  46240. texture: destinationGPU,
  46241. mipLevel: level,
  46242. origin: { x: dstX, y: dstY, z: dstLayer }
  46243. },
  46244. [
  46245. srcWidth,
  46246. srcHeight,
  46247. 1
  46248. ]
  46249. );
  46250. this.device.queue.submit( [ encoder.finish() ] );
  46251. }
  46252. /**
  46253. * Copies the current bound framebuffer to the given texture.
  46254. *
  46255. * @param {Texture} texture - The destination texture.
  46256. * @param {RenderContext} renderContext - The render context.
  46257. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  46258. */
  46259. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  46260. const renderContextData = this.get( renderContext );
  46261. let sourceGPU = null;
  46262. if ( renderContext.renderTarget ) {
  46263. if ( texture.isDepthTexture ) {
  46264. sourceGPU = this.get( renderContext.depthTexture ).texture;
  46265. } else {
  46266. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  46267. }
  46268. } else {
  46269. if ( texture.isDepthTexture ) {
  46270. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  46271. } else {
  46272. sourceGPU = this.context.getCurrentTexture();
  46273. }
  46274. }
  46275. const destinationGPU = this.get( texture ).texture;
  46276. if ( sourceGPU.format !== destinationGPU.format ) {
  46277. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  46278. return;
  46279. }
  46280. let encoder;
  46281. if ( renderContextData.currentPass ) {
  46282. renderContextData.currentPass.end();
  46283. encoder = renderContextData.encoder;
  46284. } else {
  46285. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  46286. }
  46287. encoder.copyTextureToTexture(
  46288. {
  46289. texture: sourceGPU,
  46290. origin: [ rectangle.x, rectangle.y, 0 ],
  46291. },
  46292. {
  46293. texture: destinationGPU
  46294. },
  46295. [
  46296. rectangle.z,
  46297. rectangle.w
  46298. ]
  46299. );
  46300. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  46301. if ( renderContextData.currentPass ) {
  46302. const { descriptor } = renderContextData;
  46303. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  46304. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  46305. }
  46306. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  46307. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  46308. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  46309. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  46310. if ( renderContext.viewport ) {
  46311. this.updateViewport( renderContext );
  46312. }
  46313. if ( renderContext.scissor ) {
  46314. const { x, y, width, height } = renderContext.scissorValue;
  46315. renderContextData.currentPass.setScissorRect( x, y, width, height );
  46316. }
  46317. } else {
  46318. this.device.queue.submit( [ encoder.finish() ] );
  46319. }
  46320. }
  46321. }
  46322. class IESSpotLight extends SpotLight {
  46323. constructor( color, intensity, distance, angle, penumbra, decay ) {
  46324. super( color, intensity, distance, angle, penumbra, decay );
  46325. this.iesMap = null;
  46326. }
  46327. copy( source, recursive ) {
  46328. super.copy( source, recursive );
  46329. this.iesMap = source.iesMap;
  46330. return this;
  46331. }
  46332. }
  46333. /**
  46334. * This version of a node library represents a basic version
  46335. * just focusing on lights and tone mapping techniques.
  46336. *
  46337. * @private
  46338. * @augments NodeLibrary
  46339. */
  46340. class BasicNodeLibrary extends NodeLibrary {
  46341. /**
  46342. * Constructs a new basic node library.
  46343. */
  46344. constructor() {
  46345. super();
  46346. this.addLight( PointLightNode, PointLight );
  46347. this.addLight( DirectionalLightNode, DirectionalLight );
  46348. this.addLight( RectAreaLightNode, RectAreaLight );
  46349. this.addLight( SpotLightNode, SpotLight );
  46350. this.addLight( AmbientLightNode, AmbientLight );
  46351. this.addLight( HemisphereLightNode, HemisphereLight );
  46352. this.addLight( LightProbeNode, LightProbe );
  46353. this.addLight( IESSpotLightNode, IESSpotLight );
  46354. this.addToneMapping( linearToneMapping, LinearToneMapping );
  46355. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  46356. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  46357. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  46358. this.addToneMapping( agxToneMapping, AgXToneMapping );
  46359. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  46360. }
  46361. }
  46362. /**
  46363. * This alternative version of {@link WebGPURenderer} only supports node materials.
  46364. * So classes like `MeshBasicMaterial` are not compatible.
  46365. *
  46366. * @augments module:Renderer~Renderer
  46367. */
  46368. class WebGPURenderer extends Renderer {
  46369. /**
  46370. * Constructs a new WebGPU renderer.
  46371. *
  46372. * @param {Object} parameters - The configuration parameter.
  46373. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  46374. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  46375. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  46376. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  46377. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  46378. * @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
  46379. * to overwrite the default.
  46380. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses it
  46381. * WebGL 2 backend no matter if WebGPU is supported or not.
  46382. */
  46383. constructor( parameters = {} ) {
  46384. let BackendClass;
  46385. if ( parameters.forceWebGL ) {
  46386. BackendClass = WebGLBackend;
  46387. } else {
  46388. BackendClass = WebGPUBackend;
  46389. parameters.getFallback = () => {
  46390. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  46391. return new WebGLBackend( parameters );
  46392. };
  46393. }
  46394. const backend = new BackendClass( parameters );
  46395. super( backend, parameters );
  46396. /**
  46397. * The generic default value is overwritten with the
  46398. * standard node library for type mapping. Material
  46399. * mapping is not supported with this version.
  46400. *
  46401. * @type {BasicNodeLibrary}
  46402. */
  46403. this.library = new BasicNodeLibrary();
  46404. /**
  46405. * This flag can be used for type testing.
  46406. *
  46407. * @type {Boolean}
  46408. * @readonly
  46409. * @default true
  46410. */
  46411. this.isWebGPURenderer = true;
  46412. }
  46413. }
  46414. /**
  46415. * A specialized group which enables applications access to the
  46416. * Render Bundle API of WebGPU. The group with all its descendant nodes
  46417. * are considered as one render bundle and processed as such by
  46418. * the renderer.
  46419. *
  46420. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  46421. * With a WebGL backend, the group can technically be rendered but without
  46422. * any performance improvements.
  46423. *
  46424. * @augments Group
  46425. */
  46426. class BundleGroup extends Group {
  46427. /**
  46428. * Constructs a new bundle group.
  46429. */
  46430. constructor() {
  46431. super();
  46432. /**
  46433. * This flag can be used for type testing.
  46434. *
  46435. * @type {Boolean}
  46436. * @readonly
  46437. * @default true
  46438. */
  46439. this.isBundleGroup = true;
  46440. /**
  46441. * This property is only relevant for detecting types
  46442. * during serialization/deserialization. It should always
  46443. * match the class name.
  46444. *
  46445. * @type {String}
  46446. * @readonly
  46447. * @default 'BundleGroup'
  46448. */
  46449. this.type = 'BundleGroup';
  46450. /**
  46451. * Whether the bundle is static or not. When set to `true`, the structure
  46452. * is assumed to be static and does not change. E.g. no new objects are
  46453. * added to the group
  46454. *
  46455. * If a change is required, an update can still be forced by setting the
  46456. * `needsUpdate` flag to `true`.
  46457. *
  46458. * @type {Boolean}
  46459. * @default true
  46460. */
  46461. this.static = true;
  46462. /**
  46463. * The bundle group's version.
  46464. *
  46465. * @type {Number}
  46466. * @readonly
  46467. * @default 0
  46468. */
  46469. this.version = 0;
  46470. }
  46471. /**
  46472. * Set this property to `true` when the bundle group has changed.
  46473. *
  46474. * @type {Boolean}
  46475. * @default false
  46476. * @param {Boolean} value
  46477. */
  46478. set needsUpdate( value ) {
  46479. if ( value === true ) this.version ++;
  46480. }
  46481. }
  46482. /**
  46483. * This module is responsible to manage the post processing setups in apps.
  46484. * You usually create a single instance of this class and use it to define
  46485. * the output of your post processing effect chain.
  46486. * ```js
  46487. * const postProcessing = new PostProcessing( renderer );
  46488. *
  46489. * const scenePass = pass( scene, camera );
  46490. *
  46491. * postProcessing.outputNode = scenePass;
  46492. * ```
  46493. */
  46494. class PostProcessing {
  46495. /**
  46496. * Constructs a new post processing management module.
  46497. *
  46498. * @param {Renderer} renderer - A reference to the renderer.
  46499. * @param {Node<vec4>} outputNode - An optional output node.
  46500. */
  46501. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  46502. /**
  46503. * A reference to the renderer.
  46504. *
  46505. * @type {Renderer}
  46506. */
  46507. this.renderer = renderer;
  46508. /**
  46509. * A node which defines the final output of the post
  46510. * processing. This is usually the last node in a chain
  46511. * of effect nodes.
  46512. *
  46513. * @type {Node<vec4>}
  46514. */
  46515. this.outputNode = outputNode;
  46516. /**
  46517. * Whether the default output tone mapping and color
  46518. * space transformation should be enabled or not.
  46519. *
  46520. * It is enabled by default by it must be disabled when
  46521. * effects must be executed after tone mapping and color
  46522. * space conversion. A typical example is FXAA which
  46523. * requires sRGB input.
  46524. *
  46525. * When set to `false`, the app must control the output
  46526. * transformation with `RenderOutputNode`.
  46527. *
  46528. * ```js
  46529. * const outputPass = renderOutput( scenePass );
  46530. * ```
  46531. *
  46532. * @type {Boolean}
  46533. */
  46534. this.outputColorTransform = true;
  46535. /**
  46536. * Must be set to `true` when the output node changes.
  46537. *
  46538. * @type {Node<vec4>}
  46539. */
  46540. this.needsUpdate = true;
  46541. const material = new NodeMaterial();
  46542. material.name = 'PostProcessing';
  46543. /**
  46544. * The full screen quad that is used to render
  46545. * the effects.
  46546. *
  46547. * @private
  46548. * @type {QuadMesh}
  46549. */
  46550. this._quadMesh = new QuadMesh( material );
  46551. }
  46552. /**
  46553. * When `PostProcessing` is used to apply post processing effects,
  46554. * the application must use this version of `render()` inside
  46555. * its animation loop (not the one from the renderer).
  46556. */
  46557. render() {
  46558. this._update();
  46559. const renderer = this.renderer;
  46560. const toneMapping = renderer.toneMapping;
  46561. const outputColorSpace = renderer.outputColorSpace;
  46562. renderer.toneMapping = NoToneMapping;
  46563. renderer.outputColorSpace = LinearSRGBColorSpace;
  46564. //
  46565. this._quadMesh.render( renderer );
  46566. //
  46567. renderer.toneMapping = toneMapping;
  46568. renderer.outputColorSpace = outputColorSpace;
  46569. }
  46570. /**
  46571. * Frees internal resources.
  46572. */
  46573. dispose() {
  46574. this._quadMesh.material.dispose();
  46575. }
  46576. /**
  46577. * Updates the state of the module.
  46578. *
  46579. * @private
  46580. */
  46581. _update() {
  46582. if ( this.needsUpdate === true ) {
  46583. const renderer = this.renderer;
  46584. const toneMapping = renderer.toneMapping;
  46585. const outputColorSpace = renderer.outputColorSpace;
  46586. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  46587. this._quadMesh.material.needsUpdate = true;
  46588. this.needsUpdate = false;
  46589. }
  46590. }
  46591. /**
  46592. * When `PostProcessing` is used to apply post processing effects,
  46593. * the application must use this version of `renderAsync()` inside
  46594. * its animation loop (not the one from the renderer).
  46595. *
  46596. * @async
  46597. * @return {Promise} A Promise that resolves when the render has been finished.
  46598. */
  46599. async renderAsync() {
  46600. this._update();
  46601. const renderer = this.renderer;
  46602. const toneMapping = renderer.toneMapping;
  46603. const outputColorSpace = renderer.outputColorSpace;
  46604. renderer.toneMapping = NoToneMapping;
  46605. renderer.outputColorSpace = LinearSRGBColorSpace;
  46606. //
  46607. await this._quadMesh.renderAsync( renderer );
  46608. //
  46609. renderer.toneMapping = toneMapping;
  46610. renderer.outputColorSpace = outputColorSpace;
  46611. }
  46612. }
  46613. /**
  46614. * This special type of texture is intended for compute shaders.
  46615. * It can be used to compute the data of a texture with a compute shader.
  46616. *
  46617. * Note: This type of texture can only be used with `WebGPURenderer`
  46618. * and a WebGPU backend.
  46619. *
  46620. * @augments Texture
  46621. */
  46622. class StorageTexture extends Texture {
  46623. /**
  46624. * Constructs a new storage texture.
  46625. *
  46626. * @param {Number} [width=1] - The storage texture's width.
  46627. * @param {Number} [height=1] - The storage texture's height.
  46628. */
  46629. constructor( width = 1, height = 1 ) {
  46630. super();
  46631. /**
  46632. * The image object which just represents the texture's dimension.
  46633. *
  46634. * @type {{width: Number, height:Number}}
  46635. */
  46636. this.image = { width, height };
  46637. /**
  46638. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  46639. *
  46640. * @type {Number}
  46641. */
  46642. this.magFilter = LinearFilter;
  46643. /**
  46644. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  46645. *
  46646. * @type {Number}
  46647. */
  46648. this.minFilter = LinearFilter;
  46649. /**
  46650. * This flag can be used for type testing.
  46651. *
  46652. * @type {Boolean}
  46653. * @readonly
  46654. * @default true
  46655. */
  46656. this.isStorageTexture = true;
  46657. }
  46658. }
  46659. /**
  46660. * This special type of buffer attribute is intended for compute shaders.
  46661. * It can be used to encode draw parameters for indirect draw calls.
  46662. *
  46663. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  46664. * and a WebGPU backend.
  46665. *
  46666. * @augments StorageBufferAttribute
  46667. */
  46668. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  46669. /**
  46670. * Constructs a new storage buffer attribute.
  46671. *
  46672. * @param {Number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  46673. * The subsequent parameter is then obsolete.
  46674. * @param {Number} itemSize - The item size.
  46675. */
  46676. constructor( count, itemSize ) {
  46677. super( count, itemSize, Uint32Array );
  46678. /**
  46679. * This flag can be used for type testing.
  46680. *
  46681. * @type {Boolean}
  46682. * @readonly
  46683. * @default true
  46684. */
  46685. this.isIndirectStorageBufferAttribute = true;
  46686. }
  46687. }
  46688. /**
  46689. * A loader for loading node objects in the three.js JSON Object/Scene format.
  46690. *
  46691. * @augments Loader
  46692. */
  46693. class NodeLoader extends Loader {
  46694. /**
  46695. * Constructs a new node loader.
  46696. *
  46697. * @param {LoadingManager?} manager - A reference to a loading manager.
  46698. */
  46699. constructor( manager ) {
  46700. super( manager );
  46701. /**
  46702. * Represents a dictionary of textures.
  46703. *
  46704. * @type {Object<String,Texture>}
  46705. */
  46706. this.textures = {};
  46707. /**
  46708. * Represents a dictionary of node types.
  46709. *
  46710. * @type {Object<String,Node.constructor>}
  46711. */
  46712. this.nodes = {};
  46713. }
  46714. /**
  46715. * Loads the node definitions from the given URL.
  46716. *
  46717. * @param {String} url - The path/URL of the file to be loaded.
  46718. * @param {Function} onLoad - Will be called when load completes.
  46719. * @param {Function} onProgress - Will be called while load progresses.
  46720. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  46721. */
  46722. load( url, onLoad, onProgress, onError ) {
  46723. const loader = new FileLoader( this.manager );
  46724. loader.setPath( this.path );
  46725. loader.setRequestHeader( this.requestHeader );
  46726. loader.setWithCredentials( this.withCredentials );
  46727. loader.load( url, ( text ) => {
  46728. try {
  46729. onLoad( this.parse( JSON.parse( text ) ) );
  46730. } catch ( e ) {
  46731. if ( onError ) {
  46732. onError( e );
  46733. } else {
  46734. console.error( e );
  46735. }
  46736. this.manager.itemError( url );
  46737. }
  46738. }, onProgress, onError );
  46739. }
  46740. /**
  46741. * Parse the node dependencies for the loaded node.
  46742. *
  46743. * @param {Object} json - The JSON definition
  46744. * @return {Object<String,Node>} A dictionary with node dependencies.
  46745. */
  46746. parseNodes( json ) {
  46747. const nodes = {};
  46748. if ( json !== undefined ) {
  46749. for ( const nodeJSON of json ) {
  46750. const { uuid, type } = nodeJSON;
  46751. nodes[ uuid ] = this.createNodeFromType( type );
  46752. nodes[ uuid ].uuid = uuid;
  46753. }
  46754. const meta = { nodes, textures: this.textures };
  46755. for ( const nodeJSON of json ) {
  46756. nodeJSON.meta = meta;
  46757. const node = nodes[ nodeJSON.uuid ];
  46758. node.deserialize( nodeJSON );
  46759. delete nodeJSON.meta;
  46760. }
  46761. }
  46762. return nodes;
  46763. }
  46764. /**
  46765. * Parses the node from the given JSON.
  46766. *
  46767. * @param {Object} json - The JSON definition
  46768. * @return {Node} The parsed node.
  46769. */
  46770. parse( json ) {
  46771. const node = this.createNodeFromType( json.type );
  46772. node.uuid = json.uuid;
  46773. const nodes = this.parseNodes( json.nodes );
  46774. const meta = { nodes, textures: this.textures };
  46775. json.meta = meta;
  46776. node.deserialize( json );
  46777. delete json.meta;
  46778. return node;
  46779. }
  46780. /**
  46781. * Defines the dictionary of textures.
  46782. *
  46783. * @param {Object<String,Texture>} value - The texture library defines as `<uuid,texture>`.
  46784. * @return {NodeLoader} A reference to this loader.
  46785. */
  46786. setTextures( value ) {
  46787. this.textures = value;
  46788. return this;
  46789. }
  46790. /**
  46791. * Defines the dictionary of node types.
  46792. *
  46793. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  46794. * @return {NodeLoader} A reference to this loader.
  46795. */
  46796. setNodes( value ) {
  46797. this.nodes = value;
  46798. return this;
  46799. }
  46800. /**
  46801. * Creates a node object from the given type.
  46802. *
  46803. * @param {String} type - The node type.
  46804. * @return {Node} The created node instance.
  46805. */
  46806. createNodeFromType( type ) {
  46807. if ( this.nodes[ type ] === undefined ) {
  46808. console.error( 'THREE.NodeLoader: Node type not found:', type );
  46809. return float();
  46810. }
  46811. return nodeObject( new this.nodes[ type ]() );
  46812. }
  46813. }
  46814. /**
  46815. * A special type of material loader for loading node materials.
  46816. *
  46817. * @augments MaterialLoader
  46818. */
  46819. class NodeMaterialLoader extends MaterialLoader {
  46820. /**
  46821. * Constructs a new node material loader.
  46822. *
  46823. * @param {LoadingManager?} manager - A reference to a loading manager.
  46824. */
  46825. constructor( manager ) {
  46826. super( manager );
  46827. /**
  46828. * Represents a dictionary of node types.
  46829. *
  46830. * @type {Object<String,Node.constructor>}
  46831. */
  46832. this.nodes = {};
  46833. /**
  46834. * Represents a dictionary of node material types.
  46835. *
  46836. * @type {Object<String,NodeMaterial.constructor>}
  46837. */
  46838. this.nodeMaterials = {};
  46839. }
  46840. /**
  46841. * Parses the node material from the given JSON.
  46842. *
  46843. * @param {Object} json - The JSON definition
  46844. * @return {NodeMaterial}. The parsed material.
  46845. */
  46846. parse( json ) {
  46847. const material = super.parse( json );
  46848. const nodes = this.nodes;
  46849. const inputNodes = json.inputNodes;
  46850. for ( const property in inputNodes ) {
  46851. const uuid = inputNodes[ property ];
  46852. material[ property ] = nodes[ uuid ];
  46853. }
  46854. return material;
  46855. }
  46856. /**
  46857. * Defines the dictionary of node types.
  46858. *
  46859. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  46860. * @return {NodeLoader} A reference to this loader.
  46861. */
  46862. setNodes( value ) {
  46863. this.nodes = value;
  46864. return this;
  46865. }
  46866. /**
  46867. * Defines the dictionary of node material types.
  46868. *
  46869. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  46870. * @return {NodeLoader} A reference to this loader.
  46871. */
  46872. setNodeMaterials( value ) {
  46873. this.nodeMaterials = value;
  46874. return this;
  46875. }
  46876. /**
  46877. * Creates a node material from the given type.
  46878. *
  46879. * @param {String} type - The node material type.
  46880. * @return {Node} The created node material instance.
  46881. */
  46882. createMaterialFromType( type ) {
  46883. const materialClass = this.nodeMaterials[ type ];
  46884. if ( materialClass !== undefined ) {
  46885. return new materialClass();
  46886. }
  46887. return super.createMaterialFromType( type );
  46888. }
  46889. }
  46890. /**
  46891. * A special type of object loader for loading 3D objects using
  46892. * node materials.
  46893. *
  46894. * @augments ObjectLoader
  46895. */
  46896. class NodeObjectLoader extends ObjectLoader {
  46897. /**
  46898. * Constructs a new node object loader.
  46899. *
  46900. * @param {LoadingManager?} manager - A reference to a loading manager.
  46901. */
  46902. constructor( manager ) {
  46903. super( manager );
  46904. /**
  46905. * Represents a dictionary of node types.
  46906. *
  46907. * @type {Object<String,Node.constructor>}
  46908. */
  46909. this.nodes = {};
  46910. /**
  46911. * Represents a dictionary of node material types.
  46912. *
  46913. * @type {Object<String,NodeMaterial.constructor>}
  46914. */
  46915. this.nodeMaterials = {};
  46916. /**
  46917. * A reference to hold the `nodes` JSON property.
  46918. *
  46919. * @private
  46920. * @type {Object?}
  46921. */
  46922. this._nodesJSON = null;
  46923. }
  46924. /**
  46925. * Defines the dictionary of node types.
  46926. *
  46927. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  46928. * @return {NodeLoader} A reference to this loader.
  46929. */
  46930. setNodes( value ) {
  46931. this.nodes = value;
  46932. return this;
  46933. }
  46934. /**
  46935. * Defines the dictionary of node material types.
  46936. *
  46937. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  46938. * @return {NodeLoader} A reference to this loader.
  46939. */
  46940. setNodeMaterials( value ) {
  46941. this.nodeMaterials = value;
  46942. return this;
  46943. }
  46944. /**
  46945. * Parses the node objects from the given JSON.
  46946. *
  46947. * @param {Object} json - The JSON definition
  46948. * @param {Function} onLoad - The onLoad callback function.
  46949. * @return {Object3D}. The parsed 3D object.
  46950. */
  46951. parse( json, onLoad ) {
  46952. this._nodesJSON = json.nodes;
  46953. const data = super.parse( json, onLoad );
  46954. this._nodesJSON = null; // dispose
  46955. return data;
  46956. }
  46957. /**
  46958. * Parses the node objects from the given JSON and textures.
  46959. *
  46960. * @param {Object} json - The JSON definition
  46961. * @param {Object<String,Texture>} textures - The texture library.
  46962. * @return {Object<String,Node>}. The parsed nodes.
  46963. */
  46964. parseNodes( json, textures ) {
  46965. if ( json !== undefined ) {
  46966. const loader = new NodeLoader();
  46967. loader.setNodes( this.nodes );
  46968. loader.setTextures( textures );
  46969. return loader.parseNodes( json );
  46970. }
  46971. return {};
  46972. }
  46973. /**
  46974. * Parses the node objects from the given JSON and textures.
  46975. *
  46976. * @param {Object} json - The JSON definition
  46977. * @param {Object<String,Texture>} textures - The texture library.
  46978. * @return {Object<String,NodeMaterial>}. The parsed materials.
  46979. */
  46980. parseMaterials( json, textures ) {
  46981. const materials = {};
  46982. if ( json !== undefined ) {
  46983. const nodes = this.parseNodes( this._nodesJSON, textures );
  46984. const loader = new NodeMaterialLoader();
  46985. loader.setTextures( textures );
  46986. loader.setNodes( nodes );
  46987. loader.setNodeMaterials( this.nodeMaterials );
  46988. for ( let i = 0, l = json.length; i < l; i ++ ) {
  46989. const data = json[ i ];
  46990. materials[ data.uuid ] = loader.parse( data );
  46991. }
  46992. }
  46993. return materials;
  46994. }
  46995. }
  46996. /**
  46997. * In earlier three.js versions, clipping was defined globally
  46998. * on the renderer or on material level. This special version of
  46999. * `THREE.Group` allows to encode the clipping state into the scene
  47000. * graph. Meaning if you create an instance of this group, all
  47001. * descendant 3D objects will be affected by the respective clipping
  47002. * planes.
  47003. *
  47004. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  47005. *
  47006. * @augments Group
  47007. */
  47008. class ClippingGroup extends Group {
  47009. /**
  47010. * Constructs a new clipping group.
  47011. */
  47012. constructor() {
  47013. super();
  47014. /**
  47015. * This flag can be used for type testing.
  47016. *
  47017. * @type {Boolean}
  47018. * @readonly
  47019. * @default true
  47020. */
  47021. this.isClippingGroup = true;
  47022. /**
  47023. * An array with clipping planes.
  47024. *
  47025. * @type {Array<Plane>}
  47026. */
  47027. this.clippingPlanes = [];
  47028. /**
  47029. * Whether clipping should be enabled or not.
  47030. *
  47031. * @type {Boolean}
  47032. * @default true
  47033. */
  47034. this.enabled = true;
  47035. /**
  47036. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  47037. *
  47038. * @type {Boolean}
  47039. * @default false
  47040. */
  47041. this.clipIntersection = false;
  47042. /**
  47043. * Whether shadows should be clipped or not.
  47044. *
  47045. * @type {Boolean}
  47046. * @default false
  47047. */
  47048. this.clipShadows = false;
  47049. }
  47050. }
  47051. 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, 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号