three.webgpu.nodes.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix3, Matrix4, EventDispatcher, MathUtils, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, BackSide, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, PointsMaterial, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, RenderTarget, Plane, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, CubeUVReflectionMapping, PerspectiveCamera, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, SRGBColorSpace, PCFShadowMap, FrontSide, Frustum, DataTexture, RedIntegerFormat, RedFormat, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, UnsignedShortType, ByteType, ShortType, createCanvasElement, AddEquation, SubtractEquation, ReverseSubtractEquation, ZeroFactor, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, LuminanceFormat, LuminanceAlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipmapNearestFilter, NeverCompare, AlwaysCompare, LessEqualCompare, EqualCompare, GreaterEqualCompare, GreaterCompare, NotEqualCompare, warnOnce, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LinearTransfer, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Matrix2, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneGeometry, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RenderTargetArray, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'attenuationColor',
  16. 'attenuationDistance',
  17. 'bumpMap',
  18. 'clearcoat',
  19. 'clearcoatMap',
  20. 'clearcoatNormalMap',
  21. 'clearcoatNormalScale',
  22. 'clearcoatRoughness',
  23. 'color',
  24. 'dispersion',
  25. 'displacementMap',
  26. 'emissive',
  27. 'emissiveMap',
  28. 'envMap',
  29. 'gradientMap',
  30. 'ior',
  31. 'iridescence',
  32. 'iridescenceIOR',
  33. 'iridescenceMap',
  34. 'iridescenceThicknessMap',
  35. 'lightMap',
  36. 'map',
  37. 'matcap',
  38. 'metalness',
  39. 'metalnessMap',
  40. 'normalMap',
  41. 'normalScale',
  42. 'opacity',
  43. 'roughness',
  44. 'roughnessMap',
  45. 'sheen',
  46. 'sheenColor',
  47. 'sheenColorMap',
  48. 'sheenRoughnessMap',
  49. 'shininess',
  50. 'specular',
  51. 'specularColor',
  52. 'specularColorMap',
  53. 'specularIntensity',
  54. 'specularIntensityMap',
  55. 'specularMap',
  56. 'thickness',
  57. 'transmission',
  58. 'transmissionMap'
  59. ];
  60. /**
  61. * This class is used by {@link WebGPURenderer} as management component.
  62. * It's primary purpose is to determine whether render objects require a
  63. * refresh right before they are going to be rendered or not.
  64. */
  65. class NodeMaterialObserver {
  66. /**
  67. * Constructs a new node material observer.
  68. *
  69. * @param {NodeBuilder} builder - The node builder.
  70. */
  71. constructor( builder ) {
  72. /**
  73. * A node material can be used by more than one render object so the
  74. * monitor must maintain a list of render objects.
  75. *
  76. * @type {WeakMap<RenderObject,Object>}
  77. */
  78. this.renderObjects = new WeakMap();
  79. /**
  80. * Whether the material uses node objects or not.
  81. *
  82. * @type {Boolean}
  83. */
  84. this.hasNode = this.containsNode( builder );
  85. /**
  86. * Whether the node builder's 3D object is animated or not.
  87. *
  88. * @type {Boolean}
  89. */
  90. this.hasAnimation = builder.object.isSkinnedMesh === true;
  91. /**
  92. * A list of all possible material uniforms
  93. *
  94. * @type {Array<String>}
  95. */
  96. this.refreshUniforms = refreshUniforms;
  97. /**
  98. * Holds the current render ID from the node frame.
  99. *
  100. * @type {Number}
  101. * @default 0
  102. */
  103. this.renderId = 0;
  104. }
  105. /**
  106. * Returns `true` if the given render object is verified for the first time of this observer.
  107. *
  108. * @param {RenderObject} renderObject - The render object.
  109. * @return {Boolean} Whether the given render object is verified for the first time of this observer.
  110. */
  111. firstInitialization( renderObject ) {
  112. const hasInitialized = this.renderObjects.has( renderObject );
  113. if ( hasInitialized === false ) {
  114. this.getRenderObjectData( renderObject );
  115. return true;
  116. }
  117. return false;
  118. }
  119. /**
  120. * Returns monitoring data for the given render object.
  121. *
  122. * @param {RenderObject} renderObject - The render object.
  123. * @return {Object} The monitoring data.
  124. */
  125. getRenderObjectData( renderObject ) {
  126. let data = this.renderObjects.get( renderObject );
  127. if ( data === undefined ) {
  128. const { geometry, material, object } = renderObject;
  129. data = {
  130. material: this.getMaterialData( material ),
  131. geometry: {
  132. attributes: this.getAttributesData( geometry.attributes ),
  133. indexVersion: geometry.index ? geometry.index.version : null,
  134. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  135. },
  136. worldMatrix: object.matrixWorld.clone()
  137. };
  138. if ( object.center ) {
  139. data.center = object.center.clone();
  140. }
  141. if ( object.morphTargetInfluences ) {
  142. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  143. }
  144. if ( renderObject.bundle !== null ) {
  145. data.version = renderObject.bundle.version;
  146. }
  147. if ( data.material.transmission > 0 ) {
  148. const { width, height } = renderObject.context;
  149. data.bufferWidth = width;
  150. data.bufferHeight = height;
  151. }
  152. this.renderObjects.set( renderObject, data );
  153. }
  154. return data;
  155. }
  156. /**
  157. * Returns an attribute data structure holding the attributes versions for
  158. * monitoring.
  159. *
  160. * @param {Object} attributes - The geometry attributes.
  161. * @return {Object} An object for monitoring the versions of attributes.
  162. */
  163. getAttributesData( attributes ) {
  164. const attributesData = {};
  165. for ( const name in attributes ) {
  166. const attribute = attributes[ name ];
  167. attributesData[ name ] = {
  168. version: attribute.version
  169. };
  170. }
  171. return attributesData;
  172. }
  173. /**
  174. * Returns `true` if the node builder's material uses
  175. * node properties.
  176. *
  177. * @param {NodeBuilder} builder - The current node builder.
  178. * @return {Boolean} Whether the node builder's material uses node properties or not.
  179. */
  180. containsNode( builder ) {
  181. const material = builder.material;
  182. for ( const property in material ) {
  183. if ( material[ property ] && material[ property ].isNode )
  184. return true;
  185. }
  186. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  187. return true;
  188. return false;
  189. }
  190. /**
  191. * Returns a material data structure holding the material property values for
  192. * monitoring.
  193. *
  194. * @param {Material} material - The material.
  195. * @return {Object} An object for monitoring material properties.
  196. */
  197. getMaterialData( material ) {
  198. const data = {};
  199. for ( const property of this.refreshUniforms ) {
  200. const value = material[ property ];
  201. if ( value === null || value === undefined ) continue;
  202. if ( typeof value === 'object' && value.clone !== undefined ) {
  203. if ( value.isTexture === true ) {
  204. data[ property ] = { id: value.id, version: value.version };
  205. } else {
  206. data[ property ] = value.clone();
  207. }
  208. } else {
  209. data[ property ] = value;
  210. }
  211. }
  212. return data;
  213. }
  214. /**
  215. * Returns `true` if the given render object has not changed its state.
  216. *
  217. * @param {RenderObject} renderObject - The render object.
  218. * @return {Boolean} Whether the given render object has changed its state or not.
  219. */
  220. equals( renderObject ) {
  221. const { object, material, geometry } = renderObject;
  222. const renderObjectData = this.getRenderObjectData( renderObject );
  223. // world matrix
  224. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  225. renderObjectData.worldMatrix.copy( object.matrixWorld );
  226. return false;
  227. }
  228. // material
  229. const materialData = renderObjectData.material;
  230. for ( const property in materialData ) {
  231. const value = materialData[ property ];
  232. const mtlValue = material[ property ];
  233. if ( value.equals !== undefined ) {
  234. if ( value.equals( mtlValue ) === false ) {
  235. value.copy( mtlValue );
  236. return false;
  237. }
  238. } else if ( mtlValue.isTexture === true ) {
  239. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  240. value.id = mtlValue.id;
  241. value.version = mtlValue.version;
  242. return false;
  243. }
  244. } else if ( value !== mtlValue ) {
  245. materialData[ property ] = mtlValue;
  246. return false;
  247. }
  248. }
  249. if ( materialData.transmission > 0 ) {
  250. const { width, height } = renderObject.context;
  251. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  252. renderObjectData.bufferWidth = width;
  253. renderObjectData.bufferHeight = height;
  254. return false;
  255. }
  256. }
  257. // geometry
  258. const storedGeometryData = renderObjectData.geometry;
  259. const attributes = geometry.attributes;
  260. const storedAttributes = storedGeometryData.attributes;
  261. const storedAttributeNames = Object.keys( storedAttributes );
  262. const currentAttributeNames = Object.keys( attributes );
  263. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  264. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  265. return false;
  266. }
  267. // compare each attribute
  268. for ( const name of storedAttributeNames ) {
  269. const storedAttributeData = storedAttributes[ name ];
  270. const attribute = attributes[ name ];
  271. if ( attribute === undefined ) {
  272. // attribute was removed
  273. delete storedAttributes[ name ];
  274. return false;
  275. }
  276. if ( storedAttributeData.version !== attribute.version ) {
  277. storedAttributeData.version = attribute.version;
  278. return false;
  279. }
  280. }
  281. // check index
  282. const index = geometry.index;
  283. const storedIndexVersion = storedGeometryData.indexVersion;
  284. const currentIndexVersion = index ? index.version : null;
  285. if ( storedIndexVersion !== currentIndexVersion ) {
  286. storedGeometryData.indexVersion = currentIndexVersion;
  287. return false;
  288. }
  289. // check drawRange
  290. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  291. storedGeometryData.drawRange.start = geometry.drawRange.start;
  292. storedGeometryData.drawRange.count = geometry.drawRange.count;
  293. return false;
  294. }
  295. // morph targets
  296. if ( renderObjectData.morphTargetInfluences ) {
  297. let morphChanged = false;
  298. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  299. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  300. morphChanged = true;
  301. }
  302. }
  303. if ( morphChanged ) return true;
  304. }
  305. // center
  306. if ( renderObjectData.center ) {
  307. if ( renderObjectData.center.equals( object.center ) === false ) {
  308. renderObjectData.center.copy( object.center );
  309. return true;
  310. }
  311. }
  312. // bundle
  313. if ( renderObject.bundle !== null ) {
  314. renderObjectData.version = renderObject.bundle.version;
  315. }
  316. return true;
  317. }
  318. /**
  319. * Checks if the given render object requires a refresh.
  320. *
  321. * @param {RenderObject} renderObject - The render object.
  322. * @param {NodeFrame} nodeFrame - The current node frame.
  323. * @return {Boolean} Whether the given render object requires a refresh or not.
  324. */
  325. needsRefresh( renderObject, nodeFrame ) {
  326. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  327. return true;
  328. const { renderId } = nodeFrame;
  329. if ( this.renderId !== renderId ) {
  330. this.renderId = renderId;
  331. return true;
  332. }
  333. const isStatic = renderObject.object.static === true;
  334. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  335. if ( isStatic || isBundle )
  336. return false;
  337. const notEqual = this.equals( renderObject ) !== true;
  338. return notEqual;
  339. }
  340. }
  341. /** @module NodeUtils **/
  342. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  343. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  344. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  345. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  346. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  347. function cyrb53( value, seed = 0 ) {
  348. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  349. if ( value instanceof Array ) {
  350. for ( let i = 0, val; i < value.length; i ++ ) {
  351. val = value[ i ];
  352. h1 = Math.imul( h1 ^ val, 2654435761 );
  353. h2 = Math.imul( h2 ^ val, 1597334677 );
  354. }
  355. } else {
  356. for ( let i = 0, ch; i < value.length; i ++ ) {
  357. ch = value.charCodeAt( i );
  358. h1 = Math.imul( h1 ^ ch, 2654435761 );
  359. h2 = Math.imul( h2 ^ ch, 1597334677 );
  360. }
  361. }
  362. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  363. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  364. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  365. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  366. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  367. }
  368. /**
  369. * Computes a hash for the given string.
  370. *
  371. * @method
  372. * @param {String} str - The string to be hashed.
  373. * @return {Number} The hash.
  374. */
  375. const hashString = ( str ) => cyrb53( str );
  376. /**
  377. * Computes a hash for the given array.
  378. *
  379. * @method
  380. * @param {Array<Number>} array - The array to be hashed.
  381. * @return {Number} The hash.
  382. */
  383. const hashArray = ( array ) => cyrb53( array );
  384. /**
  385. * Computes a hash for the given list of parameters.
  386. *
  387. * @method
  388. * @param {...Number} params - A list of parameters.
  389. * @return {Number} The hash.
  390. */
  391. const hash$1 = ( ...params ) => cyrb53( params );
  392. /**
  393. * Computes a cache key for the given node.
  394. *
  395. * @method
  396. * @param {Object} object - The object to be hashed.
  397. * @param {Boolean} [force=false] - Whether to force a cache key computation or not.
  398. * @return {Number} The hash.
  399. */
  400. function getCacheKey$1( object, force = false ) {
  401. const values = [];
  402. if ( object.isNode === true ) {
  403. values.push( object.id );
  404. object = object.getSelf();
  405. }
  406. for ( const { property, childNode } of getNodeChildren( object ) ) {
  407. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  408. }
  409. return cyrb53( values );
  410. }
  411. /**
  412. * This generator function can be used to iterate over the node children
  413. * of the given object.
  414. *
  415. * @generator
  416. * @param {Object} node - The object to be hashed.
  417. * @param {Boolean} [toJSON=false] - Whether to return JSON or not.
  418. * @yields {Object} A result node holding the property, index (if available) and the child node.
  419. */
  420. function* getNodeChildren( node, toJSON = false ) {
  421. for ( const property in node ) {
  422. // Ignore private properties.
  423. if ( property.startsWith( '_' ) === true ) continue;
  424. const object = node[ property ];
  425. if ( Array.isArray( object ) === true ) {
  426. for ( let i = 0; i < object.length; i ++ ) {
  427. const child = object[ i ];
  428. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  429. yield { property, index: i, childNode: child };
  430. }
  431. }
  432. } else if ( object && object.isNode === true ) {
  433. yield { property, childNode: object };
  434. } else if ( typeof object === 'object' ) {
  435. for ( const subProperty in object ) {
  436. const child = object[ subProperty ];
  437. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  438. yield { property, index: subProperty, childNode: child };
  439. }
  440. }
  441. }
  442. }
  443. }
  444. const typeFromLength = /*@__PURE__*/ new Map( [
  445. [ 1, 'float' ],
  446. [ 2, 'vec2' ],
  447. [ 3, 'vec3' ],
  448. [ 4, 'vec4' ],
  449. [ 9, 'mat3' ],
  450. [ 16, 'mat4' ]
  451. ] );
  452. const dataFromObject = /*@__PURE__*/ new WeakMap();
  453. /**
  454. * Returns the data type for the given the length.
  455. *
  456. * @method
  457. * @param {Number} length - The length.
  458. * @return {String} The data type.
  459. */
  460. function getTypeFromLength( length ) {
  461. return typeFromLength.get( length );
  462. }
  463. /**
  464. * Returns the typed array for the given data type.
  465. *
  466. * @method
  467. * @param {String} type - The data type.
  468. * @return {TypedArray} The typed array.
  469. */
  470. function getTypedArrayFromType( type ) {
  471. // Handle component type for vectors and matrices
  472. if ( /[iu]?vec\d/.test( type ) ) {
  473. // Handle int vectors
  474. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  475. // Handle uint vectors
  476. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  477. // Default to float vectors
  478. return Float32Array;
  479. }
  480. // Handle matrices (always float)
  481. if ( /mat\d/.test( type ) ) return Float32Array;
  482. // Basic types
  483. if ( /float/.test( type ) ) return Float32Array;
  484. if ( /uint/.test( type ) ) return Uint32Array;
  485. if ( /int/.test( type ) ) return Int32Array;
  486. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  487. }
  488. /**
  489. * Returns the length for the given data type.
  490. *
  491. * @method
  492. * @param {String} type - The data type.
  493. * @return {Number} The length.
  494. */
  495. function getLengthFromType( type ) {
  496. if ( /float|int|uint/.test( type ) ) return 1;
  497. if ( /vec2/.test( type ) ) return 2;
  498. if ( /vec3/.test( type ) ) return 3;
  499. if ( /vec4/.test( type ) ) return 4;
  500. if ( /mat3/.test( type ) ) return 9;
  501. if ( /mat4/.test( type ) ) return 16;
  502. console.error( 'THREE.TSL: Unsupported type:', type );
  503. }
  504. /**
  505. * Returns the data type for the given value.
  506. *
  507. * @method
  508. * @param {Any} value - The value.
  509. * @return {String?} The data type.
  510. */
  511. function getValueType( value ) {
  512. if ( value === undefined || value === null ) return null;
  513. const typeOf = typeof value;
  514. if ( value.isNode === true ) {
  515. return 'node';
  516. } else if ( typeOf === 'number' ) {
  517. return 'float';
  518. } else if ( typeOf === 'boolean' ) {
  519. return 'bool';
  520. } else if ( typeOf === 'string' ) {
  521. return 'string';
  522. } else if ( typeOf === 'function' ) {
  523. return 'shader';
  524. } else if ( value.isVector2 === true ) {
  525. return 'vec2';
  526. } else if ( value.isVector3 === true ) {
  527. return 'vec3';
  528. } else if ( value.isVector4 === true ) {
  529. return 'vec4';
  530. } else if ( value.isMatrix3 === true ) {
  531. return 'mat3';
  532. } else if ( value.isMatrix4 === true ) {
  533. return 'mat4';
  534. } else if ( value.isColor === true ) {
  535. return 'color';
  536. } else if ( value instanceof ArrayBuffer ) {
  537. return 'ArrayBuffer';
  538. }
  539. return null;
  540. }
  541. /**
  542. * Returns the value/object for the given data type and parameters.
  543. *
  544. * @method
  545. * @param {String} type - The given type.
  546. * @param {...Any} params - A parameter list.
  547. * @return {Any} The value/object.
  548. */
  549. function getValueFromType( type, ...params ) {
  550. const last4 = type ? type.slice( - 4 ) : undefined;
  551. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  552. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  553. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  554. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  555. }
  556. if ( type === 'color' ) {
  557. return new Color( ...params );
  558. } else if ( last4 === 'vec2' ) {
  559. return new Vector2( ...params );
  560. } else if ( last4 === 'vec3' ) {
  561. return new Vector3( ...params );
  562. } else if ( last4 === 'vec4' ) {
  563. return new Vector4( ...params );
  564. } else if ( last4 === 'mat3' ) {
  565. return new Matrix3( ...params );
  566. } else if ( last4 === 'mat4' ) {
  567. return new Matrix4( ...params );
  568. } else if ( type === 'bool' ) {
  569. return params[ 0 ] || false;
  570. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  571. return params[ 0 ] || 0;
  572. } else if ( type === 'string' ) {
  573. return params[ 0 ] || '';
  574. } else if ( type === 'ArrayBuffer' ) {
  575. return base64ToArrayBuffer( params[ 0 ] );
  576. }
  577. return null;
  578. }
  579. /**
  580. * Gets the object data that can be shared between different rendering steps.
  581. *
  582. * @param {Object} object - The object to get the data for.
  583. * @return {Object} The object data.
  584. */
  585. function getDataFromObject( object ) {
  586. let data = dataFromObject.get( object );
  587. if ( data === undefined ) {
  588. data = {};
  589. dataFromObject.set( object, data );
  590. }
  591. return data;
  592. }
  593. /**
  594. * Converts the given array buffer to a Base64 string.
  595. *
  596. * @method
  597. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  598. * @return {String} The Base64 string.
  599. */
  600. function arrayBufferToBase64( arrayBuffer ) {
  601. let chars = '';
  602. const array = new Uint8Array( arrayBuffer );
  603. for ( let i = 0; i < array.length; i ++ ) {
  604. chars += String.fromCharCode( array[ i ] );
  605. }
  606. return btoa( chars );
  607. }
  608. /**
  609. * Converts the given Base64 string to an array buffer.
  610. *
  611. * @method
  612. * @param {String} base64 - The Base64 string.
  613. * @return {ArrayBuffer} The array buffer.
  614. */
  615. function base64ToArrayBuffer( base64 ) {
  616. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  617. }
  618. var NodeUtils = /*#__PURE__*/Object.freeze({
  619. __proto__: null,
  620. arrayBufferToBase64: arrayBufferToBase64,
  621. base64ToArrayBuffer: base64ToArrayBuffer,
  622. getCacheKey: getCacheKey$1,
  623. getDataFromObject: getDataFromObject,
  624. getLengthFromType: getLengthFromType,
  625. getNodeChildren: getNodeChildren,
  626. getTypeFromLength: getTypeFromLength,
  627. getTypedArrayFromType: getTypedArrayFromType,
  628. getValueFromType: getValueFromType,
  629. getValueType: getValueType,
  630. hash: hash$1,
  631. hashArray: hashArray,
  632. hashString: hashString
  633. });
  634. /** @module NodeConstants **/
  635. /**
  636. * Possible shader stages.
  637. *
  638. * @property {string} VERTEX The vertex shader stage.
  639. * @property {string} FRAGMENT The fragment shader stage.
  640. */
  641. const NodeShaderStage = {
  642. VERTEX: 'vertex',
  643. FRAGMENT: 'fragment'
  644. };
  645. /**
  646. * Update types of a node.
  647. *
  648. * @property {string} NONE The update method is not executed.
  649. * @property {string} FRAME The update method is executed per frame.
  650. * @property {string} RENDER The update method is executed per render. A frame might be produced by multiple render calls so this value allows more detailed updates than FRAME.
  651. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  652. */
  653. const NodeUpdateType = {
  654. NONE: 'none',
  655. FRAME: 'frame',
  656. RENDER: 'render',
  657. OBJECT: 'object'
  658. };
  659. /**
  660. * Data types of a node.
  661. *
  662. * @property {string} BOOLEAN Boolean type.
  663. * @property {string} INTEGER Integer type.
  664. * @property {string} FLOAT Float type.
  665. * @property {string} VECTOR2 Two-dimensional vector type.
  666. * @property {string} VECTOR3 Three-dimensional vector type.
  667. * @property {string} VECTOR4 Four-dimensional vector type.
  668. * @property {string} MATRIX2 2x2 matrix type.
  669. * @property {string} MATRIX3 3x3 matrix type.
  670. * @property {string} MATRIX4 4x4 matrix type.
  671. */
  672. const NodeType = {
  673. BOOLEAN: 'bool',
  674. INTEGER: 'int',
  675. FLOAT: 'float',
  676. VECTOR2: 'vec2',
  677. VECTOR3: 'vec3',
  678. VECTOR4: 'vec4',
  679. MATRIX2: 'mat2',
  680. MATRIX3: 'mat3',
  681. MATRIX4: 'mat4'
  682. };
  683. /**
  684. * Access types of a node. These are relevant for compute and storage usage.
  685. *
  686. * @property {string} READ_ONLY Read-only access
  687. * @property {string} WRITE_ONLY Write-only access.
  688. * @property {string} READ_WRITE Read and write access.
  689. */
  690. const NodeAccess = {
  691. READ_ONLY: 'readOnly',
  692. WRITE_ONLY: 'writeOnly',
  693. READ_WRITE: 'readWrite',
  694. };
  695. const defaultShaderStages = [ 'fragment', 'vertex' ];
  696. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  697. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  698. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  699. let _nodeId = 0;
  700. /**
  701. * Base class for all nodes.
  702. *
  703. * @augments EventDispatcher
  704. */
  705. class Node extends EventDispatcher {
  706. static get type() {
  707. return 'Node';
  708. }
  709. /**
  710. * Constructs a new node.
  711. *
  712. * @param {String?} nodeType - The node type.
  713. */
  714. constructor( nodeType = null ) {
  715. super();
  716. /**
  717. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  718. *
  719. * @type {String?}
  720. * @default null
  721. */
  722. this.nodeType = nodeType;
  723. /**
  724. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  725. *
  726. * @type {String}
  727. * @default 'none'
  728. */
  729. this.updateType = NodeUpdateType.NONE;
  730. /**
  731. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  732. *
  733. * @type {String}
  734. * @default 'none'
  735. */
  736. this.updateBeforeType = NodeUpdateType.NONE;
  737. /**
  738. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  739. *
  740. * @type {String}
  741. * @default 'none'
  742. */
  743. this.updateAfterType = NodeUpdateType.NONE;
  744. /**
  745. * The UUID of the node.
  746. *
  747. * @type {String}
  748. * @readonly
  749. */
  750. this.uuid = MathUtils.generateUUID();
  751. /**
  752. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  753. *
  754. * @type {Number}
  755. * @readonly
  756. * @default 0
  757. */
  758. this.version = 0;
  759. /**
  760. * Whether this node is global or not. This property is relevant for the internal
  761. * node caching system. All nodes which should be declared just once should
  762. * set this flag to `true` (a typical example is {@link AttributeNode}).
  763. *
  764. * @type {Boolean}
  765. * @default false
  766. */
  767. this.global = false;
  768. /**
  769. * This flag can be used for type testing.
  770. *
  771. * @type {Boolean}
  772. * @readonly
  773. * @default true
  774. */
  775. this.isNode = true;
  776. // private
  777. /**
  778. * The cache key of this node.
  779. *
  780. * @private
  781. * @type {Number?}
  782. * @default null
  783. */
  784. this._cacheKey = null;
  785. /**
  786. * The cache key 's version.
  787. *
  788. * @private
  789. * @type {Number}
  790. * @default 0
  791. */
  792. this._cacheKeyVersion = 0;
  793. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  794. }
  795. /**
  796. * Set this property to `true` when the node should be regenerated.
  797. *
  798. * @type {Boolean}
  799. * @default false
  800. * @param {boolean} value
  801. */
  802. set needsUpdate( value ) {
  803. if ( value === true ) {
  804. this.version ++;
  805. }
  806. }
  807. /**
  808. * The type of the class. The value is usually the constructor name.
  809. *
  810. * @type {String}
  811. * @readonly
  812. */
  813. get type() {
  814. return this.constructor.type;
  815. }
  816. /**
  817. * Convenient method for defining {@link Node#update}.
  818. *
  819. * @param {Function} callback - The update method.
  820. * @param {String} updateType - The update type.
  821. * @return {Node} A reference to this node.
  822. */
  823. onUpdate( callback, updateType ) {
  824. this.updateType = updateType;
  825. this.update = callback.bind( this.getSelf() );
  826. return this;
  827. }
  828. /**
  829. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  830. * this method automatically sets the update type to `FRAME`.
  831. *
  832. * @param {Function} callback - The update method.
  833. * @return {Node} A reference to this node.
  834. */
  835. onFrameUpdate( callback ) {
  836. return this.onUpdate( callback, NodeUpdateType.FRAME );
  837. }
  838. /**
  839. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  840. * this method automatically sets the update type to `RENDER`.
  841. *
  842. * @param {Function} callback - The update method.
  843. * @return {Node} A reference to this node.
  844. */
  845. onRenderUpdate( callback ) {
  846. return this.onUpdate( callback, NodeUpdateType.RENDER );
  847. }
  848. /**
  849. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  850. * this method automatically sets the update type to `OBJECT`.
  851. *
  852. * @param {Function} callback - The update method.
  853. * @return {Node} A reference to this node.
  854. */
  855. onObjectUpdate( callback ) {
  856. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  857. }
  858. /**
  859. * Convenient method for defining {@link Node#updateReference}.
  860. *
  861. * @param {Function} callback - The update method.
  862. * @return {Node} A reference to this node.
  863. */
  864. onReference( callback ) {
  865. this.updateReference = callback.bind( this.getSelf() );
  866. return this;
  867. }
  868. /**
  869. * The `this` reference might point to a Proxy so this method can be used
  870. * to get the reference to the actual node instance.
  871. *
  872. * @return {Node} A reference to the node.
  873. */
  874. getSelf() {
  875. // Returns non-node object.
  876. return this.self || this;
  877. }
  878. /**
  879. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  880. * to such objects based on a given state (e.g. the current node frame or builder).
  881. *
  882. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  883. * @return {Any} The updated reference.
  884. */
  885. updateReference( /*state*/ ) {
  886. return this;
  887. }
  888. /**
  889. * By default this method returns the value of the {@link Node#global} flag. This method
  890. * can be overwritten in derived classes if an analytical way is required to determine the
  891. * global status.
  892. *
  893. * @param {NodeBuilder} builder - The current node builder.
  894. * @return {Boolean} Whether this node is global or not.
  895. */
  896. isGlobal( /*builder*/ ) {
  897. return this.global;
  898. }
  899. /**
  900. * Generator function that can be used to iterate over the child nodes.
  901. *
  902. * @generator
  903. * @yields {Node} A child node.
  904. */
  905. * getChildren() {
  906. for ( const { childNode } of getNodeChildren( this ) ) {
  907. yield childNode;
  908. }
  909. }
  910. /**
  911. * Calling this method dispatches the `dispose` event. This event can be used
  912. * to register event listeners for clean up tasks.
  913. */
  914. dispose() {
  915. this.dispatchEvent( { type: 'dispose' } );
  916. }
  917. /**
  918. * Callback for {@link Node#traverse}.
  919. *
  920. * @callback traverseCallback
  921. * @param {Node} node - The current node.
  922. */
  923. /**
  924. * Can be used to traverse through the node's hierarchy.
  925. *
  926. * @param {traverseCallback} callback - A callback that is executed per node.
  927. */
  928. traverse( callback ) {
  929. callback( this );
  930. for ( const childNode of this.getChildren() ) {
  931. childNode.traverse( callback );
  932. }
  933. }
  934. /**
  935. * Returns the cache key for this node.
  936. *
  937. * @param {Boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  938. * @return {Number} The cache key of the node.
  939. */
  940. getCacheKey( force = false ) {
  941. force = force || this.version !== this._cacheKeyVersion;
  942. if ( force === true || this._cacheKey === null ) {
  943. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  944. this._cacheKeyVersion = this.version;
  945. }
  946. return this._cacheKey;
  947. }
  948. /**
  949. * Generate a custom cache key for this node.
  950. *
  951. * @return {Number} The cache key of the node.
  952. */
  953. customCacheKey() {
  954. return 0;
  955. }
  956. /**
  957. * Returns the references to this node which is by default `this`.
  958. *
  959. * @return {Node} A reference to this node.
  960. */
  961. getScope() {
  962. return this;
  963. }
  964. /**
  965. * Returns the hash of the node which is used to identify the node. By default it's
  966. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  967. * depending on their implementation.
  968. *
  969. * @param {NodeBuilder} builder - The current node builder.
  970. * @return {String} The hash.
  971. */
  972. getHash( /*builder*/ ) {
  973. return this.uuid;
  974. }
  975. /**
  976. * Returns the update type of {@link Node#update}.
  977. *
  978. * @return {NodeUpdateType} The update type.
  979. */
  980. getUpdateType() {
  981. return this.updateType;
  982. }
  983. /**
  984. * Returns the update type of {@link Node#updateBefore}.
  985. *
  986. * @return {NodeUpdateType} The update type.
  987. */
  988. getUpdateBeforeType() {
  989. return this.updateBeforeType;
  990. }
  991. /**
  992. * Returns the update type of {@link Node#updateAfter}.
  993. *
  994. * @return {NodeUpdateType} The update type.
  995. */
  996. getUpdateAfterType() {
  997. return this.updateAfterType;
  998. }
  999. /**
  1000. * Certain types are composed of multiple elements. For example a `vec3`
  1001. * is composed of three `float` values. This method returns the type of
  1002. * these elements.
  1003. *
  1004. * @param {NodeBuilder} builder - The current node builder.
  1005. * @return {String} The type of the node.
  1006. */
  1007. getElementType( builder ) {
  1008. const type = this.getNodeType( builder );
  1009. const elementType = builder.getElementType( type );
  1010. return elementType;
  1011. }
  1012. /**
  1013. * Returns the node's type.
  1014. *
  1015. * @param {NodeBuilder} builder - The current node builder.
  1016. * @return {String} The type of the node.
  1017. */
  1018. getNodeType( builder ) {
  1019. const nodeProperties = builder.getNodeProperties( this );
  1020. if ( nodeProperties.outputNode ) {
  1021. return nodeProperties.outputNode.getNodeType( builder );
  1022. }
  1023. return this.nodeType;
  1024. }
  1025. /**
  1026. * This method is used during the build process of a node and ensures
  1027. * equal nodes are not built multiple times but just once. For example if
  1028. * `attribute( 'uv' )` is used multiple times by the user, the build
  1029. * process makes sure to process just the first node.
  1030. *
  1031. * @param {NodeBuilder} builder - The current node builder.
  1032. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1033. */
  1034. getShared( builder ) {
  1035. const hash = this.getHash( builder );
  1036. const nodeFromHash = builder.getNodeFromHash( hash );
  1037. return nodeFromHash || this;
  1038. }
  1039. /**
  1040. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1041. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1042. * The output node must be returned in the `return` statement.
  1043. *
  1044. * @param {NodeBuilder} builder - The current node builder.
  1045. * @return {Node?} The output node.
  1046. */
  1047. setup( builder ) {
  1048. const nodeProperties = builder.getNodeProperties( this );
  1049. let index = 0;
  1050. for ( const childNode of this.getChildren() ) {
  1051. nodeProperties[ 'node' + index ++ ] = childNode;
  1052. }
  1053. // return a outputNode if exists or null
  1054. return nodeProperties.outputNode || null;
  1055. }
  1056. /**
  1057. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1058. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1059. *
  1060. * @param {NodeBuilder} builder - The current node builder.
  1061. */
  1062. analyze( builder ) {
  1063. const usageCount = builder.increaseUsage( this );
  1064. if ( usageCount === 1 ) {
  1065. // node flow children
  1066. const nodeProperties = builder.getNodeProperties( this );
  1067. for ( const childNode of Object.values( nodeProperties ) ) {
  1068. if ( childNode && childNode.isNode === true ) {
  1069. childNode.build( builder );
  1070. }
  1071. }
  1072. }
  1073. }
  1074. /**
  1075. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1076. * This state builds the output node and returns the resulting shader string.
  1077. *
  1078. * @param {NodeBuilder} builder - The current node builder.
  1079. * @param {String?} output - Can be used to define the output type.
  1080. * @return {String?} The generated shader string.
  1081. */
  1082. generate( builder, output ) {
  1083. const { outputNode } = builder.getNodeProperties( this );
  1084. if ( outputNode && outputNode.isNode === true ) {
  1085. return outputNode.build( builder, output );
  1086. }
  1087. }
  1088. /**
  1089. * The method can be implemented to update the node's internal state before it is used to render an object.
  1090. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1091. *
  1092. * @abstract
  1093. * @param {NodeFrame} frame - A reference to the current node frame.
  1094. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1095. */
  1096. updateBefore( /*frame*/ ) {
  1097. console.warn( 'Abstract function.' );
  1098. }
  1099. /**
  1100. * The method can be implemented to update the node's internal state after it was used to render an object.
  1101. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1102. *
  1103. * @abstract
  1104. * @param {NodeFrame} frame - A reference to the current node frame.
  1105. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1106. */
  1107. updateAfter( /*frame*/ ) {
  1108. console.warn( 'Abstract function.' );
  1109. }
  1110. /**
  1111. * The method can be implemented to update the node's internal state when it is used to render an object.
  1112. * The {@link Node#updateType} property defines how often the update is executed.
  1113. *
  1114. * @abstract
  1115. * @param {NodeFrame} frame - A reference to the current node frame.
  1116. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1117. */
  1118. update( /*frame*/ ) {
  1119. console.warn( 'Abstract function.' );
  1120. }
  1121. /**
  1122. * This method performs the build of a node. The behavior of this method as well as its return value depend
  1123. * on the current build stage (setup, analyze or generate).
  1124. *
  1125. * @param {NodeBuilder} builder - The current node builder.
  1126. * @param {String?} output - Can be used to define the output type.
  1127. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  1128. */
  1129. build( builder, output = null ) {
  1130. const refNode = this.getShared( builder );
  1131. if ( this !== refNode ) {
  1132. return refNode.build( builder, output );
  1133. }
  1134. builder.addNode( this );
  1135. builder.addChain( this );
  1136. /* Build stages expected results:
  1137. - "setup" -> Node
  1138. - "analyze" -> null
  1139. - "generate" -> String
  1140. */
  1141. let result = null;
  1142. const buildStage = builder.getBuildStage();
  1143. if ( buildStage === 'setup' ) {
  1144. this.updateReference( builder );
  1145. const properties = builder.getNodeProperties( this );
  1146. if ( properties.initialized !== true ) {
  1147. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1148. properties.initialized = true;
  1149. const outputNode = this.setup( builder ); // return a node or null
  1150. const isNodeOutput = outputNode && outputNode.isNode === true;
  1151. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1152. // !! no outputNode !!
  1153. //outputNode = builder.stack;
  1154. }*/
  1155. for ( const childNode of Object.values( properties ) ) {
  1156. if ( childNode && childNode.isNode === true ) {
  1157. childNode.build( builder );
  1158. }
  1159. }
  1160. if ( isNodeOutput ) {
  1161. outputNode.build( builder );
  1162. }
  1163. properties.outputNode = outputNode;
  1164. }
  1165. } else if ( buildStage === 'analyze' ) {
  1166. this.analyze( builder );
  1167. } else if ( buildStage === 'generate' ) {
  1168. const isGenerateOnce = this.generate.length === 1;
  1169. if ( isGenerateOnce ) {
  1170. const type = this.getNodeType( builder );
  1171. const nodeData = builder.getDataFromNode( this );
  1172. result = nodeData.snippet;
  1173. if ( result === undefined ) {
  1174. result = this.generate( builder ) || '';
  1175. nodeData.snippet = result;
  1176. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1177. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1178. }
  1179. result = builder.format( result, type, output );
  1180. } else {
  1181. result = this.generate( builder, output ) || '';
  1182. }
  1183. }
  1184. builder.removeChain( this );
  1185. builder.addSequentialNode( this );
  1186. return result;
  1187. }
  1188. /**
  1189. * Returns the child nodes as a JSON object.
  1190. *
  1191. * @return {Object} The serialized child objects as JSON.
  1192. */
  1193. getSerializeChildren() {
  1194. return getNodeChildren( this );
  1195. }
  1196. /**
  1197. * Serializes the node to JSON.
  1198. *
  1199. * @param {Object} json - The output JSON object.
  1200. */
  1201. serialize( json ) {
  1202. const nodeChildren = this.getSerializeChildren();
  1203. const inputNodes = {};
  1204. for ( const { property, index, childNode } of nodeChildren ) {
  1205. if ( index !== undefined ) {
  1206. if ( inputNodes[ property ] === undefined ) {
  1207. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1208. }
  1209. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1210. } else {
  1211. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1212. }
  1213. }
  1214. if ( Object.keys( inputNodes ).length > 0 ) {
  1215. json.inputNodes = inputNodes;
  1216. }
  1217. }
  1218. /**
  1219. * Deserializes the node from the given JSON.
  1220. *
  1221. * @param {Object} json - The JSON object.
  1222. */
  1223. deserialize( json ) {
  1224. if ( json.inputNodes !== undefined ) {
  1225. const nodes = json.meta.nodes;
  1226. for ( const property in json.inputNodes ) {
  1227. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1228. const inputArray = [];
  1229. for ( const uuid of json.inputNodes[ property ] ) {
  1230. inputArray.push( nodes[ uuid ] );
  1231. }
  1232. this[ property ] = inputArray;
  1233. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1234. const inputObject = {};
  1235. for ( const subProperty in json.inputNodes[ property ] ) {
  1236. const uuid = json.inputNodes[ property ][ subProperty ];
  1237. inputObject[ subProperty ] = nodes[ uuid ];
  1238. }
  1239. this[ property ] = inputObject;
  1240. } else {
  1241. const uuid = json.inputNodes[ property ];
  1242. this[ property ] = nodes[ uuid ];
  1243. }
  1244. }
  1245. }
  1246. }
  1247. /**
  1248. * Serializes the node into the three.js JSON Object/Scene format.
  1249. *
  1250. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1251. * @return {Object} The serialized node.
  1252. */
  1253. toJSON( meta ) {
  1254. const { uuid, type } = this;
  1255. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1256. if ( isRoot ) {
  1257. meta = {
  1258. textures: {},
  1259. images: {},
  1260. nodes: {}
  1261. };
  1262. }
  1263. // serialize
  1264. let data = meta.nodes[ uuid ];
  1265. if ( data === undefined ) {
  1266. data = {
  1267. uuid,
  1268. type,
  1269. meta,
  1270. metadata: {
  1271. version: 4.6,
  1272. type: 'Node',
  1273. generator: 'Node.toJSON'
  1274. }
  1275. };
  1276. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1277. this.serialize( data );
  1278. delete data.meta;
  1279. }
  1280. // TODO: Copied from Object3D.toJSON
  1281. function extractFromCache( cache ) {
  1282. const values = [];
  1283. for ( const key in cache ) {
  1284. const data = cache[ key ];
  1285. delete data.metadata;
  1286. values.push( data );
  1287. }
  1288. return values;
  1289. }
  1290. if ( isRoot ) {
  1291. const textures = extractFromCache( meta.textures );
  1292. const images = extractFromCache( meta.images );
  1293. const nodes = extractFromCache( meta.nodes );
  1294. if ( textures.length > 0 ) data.textures = textures;
  1295. if ( images.length > 0 ) data.images = images;
  1296. if ( nodes.length > 0 ) data.nodes = nodes;
  1297. }
  1298. return data;
  1299. }
  1300. }
  1301. /**
  1302. * Base class for representing element access on an array-like
  1303. * node data structures.
  1304. *
  1305. * @augments Node
  1306. */
  1307. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1308. static get type() {
  1309. return 'ArrayElementNode';
  1310. }
  1311. /**
  1312. * Constructs an array element node.
  1313. *
  1314. * @param {Node} node - The array-like node.
  1315. * @param {Node} indexNode - The index node that defines the element access.
  1316. */
  1317. constructor( node, indexNode ) {
  1318. super();
  1319. /**
  1320. * The array-like node.
  1321. *
  1322. * @type {Node}
  1323. */
  1324. this.node = node;
  1325. /**
  1326. * The index node that defines the element access.
  1327. *
  1328. * @type {Node}
  1329. */
  1330. this.indexNode = indexNode;
  1331. /**
  1332. * This flag can be used for type testing.
  1333. *
  1334. * @type {Boolean}
  1335. * @readonly
  1336. * @default true
  1337. */
  1338. this.isArrayElementNode = true;
  1339. }
  1340. /**
  1341. * This method is overwritten since the node type is inferred from the array-like node.
  1342. *
  1343. * @param {NodeBuilder} builder - The current node builder.
  1344. * @return {String} The node type.
  1345. */
  1346. getNodeType( builder ) {
  1347. return this.node.getElementType( builder );
  1348. }
  1349. generate( builder ) {
  1350. const nodeSnippet = this.node.build( builder );
  1351. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1352. return `${nodeSnippet}[ ${indexSnippet} ]`;
  1353. }
  1354. }
  1355. /**
  1356. * This module is part of the TSL core and usually not used in app level code.
  1357. * It represents a convert operation during the shader generation process
  1358. * meaning it converts the data type of a node to a target data type.
  1359. *
  1360. * @augments Node
  1361. */
  1362. class ConvertNode extends Node {
  1363. static get type() {
  1364. return 'ConvertNode';
  1365. }
  1366. /**
  1367. * Constructs a new convert node.
  1368. *
  1369. * @param {Node} node - The node which type should be converted.
  1370. * @param {String} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1371. */
  1372. constructor( node, convertTo ) {
  1373. super();
  1374. /**
  1375. * The node which type should be converted.
  1376. *
  1377. * @type {Node}
  1378. */
  1379. this.node = node;
  1380. /**
  1381. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1382. *
  1383. * @type {String}
  1384. */
  1385. this.convertTo = convertTo;
  1386. }
  1387. /**
  1388. * This method is overwritten since the implementation tries to infer the best
  1389. * matching type from the {@link ConvertNode#convertTo} property.
  1390. *
  1391. * @param {NodeBuilder} builder - The current node builder.
  1392. * @return {String} The node type.
  1393. */
  1394. getNodeType( builder ) {
  1395. const requestType = this.node.getNodeType( builder );
  1396. let convertTo = null;
  1397. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1398. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1399. convertTo = overloadingType;
  1400. }
  1401. }
  1402. return convertTo;
  1403. }
  1404. serialize( data ) {
  1405. super.serialize( data );
  1406. data.convertTo = this.convertTo;
  1407. }
  1408. deserialize( data ) {
  1409. super.deserialize( data );
  1410. this.convertTo = data.convertTo;
  1411. }
  1412. generate( builder, output ) {
  1413. const node = this.node;
  1414. const type = this.getNodeType( builder );
  1415. const snippet = node.build( builder, type );
  1416. return builder.format( snippet, type, output );
  1417. }
  1418. }
  1419. /**
  1420. * This module uses cache management to create temporary variables
  1421. * if the node is used more than once to prevent duplicate calculations.
  1422. *
  1423. * The class acts as a base class for many other nodes types.
  1424. *
  1425. * @augments Node
  1426. */
  1427. class TempNode extends Node {
  1428. static get type() {
  1429. return 'TempNode';
  1430. }
  1431. /**
  1432. * Constructs a temp node.
  1433. *
  1434. * @param {String?} nodeType - The node type.
  1435. */
  1436. constructor( nodeType = null ) {
  1437. super( nodeType );
  1438. /**
  1439. * This flag can be used for type testing.
  1440. *
  1441. * @type {Boolean}
  1442. * @readonly
  1443. * @default true
  1444. */
  1445. this.isTempNode = true;
  1446. }
  1447. /**
  1448. * Whether this node is used more than once in context of other nodes.
  1449. *
  1450. * @param {NodeBuilder} builder - The node builder.
  1451. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1452. */
  1453. hasDependencies( builder ) {
  1454. return builder.getDataFromNode( this ).usageCount > 1;
  1455. }
  1456. build( builder, output ) {
  1457. const buildStage = builder.getBuildStage();
  1458. if ( buildStage === 'generate' ) {
  1459. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1460. const nodeData = builder.getDataFromNode( this );
  1461. if ( nodeData.propertyName !== undefined ) {
  1462. return builder.format( nodeData.propertyName, type, output );
  1463. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1464. const snippet = super.build( builder, type );
  1465. const nodeVar = builder.getVarFromNode( this, null, type );
  1466. const propertyName = builder.getPropertyName( nodeVar );
  1467. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  1468. nodeData.snippet = snippet;
  1469. nodeData.propertyName = propertyName;
  1470. return builder.format( nodeData.propertyName, type, output );
  1471. }
  1472. }
  1473. return super.build( builder, output );
  1474. }
  1475. }
  1476. /**
  1477. * This module is part of the TSL core and usually not used in app level code.
  1478. * It represents a join operation during the shader generation process.
  1479. * For example in can compose/join two single floats into a `vec2` type.
  1480. *
  1481. * @augments TempNode
  1482. */
  1483. class JoinNode extends TempNode {
  1484. static get type() {
  1485. return 'JoinNode';
  1486. }
  1487. /**
  1488. * Constructs a new join node.
  1489. *
  1490. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1491. * @param {String?} [nodeType=null] - The node type.
  1492. */
  1493. constructor( nodes = [], nodeType = null ) {
  1494. super( nodeType );
  1495. /**
  1496. * An array of nodes that should be joined.
  1497. *
  1498. * @type {Array<Node>}
  1499. */
  1500. this.nodes = nodes;
  1501. }
  1502. /**
  1503. * This method is overwritten since the node type must be inferred from the
  1504. * joined data length if not explicitly defined.
  1505. *
  1506. * @param {NodeBuilder} builder - The current node builder.
  1507. * @return {String} The node type.
  1508. */
  1509. getNodeType( builder ) {
  1510. if ( this.nodeType !== null ) {
  1511. return builder.getVectorType( this.nodeType );
  1512. }
  1513. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1514. }
  1515. generate( builder, output ) {
  1516. const type = this.getNodeType( builder );
  1517. const nodes = this.nodes;
  1518. const primitiveType = builder.getComponentType( type );
  1519. const snippetValues = [];
  1520. for ( const input of nodes ) {
  1521. let inputSnippet = input.build( builder );
  1522. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1523. if ( inputPrimitiveType !== primitiveType ) {
  1524. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1525. }
  1526. snippetValues.push( inputSnippet );
  1527. }
  1528. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1529. return builder.format( snippet, type, output );
  1530. }
  1531. }
  1532. const _stringVectorComponents = vectorComponents.join( '' );
  1533. /**
  1534. * This module is part of the TSL core and usually not used in app level code.
  1535. * `SplitNode` represents a property access operation which means it is
  1536. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1537. * For example:
  1538. * ```js
  1539. * const redValue = color.r;
  1540. * ```
  1541. *
  1542. * @augments Node
  1543. */
  1544. class SplitNode extends Node {
  1545. static get type() {
  1546. return 'SplitNode';
  1547. }
  1548. /**
  1549. * Constructs a new split node.
  1550. *
  1551. * @param {Node} node - The node that should be accessed.
  1552. * @param {String} [components='x'] - The components that should be accessed.
  1553. */
  1554. constructor( node, components = 'x' ) {
  1555. super();
  1556. /**
  1557. * The node that should be accessed.
  1558. *
  1559. * @type {Node}
  1560. */
  1561. this.node = node;
  1562. /**
  1563. * The components that should be accessed.
  1564. *
  1565. * @type {string}
  1566. */
  1567. this.components = components;
  1568. /**
  1569. * This flag can be used for type testing.
  1570. *
  1571. * @type {Boolean}
  1572. * @readonly
  1573. * @default true
  1574. */
  1575. this.isSplitNode = true;
  1576. }
  1577. /**
  1578. * Returns the vector length which is computed based on the requested components.
  1579. *
  1580. * @return {Number} The vector length.
  1581. */
  1582. getVectorLength() {
  1583. let vectorLength = this.components.length;
  1584. for ( const c of this.components ) {
  1585. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1586. }
  1587. return vectorLength;
  1588. }
  1589. /**
  1590. * Returns the component type of the node's type.
  1591. *
  1592. * @param {NodeBuilder} builder - The current node builder.
  1593. * @return {String} The component type.
  1594. */
  1595. getComponentType( builder ) {
  1596. return builder.getComponentType( this.node.getNodeType( builder ) );
  1597. }
  1598. /**
  1599. * This method is overwritten since the node type is inferred from requested components.
  1600. *
  1601. * @param {NodeBuilder} builder - The current node builder.
  1602. * @return {String} The node type.
  1603. */
  1604. getNodeType( builder ) {
  1605. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1606. }
  1607. generate( builder, output ) {
  1608. const node = this.node;
  1609. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1610. let snippet = null;
  1611. if ( nodeTypeLength > 1 ) {
  1612. let type = null;
  1613. const componentsLength = this.getVectorLength();
  1614. if ( componentsLength >= nodeTypeLength ) {
  1615. // needed expand the input node
  1616. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1617. }
  1618. const nodeSnippet = node.build( builder, type );
  1619. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1620. // unnecessary swizzle
  1621. snippet = builder.format( nodeSnippet, type, output );
  1622. } else {
  1623. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1624. }
  1625. } else {
  1626. // ignore .components if .node returns float/integer
  1627. snippet = node.build( builder, output );
  1628. }
  1629. return snippet;
  1630. }
  1631. serialize( data ) {
  1632. super.serialize( data );
  1633. data.components = this.components;
  1634. }
  1635. deserialize( data ) {
  1636. super.deserialize( data );
  1637. this.components = data.components;
  1638. }
  1639. }
  1640. /**
  1641. * This module is part of the TSL core and usually not used in app level code.
  1642. * `SetNode` represents a set operation which means it is used to implement any
  1643. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1644. * For example:
  1645. * ```js
  1646. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1647. * ```
  1648. *
  1649. * @augments TempNode
  1650. */
  1651. class SetNode extends TempNode {
  1652. static get type() {
  1653. return 'SetNode';
  1654. }
  1655. /**
  1656. * Constructs a new set node.
  1657. *
  1658. * @param {Node} sourceNode - The node that should be updated.
  1659. * @param {String} components - The components that should be updated.
  1660. * @param {Node} targetNode - The value node.
  1661. */
  1662. constructor( sourceNode, components, targetNode ) {
  1663. super();
  1664. /**
  1665. * The node that should be updated.
  1666. *
  1667. * @type {Node}
  1668. */
  1669. this.sourceNode = sourceNode;
  1670. /**
  1671. * The components that should be updated.
  1672. *
  1673. * @type {String}
  1674. */
  1675. this.components = components;
  1676. /**
  1677. * The value node.
  1678. *
  1679. * @type {Node}
  1680. */
  1681. this.targetNode = targetNode;
  1682. }
  1683. /**
  1684. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1685. *
  1686. * @param {NodeBuilder} builder - The current node builder.
  1687. * @return {String} The node type.
  1688. */
  1689. getNodeType( builder ) {
  1690. return this.sourceNode.getNodeType( builder );
  1691. }
  1692. generate( builder ) {
  1693. const { sourceNode, components, targetNode } = this;
  1694. const sourceType = this.getNodeType( builder );
  1695. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1696. const targetType = builder.getTypeFromLength( components.length, componentType );
  1697. const targetSnippet = targetNode.build( builder, targetType );
  1698. const sourceSnippet = sourceNode.build( builder, sourceType );
  1699. const length = builder.getTypeLength( sourceType );
  1700. const snippetValues = [];
  1701. for ( let i = 0; i < length; i ++ ) {
  1702. const component = vectorComponents[ i ];
  1703. if ( component === components[ 0 ] ) {
  1704. snippetValues.push( targetSnippet );
  1705. i += components.length - 1;
  1706. } else {
  1707. snippetValues.push( sourceSnippet + '.' + component );
  1708. }
  1709. }
  1710. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1711. }
  1712. }
  1713. /**
  1714. * This module is part of the TSL core and usually not used in app level code.
  1715. * It represents a flip operation during the shader generation process
  1716. * meaning it flips normalized values with the following formula:
  1717. * ```
  1718. * x = 1 - x;
  1719. * ```
  1720. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1721. * `flipSTPQ()` method invocations on node objects. For example:
  1722. * ```js
  1723. * uvNode = uvNode.flipY();
  1724. * ```
  1725. *
  1726. * @augments TempNode
  1727. */
  1728. class FlipNode extends TempNode {
  1729. static get type() {
  1730. return 'FlipNode';
  1731. }
  1732. /**
  1733. * Constructs a new flip node.
  1734. *
  1735. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1736. * @param {String} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1737. */
  1738. constructor( sourceNode, components ) {
  1739. super();
  1740. /**
  1741. * The node which component(s) should be flipped.
  1742. *
  1743. * @type {Node}
  1744. */
  1745. this.sourceNode = sourceNode;
  1746. /**
  1747. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1748. *
  1749. * @type {String}
  1750. */
  1751. this.components = components;
  1752. }
  1753. /**
  1754. * This method is overwritten since the node type is inferred from the source node.
  1755. *
  1756. * @param {NodeBuilder} builder - The current node builder.
  1757. * @return {String} The node type.
  1758. */
  1759. getNodeType( builder ) {
  1760. return this.sourceNode.getNodeType( builder );
  1761. }
  1762. generate( builder ) {
  1763. const { components, sourceNode } = this;
  1764. const sourceType = this.getNodeType( builder );
  1765. const sourceSnippet = sourceNode.build( builder );
  1766. const sourceCache = builder.getVarFromNode( this );
  1767. const sourceProperty = builder.getPropertyName( sourceCache );
  1768. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1769. const length = builder.getTypeLength( sourceType );
  1770. const snippetValues = [];
  1771. let componentIndex = 0;
  1772. for ( let i = 0; i < length; i ++ ) {
  1773. const component = vectorComponents[ i ];
  1774. if ( component === components[ componentIndex ] ) {
  1775. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1776. componentIndex ++;
  1777. } else {
  1778. snippetValues.push( sourceProperty + '.' + component );
  1779. }
  1780. }
  1781. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1782. }
  1783. }
  1784. /**
  1785. * Base class for representing data input nodes.
  1786. *
  1787. * @augments Node
  1788. */
  1789. class InputNode extends Node {
  1790. static get type() {
  1791. return 'InputNode';
  1792. }
  1793. /**
  1794. * Constructs a new input node.
  1795. *
  1796. * @param {Any} value - The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1797. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1798. */
  1799. constructor( value, nodeType = null ) {
  1800. super( nodeType );
  1801. /**
  1802. * This flag can be used for type testing.
  1803. *
  1804. * @type {Boolean}
  1805. * @readonly
  1806. * @default true
  1807. */
  1808. this.isInputNode = true;
  1809. /**
  1810. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1811. *
  1812. * @type {Any}
  1813. */
  1814. this.value = value;
  1815. /**
  1816. * The precision of the value in the shader.
  1817. *
  1818. * @type {('low'|'medium'|'high')?}
  1819. * @default null
  1820. */
  1821. this.precision = null;
  1822. }
  1823. getNodeType( /*builder*/ ) {
  1824. if ( this.nodeType === null ) {
  1825. return getValueType( this.value );
  1826. }
  1827. return this.nodeType;
  1828. }
  1829. /**
  1830. * Returns the input type of the node which is by default the node type. Derived modules
  1831. * might overwrite this method and use a fixed type or compute one analytically.
  1832. *
  1833. * A typical example for different input and node types are textures. The input type of a
  1834. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1835. *
  1836. * @param {NodeBuilder} builder - The current node builder.
  1837. * @return {String} The input type.
  1838. */
  1839. getInputType( builder ) {
  1840. return this.getNodeType( builder );
  1841. }
  1842. /**
  1843. * Sets the precision to the given value. The method can be
  1844. * overwritten in derived classes if the final precision must be computed
  1845. * analytically.
  1846. *
  1847. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1848. * @return {InputNode} A reference to this node.
  1849. */
  1850. setPrecision( precision ) {
  1851. this.precision = precision;
  1852. return this;
  1853. }
  1854. serialize( data ) {
  1855. super.serialize( data );
  1856. data.value = this.value;
  1857. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1858. data.valueType = getValueType( this.value );
  1859. data.nodeType = this.nodeType;
  1860. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1861. data.precision = this.precision;
  1862. }
  1863. deserialize( data ) {
  1864. super.deserialize( data );
  1865. this.nodeType = data.nodeType;
  1866. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1867. this.precision = data.precision || null;
  1868. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1869. }
  1870. generate( /*builder, output*/ ) {
  1871. console.warn( 'Abstract function.' );
  1872. }
  1873. }
  1874. /**
  1875. * Class for representing a constant value in the shader.
  1876. *
  1877. * @augments InputNode
  1878. */
  1879. class ConstNode extends InputNode {
  1880. static get type() {
  1881. return 'ConstNode';
  1882. }
  1883. /**
  1884. * Constructs a new input node.
  1885. *
  1886. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1887. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1888. */
  1889. constructor( value, nodeType = null ) {
  1890. super( value, nodeType );
  1891. /**
  1892. * This flag can be used for type testing.
  1893. *
  1894. * @type {Boolean}
  1895. * @readonly
  1896. * @default true
  1897. */
  1898. this.isConstNode = true;
  1899. }
  1900. /**
  1901. * Generates the shader string of the value with the current node builder.
  1902. *
  1903. * @param {NodeBuilder} builder - The current node builder.
  1904. * @return {String} The generated value as a shader string.
  1905. */
  1906. generateConst( builder ) {
  1907. return builder.generateConst( this.getNodeType( builder ), this.value );
  1908. }
  1909. generate( builder, output ) {
  1910. const type = this.getNodeType( builder );
  1911. return builder.format( this.generateConst( builder ), type, output );
  1912. }
  1913. }
  1914. //
  1915. let currentStack = null;
  1916. const NodeElements = new Map();
  1917. function addMethodChaining( name, nodeElement ) {
  1918. if ( NodeElements.has( name ) ) {
  1919. console.warn( `Redefinition of method chaining ${ name }` );
  1920. return;
  1921. }
  1922. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1923. NodeElements.set( name, nodeElement );
  1924. }
  1925. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1926. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1927. const shaderNodeHandler = {
  1928. setup( NodeClosure, params ) {
  1929. const inputs = params.shift();
  1930. return NodeClosure( nodeObjects( inputs ), ...params );
  1931. },
  1932. get( node, prop, nodeObj ) {
  1933. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1934. if ( node.isStackNode !== true && prop === 'assign' ) {
  1935. return ( ...params ) => {
  1936. currentStack.assign( nodeObj, ...params );
  1937. return nodeObj;
  1938. };
  1939. } else if ( NodeElements.has( prop ) ) {
  1940. const nodeElement = NodeElements.get( prop );
  1941. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1942. } else if ( prop === 'self' ) {
  1943. return node;
  1944. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1945. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1946. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1947. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1948. // accessing properties ( swizzle )
  1949. prop = parseSwizzle( prop );
  1950. return nodeObject( new SplitNode( nodeObj, prop ) );
  1951. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1952. // set properties ( swizzle ) and sort to xyzw sequence
  1953. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1954. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1955. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1956. // set properties ( swizzle ) and sort to xyzw sequence
  1957. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1958. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1959. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1960. // accessing property
  1961. if ( prop === 'width' ) prop = 'x';
  1962. else if ( prop === 'height' ) prop = 'y';
  1963. else if ( prop === 'depth' ) prop = 'z';
  1964. return nodeObject( new SplitNode( node, prop ) );
  1965. } else if ( /^\d+$/.test( prop ) === true ) {
  1966. // accessing array
  1967. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1968. }
  1969. }
  1970. return Reflect.get( node, prop, nodeObj );
  1971. },
  1972. set( node, prop, value, nodeObj ) {
  1973. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1974. // setting properties
  1975. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1976. nodeObj[ prop ].assign( value );
  1977. return true;
  1978. }
  1979. }
  1980. return Reflect.set( node, prop, value, nodeObj );
  1981. }
  1982. };
  1983. const nodeObjectsCacheMap = new WeakMap();
  1984. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1985. const ShaderNodeObject = function ( obj, altType = null ) {
  1986. const type = getValueType( obj );
  1987. if ( type === 'node' ) {
  1988. let nodeObject = nodeObjectsCacheMap.get( obj );
  1989. if ( nodeObject === undefined ) {
  1990. nodeObject = new Proxy( obj, shaderNodeHandler );
  1991. nodeObjectsCacheMap.set( obj, nodeObject );
  1992. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1993. }
  1994. return nodeObject;
  1995. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1996. return nodeObject( getConstNode( obj, altType ) );
  1997. } else if ( type === 'shader' ) {
  1998. return Fn( obj );
  1999. }
  2000. return obj;
  2001. };
  2002. const ShaderNodeObjects = function ( objects, altType = null ) {
  2003. for ( const name in objects ) {
  2004. objects[ name ] = nodeObject( objects[ name ], altType );
  2005. }
  2006. return objects;
  2007. };
  2008. const ShaderNodeArray = function ( array, altType = null ) {
  2009. const len = array.length;
  2010. for ( let i = 0; i < len; i ++ ) {
  2011. array[ i ] = nodeObject( array[ i ], altType );
  2012. }
  2013. return array;
  2014. };
  2015. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2016. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2017. if ( scope === null ) {
  2018. return ( ...params ) => {
  2019. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  2020. };
  2021. } else if ( factor !== null ) {
  2022. factor = nodeObject( factor );
  2023. return ( ...params ) => {
  2024. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  2025. };
  2026. } else {
  2027. return ( ...params ) => {
  2028. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  2029. };
  2030. }
  2031. };
  2032. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2033. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2034. };
  2035. class ShaderCallNodeInternal extends Node {
  2036. constructor( shaderNode, inputNodes ) {
  2037. super();
  2038. this.shaderNode = shaderNode;
  2039. this.inputNodes = inputNodes;
  2040. }
  2041. getNodeType( builder ) {
  2042. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2043. }
  2044. call( builder ) {
  2045. const { shaderNode, inputNodes } = this;
  2046. const properties = builder.getNodeProperties( shaderNode );
  2047. if ( properties.onceOutput ) return properties.onceOutput;
  2048. //
  2049. let result = null;
  2050. if ( shaderNode.layout ) {
  2051. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2052. if ( functionNodesCacheMap === undefined ) {
  2053. functionNodesCacheMap = new WeakMap();
  2054. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2055. }
  2056. let functionNode = functionNodesCacheMap.get( shaderNode );
  2057. if ( functionNode === undefined ) {
  2058. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2059. functionNodesCacheMap.set( shaderNode, functionNode );
  2060. }
  2061. if ( builder.currentFunctionNode !== null ) {
  2062. builder.currentFunctionNode.includes.push( functionNode );
  2063. }
  2064. result = nodeObject( functionNode.call( inputNodes ) );
  2065. } else {
  2066. const jsFunc = shaderNode.jsFunc;
  2067. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  2068. result = nodeObject( outputNode );
  2069. }
  2070. if ( shaderNode.once ) {
  2071. properties.onceOutput = result;
  2072. }
  2073. return result;
  2074. }
  2075. getOutputNode( builder ) {
  2076. const properties = builder.getNodeProperties( this );
  2077. if ( properties.outputNode === null ) {
  2078. properties.outputNode = this.setupOutput( builder );
  2079. }
  2080. return properties.outputNode;
  2081. }
  2082. setup( builder ) {
  2083. return this.getOutputNode( builder );
  2084. }
  2085. setupOutput( builder ) {
  2086. builder.addStack();
  2087. builder.stack.outputNode = this.call( builder );
  2088. return builder.removeStack();
  2089. }
  2090. generate( builder, output ) {
  2091. const outputNode = this.getOutputNode( builder );
  2092. return outputNode.build( builder, output );
  2093. }
  2094. }
  2095. class ShaderNodeInternal extends Node {
  2096. constructor( jsFunc, nodeType ) {
  2097. super( nodeType );
  2098. this.jsFunc = jsFunc;
  2099. this.layout = null;
  2100. this.global = true;
  2101. this.once = false;
  2102. }
  2103. setLayout( layout ) {
  2104. this.layout = layout;
  2105. return this;
  2106. }
  2107. call( inputs = null ) {
  2108. nodeObjects( inputs );
  2109. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2110. }
  2111. setup() {
  2112. return this.call();
  2113. }
  2114. }
  2115. const bools = [ false, true ];
  2116. const uints = [ 0, 1, 2, 3 ];
  2117. const ints = [ - 1, - 2 ];
  2118. const floats = [ 0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / ( Math.PI * 2 ), Math.PI / 2 ];
  2119. const boolsCacheMap = new Map();
  2120. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2121. const uintsCacheMap = new Map();
  2122. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2123. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2124. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2125. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2126. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2127. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2128. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2129. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2130. const getConstNode = ( value, type ) => {
  2131. if ( constNodesCacheMap.has( value ) ) {
  2132. return constNodesCacheMap.get( value );
  2133. } else if ( value.isNode === true ) {
  2134. return value;
  2135. } else {
  2136. return new ConstNode( value, type );
  2137. }
  2138. };
  2139. const safeGetNodeType = ( node ) => {
  2140. try {
  2141. return node.getNodeType();
  2142. } catch ( _ ) {
  2143. return undefined;
  2144. }
  2145. };
  2146. const ConvertType = function ( type, cacheMap = null ) {
  2147. return ( ...params ) => {
  2148. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2149. params = [ getValueFromType( type, ...params ) ];
  2150. }
  2151. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2152. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2153. }
  2154. if ( params.length === 1 ) {
  2155. const node = getConstNode( params[ 0 ], type );
  2156. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2157. return nodeObject( new ConvertNode( node, type ) );
  2158. }
  2159. const nodes = params.map( param => getConstNode( param ) );
  2160. return nodeObject( new JoinNode( nodes, type ) );
  2161. };
  2162. };
  2163. // exports
  2164. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2165. // utils
  2166. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2167. // shader node base
  2168. function ShaderNode( jsFunc, nodeType ) {
  2169. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2170. }
  2171. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2172. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2173. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2174. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2175. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2176. const Fn = ( jsFunc, nodeType ) => {
  2177. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2178. const fn = ( ...params ) => {
  2179. let inputs;
  2180. nodeObjects( params );
  2181. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2182. inputs = [ ...params ];
  2183. } else {
  2184. inputs = params[ 0 ];
  2185. }
  2186. return shaderNode.call( inputs );
  2187. };
  2188. fn.shaderNode = shaderNode;
  2189. fn.setLayout = ( layout ) => {
  2190. shaderNode.setLayout( layout );
  2191. return fn;
  2192. };
  2193. fn.once = () => {
  2194. shaderNode.once = true;
  2195. return fn;
  2196. };
  2197. return fn;
  2198. };
  2199. const tslFn = ( ...params ) => { // @deprecated, r168
  2200. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2201. return Fn( ...params );
  2202. };
  2203. //
  2204. addMethodChaining( 'toGlobal', ( node ) => {
  2205. node.global = true;
  2206. return node;
  2207. } );
  2208. //
  2209. const setCurrentStack = ( stack ) => {
  2210. currentStack = stack;
  2211. };
  2212. const getCurrentStack = () => currentStack;
  2213. const If = ( ...params ) => currentStack.If( ...params );
  2214. function append( node ) {
  2215. if ( currentStack ) currentStack.add( node );
  2216. return node;
  2217. }
  2218. addMethodChaining( 'append', append );
  2219. // types
  2220. const color = new ConvertType( 'color' );
  2221. const float = new ConvertType( 'float', cacheMaps.float );
  2222. const int = new ConvertType( 'int', cacheMaps.ints );
  2223. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2224. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2225. const vec2 = new ConvertType( 'vec2' );
  2226. const ivec2 = new ConvertType( 'ivec2' );
  2227. const uvec2 = new ConvertType( 'uvec2' );
  2228. const bvec2 = new ConvertType( 'bvec2' );
  2229. const vec3 = new ConvertType( 'vec3' );
  2230. const ivec3 = new ConvertType( 'ivec3' );
  2231. const uvec3 = new ConvertType( 'uvec3' );
  2232. const bvec3 = new ConvertType( 'bvec3' );
  2233. const vec4 = new ConvertType( 'vec4' );
  2234. const ivec4 = new ConvertType( 'ivec4' );
  2235. const uvec4 = new ConvertType( 'uvec4' );
  2236. const bvec4 = new ConvertType( 'bvec4' );
  2237. const mat2 = new ConvertType( 'mat2' );
  2238. const mat3 = new ConvertType( 'mat3' );
  2239. const mat4 = new ConvertType( 'mat4' );
  2240. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2241. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2242. addMethodChaining( 'toColor', color );
  2243. addMethodChaining( 'toFloat', float );
  2244. addMethodChaining( 'toInt', int );
  2245. addMethodChaining( 'toUint', uint );
  2246. addMethodChaining( 'toBool', bool );
  2247. addMethodChaining( 'toVec2', vec2 );
  2248. addMethodChaining( 'toIVec2', ivec2 );
  2249. addMethodChaining( 'toUVec2', uvec2 );
  2250. addMethodChaining( 'toBVec2', bvec2 );
  2251. addMethodChaining( 'toVec3', vec3 );
  2252. addMethodChaining( 'toIVec3', ivec3 );
  2253. addMethodChaining( 'toUVec3', uvec3 );
  2254. addMethodChaining( 'toBVec3', bvec3 );
  2255. addMethodChaining( 'toVec4', vec4 );
  2256. addMethodChaining( 'toIVec4', ivec4 );
  2257. addMethodChaining( 'toUVec4', uvec4 );
  2258. addMethodChaining( 'toBVec4', bvec4 );
  2259. addMethodChaining( 'toMat2', mat2 );
  2260. addMethodChaining( 'toMat3', mat3 );
  2261. addMethodChaining( 'toMat4', mat4 );
  2262. // basic nodes
  2263. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2264. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2265. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2266. addMethodChaining( 'element', element );
  2267. addMethodChaining( 'convert', convert );
  2268. /** @module UniformGroupNode **/
  2269. /**
  2270. * This node can be used to group single instances of {@link UniformNode}
  2271. * and manage them as a uniform buffer.
  2272. *
  2273. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2274. * will be used when defining the {@link UniformNode#groupNode} property.
  2275. *
  2276. * - `objectGroup`: Uniform buffer per object.
  2277. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2278. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2279. *
  2280. * @augments Node
  2281. */
  2282. class UniformGroupNode extends Node {
  2283. static get type() {
  2284. return 'UniformGroupNode';
  2285. }
  2286. /**
  2287. * Constructs a new uniform group node.
  2288. *
  2289. * @param {String} name - The name of the uniform group node.
  2290. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  2291. * @param {Number} [order=1] - Influences the internal sorting.
  2292. */
  2293. constructor( name, shared = false, order = 1 ) {
  2294. super( 'string' );
  2295. /**
  2296. * The name of the uniform group node.
  2297. *
  2298. * @type {String}
  2299. */
  2300. this.name = name;
  2301. /**
  2302. * Whether this uniform group node is shared or not.
  2303. *
  2304. * @type {Boolean}
  2305. * @default false
  2306. */
  2307. this.shared = shared;
  2308. /**
  2309. * Influences the internal sorting.
  2310. * TODO: Add details when this property should be changed.
  2311. *
  2312. * @type {Number}
  2313. * @default 1
  2314. */
  2315. this.order = order;
  2316. /**
  2317. * This flag can be used for type testing.
  2318. *
  2319. * @type {Boolean}
  2320. * @readonly
  2321. * @default true
  2322. */
  2323. this.isUniformGroup = true;
  2324. }
  2325. serialize( data ) {
  2326. super.serialize( data );
  2327. data.name = this.name;
  2328. data.version = this.version;
  2329. data.shared = this.shared;
  2330. }
  2331. deserialize( data ) {
  2332. super.deserialize( data );
  2333. this.name = data.name;
  2334. this.version = data.version;
  2335. this.shared = data.shared;
  2336. }
  2337. }
  2338. /**
  2339. * TSL function for creating a uniform group node with the given name.
  2340. *
  2341. * @function
  2342. * @param {String} name - The name of the uniform group node.
  2343. * @returns {UniformGroupNode}
  2344. */
  2345. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2346. /**
  2347. * TSL function for creating a shared uniform group node with the given name and order.
  2348. *
  2349. * @function
  2350. * @param {String} name - The name of the uniform group node.
  2351. * @param {Number} [order=0] - Influences the internal sorting.
  2352. * @returns {UniformGroupNode}
  2353. */
  2354. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2355. /**
  2356. * TSL object that represents a shared uniform group node which is updated once per frame.
  2357. *
  2358. * @type {UniformGroupNode}
  2359. */
  2360. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2361. /**
  2362. * TSL object that represents a shared uniform group node which is updated once per render.
  2363. *
  2364. * @type {UniformGroupNode}
  2365. */
  2366. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2367. /**
  2368. * TSL object that represents a uniform group node which is updated once per object.
  2369. *
  2370. * @type {UniformGroupNode}
  2371. */
  2372. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2373. /** @module UniformNode **/
  2374. /**
  2375. * Class for representing a uniform.
  2376. *
  2377. * @augments InputNode
  2378. */
  2379. class UniformNode extends InputNode {
  2380. static get type() {
  2381. return 'UniformNode';
  2382. }
  2383. /**
  2384. * Constructs a new uniform node.
  2385. *
  2386. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2387. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2388. */
  2389. constructor( value, nodeType = null ) {
  2390. super( value, nodeType );
  2391. /**
  2392. * This flag can be used for type testing.
  2393. *
  2394. * @type {Boolean}
  2395. * @readonly
  2396. * @default true
  2397. */
  2398. this.isUniformNode = true;
  2399. /**
  2400. * The name or label of the uniform.
  2401. *
  2402. * @type {String}
  2403. * @default ''
  2404. */
  2405. this.name = '';
  2406. /**
  2407. * The uniform group of this uniform. By default, uniforms are
  2408. * managed per object but they might belong to a shared group
  2409. * which is updated per frame or render call.
  2410. *
  2411. * @type {UniformGroupNode}
  2412. */
  2413. this.groupNode = objectGroup;
  2414. }
  2415. /**
  2416. * Sets the {@link UniformNode#name} property.
  2417. *
  2418. * @param {String} name - The name of the uniform.
  2419. * @return {UniformNode} A reference to this node.
  2420. */
  2421. label( name ) {
  2422. this.name = name;
  2423. return this;
  2424. }
  2425. /**
  2426. * Sets the {@link UniformNode#groupNode} property.
  2427. *
  2428. * @param {UniformGroupNode} group - The uniform group.
  2429. * @return {UniformNode} A reference to this node.
  2430. */
  2431. setGroup( group ) {
  2432. this.groupNode = group;
  2433. return this;
  2434. }
  2435. /**
  2436. * Returns the {@link UniformNode#groupNode}.
  2437. *
  2438. * @return {UniformGroupNode} The uniform group.
  2439. */
  2440. getGroup() {
  2441. return this.groupNode;
  2442. }
  2443. /**
  2444. * By default, this method returns the result of {@link Node#getHash} but derived
  2445. * classes might overwrite this method with a different implementation.
  2446. *
  2447. * @param {NodeBuilder} builder - The current node builder.
  2448. * @return {String} The uniform hash.
  2449. */
  2450. getUniformHash( builder ) {
  2451. return this.getHash( builder );
  2452. }
  2453. onUpdate( callback, updateType ) {
  2454. const self = this.getSelf();
  2455. callback = callback.bind( self );
  2456. return super.onUpdate( ( frame ) => {
  2457. const value = callback( frame, self );
  2458. if ( value !== undefined ) {
  2459. this.value = value;
  2460. }
  2461. }, updateType );
  2462. }
  2463. generate( builder, output ) {
  2464. const type = this.getNodeType( builder );
  2465. const hash = this.getUniformHash( builder );
  2466. let sharedNode = builder.getNodeFromHash( hash );
  2467. if ( sharedNode === undefined ) {
  2468. builder.setHashNode( this, hash );
  2469. sharedNode = this;
  2470. }
  2471. const sharedNodeType = sharedNode.getInputType( builder );
  2472. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2473. const propertyName = builder.getPropertyName( nodeUniform );
  2474. if ( builder.context.label !== undefined ) delete builder.context.label;
  2475. return builder.format( propertyName, type, output );
  2476. }
  2477. }
  2478. /**
  2479. * TSL function for creating a uniform node.
  2480. *
  2481. * @function
  2482. * @param {Any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2483. * @param {String?} arg2 - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2484. * @returns {UniformNode}
  2485. */
  2486. const uniform = ( arg1, arg2 ) => {
  2487. const nodeType = getConstNodeType( arg2 || arg1 );
  2488. // @TODO: get ConstNode from .traverse() in the future
  2489. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2490. return nodeObject( new UniformNode( value, nodeType ) );
  2491. };
  2492. /** @module PropertyNode **/
  2493. /**
  2494. * This class represents a shader property. It can be used
  2495. * to explicitly define a property and assign a value to it.
  2496. *
  2497. * ```js
  2498. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2499. *```
  2500. * `PropertyNode` is used by the engine to predefined common material properties
  2501. * for TSL code.
  2502. *
  2503. * @augments Node
  2504. */
  2505. class PropertyNode extends Node {
  2506. static get type() {
  2507. return 'PropertyNode';
  2508. }
  2509. /**
  2510. * Constructs a new property node.
  2511. *
  2512. * @param {String} nodeType - The type of the node.
  2513. * @param {String?} [name=null] - The name of the property in the shader.
  2514. * @param {Boolean} [varying=false] - Whether this property is a varying or not.
  2515. */
  2516. constructor( nodeType, name = null, varying = false ) {
  2517. super( nodeType );
  2518. /**
  2519. * The name of the property in the shader. If no name is defined,
  2520. * the node system auto-generates one.
  2521. *
  2522. * @type {String?}
  2523. * @default null
  2524. */
  2525. this.name = name;
  2526. /**
  2527. * Whether this property is a varying or not.
  2528. *
  2529. * @type {Boolean}
  2530. * @default false
  2531. */
  2532. this.varying = varying;
  2533. /**
  2534. * This flag can be used for type testing.
  2535. *
  2536. * @type {Boolean}
  2537. * @readonly
  2538. * @default true
  2539. */
  2540. this.isPropertyNode = true;
  2541. }
  2542. getHash( builder ) {
  2543. return this.name || super.getHash( builder );
  2544. }
  2545. /**
  2546. * The method is overwritten so it always returns `true`.
  2547. *
  2548. * @param {NodeBuilder} builder - The current node builder.
  2549. * @return {Boolean} Whether this node is global or not.
  2550. */
  2551. isGlobal( /*builder*/ ) {
  2552. return true;
  2553. }
  2554. generate( builder ) {
  2555. let nodeVar;
  2556. if ( this.varying === true ) {
  2557. nodeVar = builder.getVaryingFromNode( this, this.name );
  2558. nodeVar.needsInterpolation = true;
  2559. } else {
  2560. nodeVar = builder.getVarFromNode( this, this.name );
  2561. }
  2562. return builder.getPropertyName( nodeVar );
  2563. }
  2564. }
  2565. /**
  2566. * TSL function for creating a property node.
  2567. *
  2568. * @function
  2569. * @param {String} type - The type of the node.
  2570. * @param {String?} [name=null] - The name of the property in the shader.
  2571. * @returns {PropertyNode}
  2572. */
  2573. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2574. /**
  2575. * TSL function for creating a varying property node.
  2576. *
  2577. * @function
  2578. * @param {String} type - The type of the node.
  2579. * @param {String?} [name=null] - The name of the varying in the shader.
  2580. * @returns {PropertyNode}
  2581. */
  2582. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2583. /**
  2584. * TSL object that represents the shader variable `DiffuseColor`.
  2585. *
  2586. * @type {PropertyNode<vec4>}
  2587. */
  2588. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2589. /**
  2590. * TSL object that represents the shader variable `EmissiveColor`.
  2591. *
  2592. * @type {PropertyNode<vec3>}
  2593. */
  2594. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2595. /**
  2596. * TSL object that represents the shader variable `Roughness`.
  2597. *
  2598. * @type {PropertyNode<float>}
  2599. */
  2600. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2601. /**
  2602. * TSL object that represents the shader variable `Metalness`.
  2603. *
  2604. * @type {PropertyNode<float>}
  2605. */
  2606. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2607. /**
  2608. * TSL object that represents the shader variable `Clearcoat`.
  2609. *
  2610. * @type {PropertyNode<float>}
  2611. */
  2612. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2613. /**
  2614. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2615. *
  2616. * @type {PropertyNode<float>}
  2617. */
  2618. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2619. /**
  2620. * TSL object that represents the shader variable `Sheen`.
  2621. *
  2622. * @type {PropertyNode<vec3>}
  2623. */
  2624. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2625. /**
  2626. * TSL object that represents the shader variable `SheenRoughness`.
  2627. *
  2628. * @type {PropertyNode<float>}
  2629. */
  2630. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2631. /**
  2632. * TSL object that represents the shader variable `Iridescence`.
  2633. *
  2634. * @type {PropertyNode<float>}
  2635. */
  2636. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2637. /**
  2638. * TSL object that represents the shader variable `IridescenceIOR`.
  2639. *
  2640. * @type {PropertyNode<float>}
  2641. */
  2642. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2643. /**
  2644. * TSL object that represents the shader variable `IridescenceThickness`.
  2645. *
  2646. * @type {PropertyNode<float>}
  2647. */
  2648. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2649. /**
  2650. * TSL object that represents the shader variable `AlphaT`.
  2651. *
  2652. * @type {PropertyNode<float>}
  2653. */
  2654. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2655. /**
  2656. * TSL object that represents the shader variable `Anisotropy`.
  2657. *
  2658. * @type {PropertyNode<float>}
  2659. */
  2660. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2661. /**
  2662. * TSL object that represents the shader variable `AnisotropyT`.
  2663. *
  2664. * @type {PropertyNode<vec3>}
  2665. */
  2666. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2667. /**
  2668. * TSL object that represents the shader variable `AnisotropyB`.
  2669. *
  2670. * @type {PropertyNode<vec3>}
  2671. */
  2672. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2673. /**
  2674. * TSL object that represents the shader variable `SpecularColor`.
  2675. *
  2676. * @type {PropertyNode<color>}
  2677. */
  2678. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2679. /**
  2680. * TSL object that represents the shader variable `SpecularF90`.
  2681. *
  2682. * @type {PropertyNode<float>}
  2683. */
  2684. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2685. /**
  2686. * TSL object that represents the shader variable `Shininess`.
  2687. *
  2688. * @type {PropertyNode<float>}
  2689. */
  2690. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2691. /**
  2692. * TSL object that represents the shader variable `Output`.
  2693. *
  2694. * @type {PropertyNode<vec4>}
  2695. */
  2696. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2697. /**
  2698. * TSL object that represents the shader variable `dashSize`.
  2699. *
  2700. * @type {PropertyNode<float>}
  2701. */
  2702. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2703. /**
  2704. * TSL object that represents the shader variable `gapSize`.
  2705. *
  2706. * @type {PropertyNode<float>}
  2707. */
  2708. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2709. /**
  2710. * TSL object that represents the shader variable `pointWidth`.
  2711. *
  2712. * @type {PropertyNode<float>}
  2713. */
  2714. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2715. /**
  2716. * TSL object that represents the shader variable `IOR`.
  2717. *
  2718. * @type {PropertyNode<float>}
  2719. */
  2720. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2721. /**
  2722. * TSL object that represents the shader variable `Transmission`.
  2723. *
  2724. * @type {PropertyNode<float>}
  2725. */
  2726. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2727. /**
  2728. * TSL object that represents the shader variable `Thickness`.
  2729. *
  2730. * @type {PropertyNode<float>}
  2731. */
  2732. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2733. /**
  2734. * TSL object that represents the shader variable `AttenuationDistance`.
  2735. *
  2736. * @type {PropertyNode<float>}
  2737. */
  2738. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2739. /**
  2740. * TSL object that represents the shader variable `AttenuationColor`.
  2741. *
  2742. * @type {PropertyNode<color>}
  2743. */
  2744. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2745. /**
  2746. * TSL object that represents the shader variable `Dispersion`.
  2747. *
  2748. * @type {PropertyNode<float>}
  2749. */
  2750. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2751. /** @module AssignNode **/
  2752. /**
  2753. * These node represents an assign operation. Meaning a node is assigned
  2754. * to another node.
  2755. *
  2756. * @augments TempNode
  2757. */
  2758. class AssignNode extends TempNode {
  2759. static get type() {
  2760. return 'AssignNode';
  2761. }
  2762. /**
  2763. * Constructs a new assign node.
  2764. *
  2765. * @param {Node} targetNode - The target node.
  2766. * @param {Node} sourceNode - The source type.
  2767. */
  2768. constructor( targetNode, sourceNode ) {
  2769. super();
  2770. /**
  2771. * The target node.
  2772. *
  2773. * @type {Node}
  2774. */
  2775. this.targetNode = targetNode;
  2776. /**
  2777. * The source node.
  2778. *
  2779. * @type {Node}
  2780. */
  2781. this.sourceNode = sourceNode;
  2782. }
  2783. /**
  2784. * Whether this node is used more than once in context of other nodes. This method
  2785. * is overwritten since it always returns `false` (assigns are unique).
  2786. *
  2787. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2788. */
  2789. hasDependencies() {
  2790. return false;
  2791. }
  2792. getNodeType( builder, output ) {
  2793. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2794. }
  2795. /**
  2796. * Whether a split is required when assigning source to target. This can happen when the component length of
  2797. * target and source data type does not match.
  2798. *
  2799. * @param {NodeBuilder} builder - The current node builder.
  2800. * @return {Boolean} Whether a split is required when assigning source to target.
  2801. */
  2802. needsSplitAssign( builder ) {
  2803. const { targetNode } = this;
  2804. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2805. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2806. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2807. return assignDifferentVector;
  2808. }
  2809. return false;
  2810. }
  2811. generate( builder, output ) {
  2812. const { targetNode, sourceNode } = this;
  2813. const needsSplitAssign = this.needsSplitAssign( builder );
  2814. const targetType = targetNode.getNodeType( builder );
  2815. const target = targetNode.context( { assign: true } ).build( builder );
  2816. const source = sourceNode.build( builder, targetType );
  2817. const sourceType = sourceNode.getNodeType( builder );
  2818. const nodeData = builder.getDataFromNode( this );
  2819. //
  2820. let snippet;
  2821. if ( nodeData.initialized === true ) {
  2822. if ( output !== 'void' ) {
  2823. snippet = target;
  2824. }
  2825. } else if ( needsSplitAssign ) {
  2826. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2827. const sourceProperty = builder.getPropertyName( sourceVar );
  2828. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2829. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2830. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2831. const component = targetNode.components[ i ];
  2832. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2833. }
  2834. if ( output !== 'void' ) {
  2835. snippet = target;
  2836. }
  2837. } else {
  2838. snippet = `${ target } = ${ source }`;
  2839. if ( output === 'void' || sourceType === 'void' ) {
  2840. builder.addLineFlowCode( snippet, this );
  2841. if ( output !== 'void' ) {
  2842. snippet = target;
  2843. }
  2844. }
  2845. }
  2846. nodeData.initialized = true;
  2847. return builder.format( snippet, targetType, output );
  2848. }
  2849. }
  2850. /**
  2851. * TSL function for creating an assign node.
  2852. *
  2853. * @function
  2854. * @param {Node} targetNode - The target node.
  2855. * @param {Node} sourceNode - The source type.
  2856. * @returns {AssignNode}
  2857. */
  2858. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2859. addMethodChaining( 'assign', assign );
  2860. /**
  2861. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2862. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2863. * this logic.
  2864. *
  2865. * @augments TempNode
  2866. */
  2867. class FunctionCallNode extends TempNode {
  2868. static get type() {
  2869. return 'FunctionCallNode';
  2870. }
  2871. /**
  2872. * Constructs a new function call node.
  2873. *
  2874. * @param {FunctionNode?} functionNode - The function node.
  2875. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2876. */
  2877. constructor( functionNode = null, parameters = {} ) {
  2878. super();
  2879. /**
  2880. * The function node.
  2881. *
  2882. * @type {FunctionNode}
  2883. * @default null
  2884. */
  2885. this.functionNode = functionNode;
  2886. /**
  2887. * The parameters of the function call.
  2888. *
  2889. * @type {Object<String, Node>}
  2890. * @default {}
  2891. */
  2892. this.parameters = parameters;
  2893. }
  2894. /**
  2895. * Sets the parameters of the function call node.
  2896. *
  2897. * @param {Object<String, Node>} parameters - The parameters to set.
  2898. * @return {FunctionCallNode} A reference to this node.
  2899. */
  2900. setParameters( parameters ) {
  2901. this.parameters = parameters;
  2902. return this;
  2903. }
  2904. /**
  2905. * Returns the parameters of the function call node.
  2906. *
  2907. * @return {Object<String, Node>} The parameters of this node.
  2908. */
  2909. getParameters() {
  2910. return this.parameters;
  2911. }
  2912. getNodeType( builder ) {
  2913. return this.functionNode.getNodeType( builder );
  2914. }
  2915. generate( builder ) {
  2916. const params = [];
  2917. const functionNode = this.functionNode;
  2918. const inputs = functionNode.getInputs( builder );
  2919. const parameters = this.parameters;
  2920. const generateInput = ( node, inputNode ) => {
  2921. const type = inputNode.type;
  2922. const pointer = type === 'pointer';
  2923. let output;
  2924. if ( pointer ) output = '&' + node.build( builder );
  2925. else output = node.build( builder, type );
  2926. return output;
  2927. };
  2928. if ( Array.isArray( parameters ) ) {
  2929. for ( let i = 0; i < parameters.length; i ++ ) {
  2930. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  2931. }
  2932. } else {
  2933. for ( const inputNode of inputs ) {
  2934. const node = parameters[ inputNode.name ];
  2935. if ( node !== undefined ) {
  2936. params.push( generateInput( node, inputNode ) );
  2937. } else {
  2938. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  2939. }
  2940. }
  2941. }
  2942. const functionName = functionNode.build( builder, 'property' );
  2943. return `${functionName}( ${params.join( ', ' )} )`;
  2944. }
  2945. }
  2946. const call = ( func, ...params ) => {
  2947. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  2948. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  2949. };
  2950. addMethodChaining( 'call', call );
  2951. /** @module OperatorNode **/
  2952. /**
  2953. * This node represents basic mathematical and logical operations like addition,
  2954. * subtraction or comparisons (e.g. `equal()`).
  2955. *
  2956. * @augments TempNode
  2957. */
  2958. class OperatorNode extends TempNode {
  2959. static get type() {
  2960. return 'OperatorNode';
  2961. }
  2962. /**
  2963. * Constructs a new operator node.
  2964. *
  2965. * @param {String} op - The operator.
  2966. * @param {Node} aNode - The first input.
  2967. * @param {Node} bNode - The second input.
  2968. * @param {...Node} params - Additional input parameters.
  2969. */
  2970. constructor( op, aNode, bNode, ...params ) {
  2971. super();
  2972. if ( params.length > 0 ) {
  2973. let finalOp = new OperatorNode( op, aNode, bNode );
  2974. for ( let i = 0; i < params.length - 1; i ++ ) {
  2975. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  2976. }
  2977. aNode = finalOp;
  2978. bNode = params[ params.length - 1 ];
  2979. }
  2980. /**
  2981. * The operator.
  2982. *
  2983. * @type {String}
  2984. */
  2985. this.op = op;
  2986. /**
  2987. * The first input.
  2988. *
  2989. * @type {Node}
  2990. */
  2991. this.aNode = aNode;
  2992. /**
  2993. * The second input.
  2994. *
  2995. * @type {Node}
  2996. */
  2997. this.bNode = bNode;
  2998. }
  2999. /**
  3000. * This method is overwritten since the node type is inferred from the operator
  3001. * and the input node types.
  3002. *
  3003. * @param {NodeBuilder} builder - The current node builder.
  3004. * @param {String} output - The current output string.
  3005. * @return {String} The node type.
  3006. */
  3007. getNodeType( builder, output ) {
  3008. const op = this.op;
  3009. const aNode = this.aNode;
  3010. const bNode = this.bNode;
  3011. const typeA = aNode.getNodeType( builder );
  3012. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3013. if ( typeA === 'void' || typeB === 'void' ) {
  3014. return 'void';
  3015. } else if ( op === '%' ) {
  3016. return typeA;
  3017. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3018. return builder.getIntegerType( typeA );
  3019. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  3020. return 'bool';
  3021. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3022. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3023. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3024. } else {
  3025. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3026. return typeB;
  3027. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  3028. // matrix x vector
  3029. return builder.getVectorFromMatrix( typeA );
  3030. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  3031. // vector x matrix
  3032. return builder.getVectorFromMatrix( typeB );
  3033. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3034. // anytype x anytype: use the greater length vector
  3035. return typeB;
  3036. }
  3037. return typeA;
  3038. }
  3039. }
  3040. generate( builder, output ) {
  3041. const op = this.op;
  3042. const aNode = this.aNode;
  3043. const bNode = this.bNode;
  3044. const type = this.getNodeType( builder, output );
  3045. let typeA = null;
  3046. let typeB = null;
  3047. if ( type !== 'void' ) {
  3048. typeA = aNode.getNodeType( builder );
  3049. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3050. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  3051. if ( builder.isVector( typeA ) ) {
  3052. typeB = typeA;
  3053. } else if ( typeA !== typeB ) {
  3054. typeA = typeB = 'float';
  3055. }
  3056. } else if ( op === '>>' || op === '<<' ) {
  3057. typeA = type;
  3058. typeB = builder.changeComponentType( typeB, 'uint' );
  3059. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  3060. // matrix x vector
  3061. typeB = builder.getVectorFromMatrix( typeA );
  3062. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  3063. // vector x matrix
  3064. typeA = builder.getVectorFromMatrix( typeB );
  3065. } else {
  3066. // anytype x anytype
  3067. typeA = typeB = type;
  3068. }
  3069. } else {
  3070. typeA = typeB = type;
  3071. }
  3072. const a = aNode.build( builder, typeA );
  3073. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3074. const outputLength = builder.getTypeLength( output );
  3075. const fnOpSnippet = builder.getFunctionOperator( op );
  3076. if ( output !== 'void' ) {
  3077. if ( op === '<' && outputLength > 1 ) {
  3078. if ( builder.useComparisonMethod ) {
  3079. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3080. } else {
  3081. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3082. }
  3083. } else if ( op === '<=' && outputLength > 1 ) {
  3084. if ( builder.useComparisonMethod ) {
  3085. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3086. } else {
  3087. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3088. }
  3089. } else if ( op === '>' && outputLength > 1 ) {
  3090. if ( builder.useComparisonMethod ) {
  3091. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3092. } else {
  3093. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3094. }
  3095. } else if ( op === '>=' && outputLength > 1 ) {
  3096. if ( builder.useComparisonMethod ) {
  3097. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3098. } else {
  3099. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3100. }
  3101. } else if ( op === '!' || op === '~' ) {
  3102. return builder.format( `(${op}${a})`, typeA, output );
  3103. } else if ( fnOpSnippet ) {
  3104. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3105. } else {
  3106. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3107. }
  3108. } else if ( typeA !== 'void' ) {
  3109. if ( fnOpSnippet ) {
  3110. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3111. } else {
  3112. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3113. }
  3114. }
  3115. }
  3116. serialize( data ) {
  3117. super.serialize( data );
  3118. data.op = this.op;
  3119. }
  3120. deserialize( data ) {
  3121. super.deserialize( data );
  3122. this.op = data.op;
  3123. }
  3124. }
  3125. /**
  3126. * Returns the addition of two or more value.
  3127. *
  3128. * @function
  3129. * @param {Node} aNode - The first input.
  3130. * @param {Node} bNode - The second input.
  3131. * @param {...Node} params - Additional input parameters.
  3132. * @returns {OperatorNode}
  3133. */
  3134. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3135. /**
  3136. * Returns the subtraction of two or more value.
  3137. *
  3138. * @function
  3139. * @param {Node} aNode - The first input.
  3140. * @param {Node} bNode - The second input.
  3141. * @param {...Node} params - Additional input parameters.
  3142. * @returns {OperatorNode}
  3143. */
  3144. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3145. /**
  3146. * Returns the multiplication of two or more value.
  3147. *
  3148. * @function
  3149. * @param {Node} aNode - The first input.
  3150. * @param {Node} bNode - The second input.
  3151. * @param {...Node} params - Additional input parameters.
  3152. * @returns {OperatorNode}
  3153. */
  3154. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3155. /**
  3156. * Returns the division of two or more value.
  3157. *
  3158. * @function
  3159. * @param {Node} aNode - The first input.
  3160. * @param {Node} bNode - The second input.
  3161. * @param {...Node} params - Additional input parameters.
  3162. * @returns {OperatorNode}
  3163. */
  3164. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3165. /**
  3166. * Computes the remainder of dividing the first node by the second, for integer values.
  3167. *
  3168. * @function
  3169. * @param {Node} aNode - The first input.
  3170. * @param {Node} bNode - The second input.
  3171. * @returns {OperatorNode}
  3172. */
  3173. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3174. /**
  3175. * Checks if two nodes are equal.
  3176. *
  3177. * @function
  3178. * @param {Node} aNode - The first input.
  3179. * @param {Node} bNode - The second input.
  3180. * @returns {OperatorNode}
  3181. */
  3182. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3183. /**
  3184. * Checks if two nodes are not equal.
  3185. *
  3186. * @function
  3187. * @param {Node} aNode - The first input.
  3188. * @param {Node} bNode - The second input.
  3189. * @returns {OperatorNode}
  3190. */
  3191. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3192. /**
  3193. * Checks if the first node is less than the second.
  3194. *
  3195. * @function
  3196. * @param {Node} aNode - The first input.
  3197. * @param {Node} bNode - The second input.
  3198. * @returns {OperatorNode}
  3199. */
  3200. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3201. /**
  3202. * Checks if the first node is greater than the second.
  3203. *
  3204. * @function
  3205. * @param {Node} aNode - The first input.
  3206. * @param {Node} bNode - The second input.
  3207. * @returns {OperatorNode}
  3208. */
  3209. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3210. /**
  3211. * Checks if the first node is less than or equal to the second.
  3212. *
  3213. * @function
  3214. * @param {Node} aNode - The first input.
  3215. * @param {Node} bNode - The second input.
  3216. * @returns {OperatorNode}
  3217. */
  3218. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3219. /**
  3220. * Checks if the first node is greater than or equal to the second.
  3221. *
  3222. * @function
  3223. * @param {Node} aNode - The first input.
  3224. * @param {Node} bNode - The second input.
  3225. * @returns {OperatorNode}
  3226. */
  3227. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3228. /**
  3229. * Performs logical AND on two nodes.
  3230. *
  3231. * @function
  3232. * @param {Node} aNode - The first input.
  3233. * @param {Node} bNode - The second input.
  3234. * @returns {OperatorNode}
  3235. */
  3236. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3237. /**
  3238. * Performs logical OR on two nodes.
  3239. *
  3240. * @function
  3241. * @param {Node} aNode - The first input.
  3242. * @param {Node} bNode - The second input.
  3243. * @returns {OperatorNode}
  3244. */
  3245. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3246. /**
  3247. * Performs logical NOT on a node.
  3248. *
  3249. * @function
  3250. * @param {Node} aNode - The first input.
  3251. * @param {Node} bNode - The second input.
  3252. * @returns {OperatorNode}
  3253. */
  3254. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3255. /**
  3256. * Performs logical XOR on two nodes.
  3257. *
  3258. * @function
  3259. * @param {Node} aNode - The first input.
  3260. * @param {Node} bNode - The second input.
  3261. * @returns {OperatorNode}
  3262. */
  3263. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3264. /**
  3265. * Performs bitwise AND on two nodes.
  3266. *
  3267. * @function
  3268. * @param {Node} aNode - The first input.
  3269. * @param {Node} bNode - The second input.
  3270. * @returns {OperatorNode}
  3271. */
  3272. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3273. /**
  3274. * Performs bitwise NOT on a node.
  3275. *
  3276. * @function
  3277. * @param {Node} aNode - The first input.
  3278. * @param {Node} bNode - The second input.
  3279. * @returns {OperatorNode}
  3280. */
  3281. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3282. /**
  3283. * Performs bitwise OR on two nodes.
  3284. *
  3285. * @function
  3286. * @param {Node} aNode - The first input.
  3287. * @param {Node} bNode - The second input.
  3288. * @returns {OperatorNode}
  3289. */
  3290. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3291. /**
  3292. * Performs bitwise XOR on two nodes.
  3293. *
  3294. * @function
  3295. * @param {Node} aNode - The first input.
  3296. * @param {Node} bNode - The second input.
  3297. * @returns {OperatorNode}
  3298. */
  3299. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3300. /**
  3301. * Shifts a node to the left.
  3302. *
  3303. * @function
  3304. * @param {Node} aNode - The node to shift.
  3305. * @param {Node} bNode - The value to shift.
  3306. * @returns {OperatorNode}
  3307. */
  3308. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3309. /**
  3310. * Shifts a node to the right.
  3311. *
  3312. * @function
  3313. * @param {Node} aNode - The node to shift.
  3314. * @param {Node} bNode - The value to shift.
  3315. * @returns {OperatorNode}
  3316. */
  3317. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3318. addMethodChaining( 'add', add );
  3319. addMethodChaining( 'sub', sub );
  3320. addMethodChaining( 'mul', mul );
  3321. addMethodChaining( 'div', div );
  3322. addMethodChaining( 'modInt', modInt );
  3323. addMethodChaining( 'equal', equal );
  3324. addMethodChaining( 'notEqual', notEqual );
  3325. addMethodChaining( 'lessThan', lessThan );
  3326. addMethodChaining( 'greaterThan', greaterThan );
  3327. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3328. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3329. addMethodChaining( 'and', and );
  3330. addMethodChaining( 'or', or );
  3331. addMethodChaining( 'not', not );
  3332. addMethodChaining( 'xor', xor );
  3333. addMethodChaining( 'bitAnd', bitAnd );
  3334. addMethodChaining( 'bitNot', bitNot );
  3335. addMethodChaining( 'bitOr', bitOr );
  3336. addMethodChaining( 'bitXor', bitXor );
  3337. addMethodChaining( 'shiftLeft', shiftLeft );
  3338. addMethodChaining( 'shiftRight', shiftRight );
  3339. const remainder = ( ...params ) => { // @deprecated, r168
  3340. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3341. return modInt( ...params );
  3342. };
  3343. addMethodChaining( 'remainder', remainder );
  3344. /** @module MathNode **/
  3345. /**
  3346. * This node represents a variety of mathematical methods available in shaders.
  3347. * They are divided into three categories:
  3348. *
  3349. * - Methods with one input like `sin`, `cos` or `normalize`.
  3350. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3351. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3352. *
  3353. * @augments TempNode
  3354. */
  3355. class MathNode extends TempNode {
  3356. static get type() {
  3357. return 'MathNode';
  3358. }
  3359. /**
  3360. * Constructs a new math node.
  3361. *
  3362. * @param {String} method - The method name.
  3363. * @param {Node} aNode - The first input.
  3364. * @param {Node?} [bNode=null] - The second input.
  3365. * @param {Node?} [cNode=null] - The third input.
  3366. */
  3367. constructor( method, aNode, bNode = null, cNode = null ) {
  3368. super();
  3369. /**
  3370. * The method name.
  3371. *
  3372. * @type {String}
  3373. */
  3374. this.method = method;
  3375. /**
  3376. * The first input.
  3377. *
  3378. * @type {Node}
  3379. */
  3380. this.aNode = aNode;
  3381. /**
  3382. * The second input.
  3383. *
  3384. * @type {Node?}
  3385. * @default null
  3386. */
  3387. this.bNode = bNode;
  3388. /**
  3389. * The third input.
  3390. *
  3391. * @type {Node?}
  3392. * @default null
  3393. */
  3394. this.cNode = cNode;
  3395. }
  3396. /**
  3397. * The input type is inferred from the node types of the input nodes.
  3398. *
  3399. * @param {NodeBuilder} builder - The current node builder.
  3400. * @return {String} The input type.
  3401. */
  3402. getInputType( builder ) {
  3403. const aType = this.aNode.getNodeType( builder );
  3404. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3405. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3406. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3407. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3408. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3409. if ( aLen > bLen && aLen > cLen ) {
  3410. return aType;
  3411. } else if ( bLen > cLen ) {
  3412. return bType;
  3413. } else if ( cLen > aLen ) {
  3414. return cType;
  3415. }
  3416. return aType;
  3417. }
  3418. /**
  3419. * The selected method as well as the input type determine the node type of this node.
  3420. *
  3421. * @param {NodeBuilder} builder - The current node builder.
  3422. * @return {String} The node type.
  3423. */
  3424. getNodeType( builder ) {
  3425. const method = this.method;
  3426. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3427. return 'float';
  3428. } else if ( method === MathNode.CROSS ) {
  3429. return 'vec3';
  3430. } else if ( method === MathNode.ALL ) {
  3431. return 'bool';
  3432. } else if ( method === MathNode.EQUALS ) {
  3433. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3434. } else if ( method === MathNode.MOD ) {
  3435. return this.aNode.getNodeType( builder );
  3436. } else {
  3437. return this.getInputType( builder );
  3438. }
  3439. }
  3440. generate( builder, output ) {
  3441. let method = this.method;
  3442. const type = this.getNodeType( builder );
  3443. const inputType = this.getInputType( builder );
  3444. const a = this.aNode;
  3445. const b = this.bNode;
  3446. const c = this.cNode;
  3447. const coordinateSystem = builder.renderer.coordinateSystem;
  3448. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3449. // dir can be either a direction vector or a normal vector
  3450. // upper-left 3x3 of matrix is assumed to be orthogonal
  3451. let tA = a;
  3452. let tB = b;
  3453. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3454. tB = vec4( vec3( tB ), 0.0 );
  3455. } else {
  3456. tA = vec4( vec3( tA ), 0.0 );
  3457. }
  3458. const mulNode = mul( tA, tB ).xyz;
  3459. return normalize( mulNode ).build( builder, output );
  3460. } else if ( method === MathNode.NEGATE ) {
  3461. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3462. } else if ( method === MathNode.ONE_MINUS ) {
  3463. return sub( 1.0, a ).build( builder, output );
  3464. } else if ( method === MathNode.RECIPROCAL ) {
  3465. return div( 1.0, a ).build( builder, output );
  3466. } else if ( method === MathNode.DIFFERENCE ) {
  3467. return abs( sub( a, b ) ).build( builder, output );
  3468. } else {
  3469. const params = [];
  3470. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3471. params.push(
  3472. a.build( builder, type ),
  3473. b.build( builder, type )
  3474. );
  3475. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3476. params.push(
  3477. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3478. b.build( builder, inputType )
  3479. );
  3480. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3481. params.push(
  3482. a.build( builder, inputType ),
  3483. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3484. );
  3485. } else if ( method === MathNode.REFRACT ) {
  3486. params.push(
  3487. a.build( builder, inputType ),
  3488. b.build( builder, inputType ),
  3489. c.build( builder, 'float' )
  3490. );
  3491. } else if ( method === MathNode.MIX ) {
  3492. params.push(
  3493. a.build( builder, inputType ),
  3494. b.build( builder, inputType ),
  3495. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3496. );
  3497. } else {
  3498. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3499. method = 'atan2';
  3500. }
  3501. params.push( a.build( builder, inputType ) );
  3502. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3503. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3504. }
  3505. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3506. }
  3507. }
  3508. serialize( data ) {
  3509. super.serialize( data );
  3510. data.method = this.method;
  3511. }
  3512. deserialize( data ) {
  3513. super.deserialize( data );
  3514. this.method = data.method;
  3515. }
  3516. }
  3517. // 1 input
  3518. MathNode.ALL = 'all';
  3519. MathNode.ANY = 'any';
  3520. MathNode.RADIANS = 'radians';
  3521. MathNode.DEGREES = 'degrees';
  3522. MathNode.EXP = 'exp';
  3523. MathNode.EXP2 = 'exp2';
  3524. MathNode.LOG = 'log';
  3525. MathNode.LOG2 = 'log2';
  3526. MathNode.SQRT = 'sqrt';
  3527. MathNode.INVERSE_SQRT = 'inversesqrt';
  3528. MathNode.FLOOR = 'floor';
  3529. MathNode.CEIL = 'ceil';
  3530. MathNode.NORMALIZE = 'normalize';
  3531. MathNode.FRACT = 'fract';
  3532. MathNode.SIN = 'sin';
  3533. MathNode.COS = 'cos';
  3534. MathNode.TAN = 'tan';
  3535. MathNode.ASIN = 'asin';
  3536. MathNode.ACOS = 'acos';
  3537. MathNode.ATAN = 'atan';
  3538. MathNode.ABS = 'abs';
  3539. MathNode.SIGN = 'sign';
  3540. MathNode.LENGTH = 'length';
  3541. MathNode.NEGATE = 'negate';
  3542. MathNode.ONE_MINUS = 'oneMinus';
  3543. MathNode.DFDX = 'dFdx';
  3544. MathNode.DFDY = 'dFdy';
  3545. MathNode.ROUND = 'round';
  3546. MathNode.RECIPROCAL = 'reciprocal';
  3547. MathNode.TRUNC = 'trunc';
  3548. MathNode.FWIDTH = 'fwidth';
  3549. MathNode.TRANSPOSE = 'transpose';
  3550. // 2 inputs
  3551. MathNode.BITCAST = 'bitcast';
  3552. MathNode.EQUALS = 'equals';
  3553. MathNode.MIN = 'min';
  3554. MathNode.MAX = 'max';
  3555. MathNode.MOD = 'mod';
  3556. MathNode.STEP = 'step';
  3557. MathNode.REFLECT = 'reflect';
  3558. MathNode.DISTANCE = 'distance';
  3559. MathNode.DIFFERENCE = 'difference';
  3560. MathNode.DOT = 'dot';
  3561. MathNode.CROSS = 'cross';
  3562. MathNode.POW = 'pow';
  3563. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3564. // 3 inputs
  3565. MathNode.MIX = 'mix';
  3566. MathNode.CLAMP = 'clamp';
  3567. MathNode.REFRACT = 'refract';
  3568. MathNode.SMOOTHSTEP = 'smoothstep';
  3569. MathNode.FACEFORWARD = 'faceforward';
  3570. // 1 inputs
  3571. /**
  3572. * A small value used to handle floating-point precision errors.
  3573. *
  3574. * @type {Node<float>}
  3575. */
  3576. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3577. /**
  3578. * Represents infinity.
  3579. *
  3580. * @type {Node<float>}
  3581. */
  3582. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3583. /**
  3584. * Represents PI.
  3585. *
  3586. * @type {Node<float>}
  3587. */
  3588. const PI = /*@__PURE__*/ float( Math.PI );
  3589. /**
  3590. * Represents PI * 2.
  3591. *
  3592. * @type {Node<float>}
  3593. */
  3594. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3595. /**
  3596. * Returns `true` if all components of `x` are `true`.
  3597. *
  3598. * @function
  3599. * @param {Node | Number} x - The parameter.
  3600. * @returns {Node<bool>}
  3601. */
  3602. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3603. /**
  3604. * Returns `true` if any components of `x` are `true`.
  3605. *
  3606. * @function
  3607. * @param {Node | Number} x - The parameter.
  3608. * @returns {Node<bool>}
  3609. */
  3610. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3611. /**
  3612. * Converts a quantity in degrees to radians.
  3613. *
  3614. * @function
  3615. * @param {Node | Number} x - The input in degrees.
  3616. * @returns {Node}
  3617. */
  3618. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3619. /**
  3620. * Convert a quantity in radians to degrees.
  3621. *
  3622. * @function
  3623. * @param {Node | Number} x - The input in radians.
  3624. * @returns {Node}
  3625. */
  3626. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3627. /**
  3628. * Returns the natural exponentiation of the parameter.
  3629. *
  3630. * @function
  3631. * @param {Node | Number} x - The parameter.
  3632. * @returns {Node}
  3633. */
  3634. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3635. /**
  3636. * Returns 2 raised to the power of the parameter.
  3637. *
  3638. * @function
  3639. * @param {Node | Number} x - The parameter.
  3640. * @returns {Node}
  3641. */
  3642. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3643. /**
  3644. * Returns the natural logarithm of the parameter.
  3645. *
  3646. * @function
  3647. * @param {Node | Number} x - The parameter.
  3648. * @returns {Node}
  3649. */
  3650. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3651. /**
  3652. * Returns the base 2 logarithm of the parameter.
  3653. *
  3654. * @function
  3655. * @param {Node | Number} x - The parameter.
  3656. * @returns {Node}
  3657. */
  3658. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3659. /**
  3660. * Returns the square root of the parameter.
  3661. *
  3662. * @function
  3663. * @param {Node | Number} x - The parameter.
  3664. * @returns {Node}
  3665. */
  3666. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3667. /**
  3668. * Returns the inverse of the square root of the parameter.
  3669. *
  3670. * @function
  3671. * @param {Node | Number} x - The parameter.
  3672. * @returns {Node}
  3673. */
  3674. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3675. /**
  3676. * Finds the nearest integer less than or equal to the parameter.
  3677. *
  3678. * @function
  3679. * @param {Node | Number} x - The parameter.
  3680. * @returns {Node}
  3681. */
  3682. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3683. /**
  3684. * Finds the nearest integer that is greater than or equal to the parameter.
  3685. *
  3686. * @function
  3687. * @param {Node | Number} x - The parameter.
  3688. * @returns {Node}
  3689. */
  3690. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3691. /**
  3692. * Calculates the unit vector in the same direction as the original vector.
  3693. *
  3694. * @function
  3695. * @param {Node} x - The input vector.
  3696. * @returns {Node}
  3697. */
  3698. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  3699. /**
  3700. * Computes the fractional part of the parameter.
  3701. *
  3702. * @function
  3703. * @param {Node | Number} x - The parameter.
  3704. * @returns {Node}
  3705. */
  3706. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  3707. /**
  3708. * Returns the sine of the parameter.
  3709. *
  3710. * @function
  3711. * @param {Node | Number} x - The parameter.
  3712. * @returns {Node}
  3713. */
  3714. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  3715. /**
  3716. * Returns the cosine of the parameter.
  3717. *
  3718. * @function
  3719. * @param {Node | Number} x - The parameter.
  3720. * @returns {Node}
  3721. */
  3722. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  3723. /**
  3724. * Returns the tangent of the parameter.
  3725. *
  3726. * @function
  3727. * @param {Node | Number} x - The parameter.
  3728. * @returns {Node}
  3729. */
  3730. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  3731. /**
  3732. * Returns the arcsine of the parameter.
  3733. *
  3734. * @function
  3735. * @param {Node | Number} x - The parameter.
  3736. * @returns {Node}
  3737. */
  3738. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  3739. /**
  3740. * Returns the arccosine of the parameter.
  3741. *
  3742. * @function
  3743. * @param {Node | Number} x - The parameter.
  3744. * @returns {Node}
  3745. */
  3746. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  3747. /**
  3748. * Returns the arc-tangent of the parameter.
  3749. *
  3750. * @function
  3751. * @param {Node | Number} x - The parameter.
  3752. * @returns {Node}
  3753. */
  3754. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  3755. /**
  3756. * Returns the absolute value of the parameter.
  3757. *
  3758. * @function
  3759. * @param {Node | Number} x - The parameter.
  3760. * @returns {Node}
  3761. */
  3762. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  3763. /**
  3764. * Extracts the sign of the parameter.
  3765. *
  3766. * @function
  3767. * @param {Node | Number} x - The parameter.
  3768. * @returns {Node}
  3769. */
  3770. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  3771. /**
  3772. * Calculates the length of a vector.
  3773. *
  3774. * @function
  3775. * @param {Node} x - The parameter.
  3776. * @returns {Node<float>}
  3777. */
  3778. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  3779. /**
  3780. * Negates the value of the parameter (-x).
  3781. *
  3782. * @function
  3783. * @param {Node | Number} x - The parameter.
  3784. * @returns {Node}
  3785. */
  3786. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  3787. /**
  3788. * Return `1` minus the parameter.
  3789. *
  3790. * @function
  3791. * @param {Node | Number} x - The parameter.
  3792. * @returns {Node}
  3793. */
  3794. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  3795. /**
  3796. * Returns the partial derivative of the parameter with respect to x.
  3797. *
  3798. * @function
  3799. * @param {Node | Number} x - The parameter.
  3800. * @returns {Node}
  3801. */
  3802. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  3803. /**
  3804. * Returns the partial derivative of the parameter with respect to y.
  3805. *
  3806. * @function
  3807. * @param {Node | Number} x - The parameter.
  3808. * @returns {Node}
  3809. */
  3810. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  3811. /**
  3812. * Rounds the parameter to the nearest integer.
  3813. *
  3814. * @function
  3815. * @param {Node | Number} x - The parameter.
  3816. * @returns {Node}
  3817. */
  3818. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  3819. /**
  3820. * Returns the reciprocal of the parameter `(1/x)`.
  3821. *
  3822. * @function
  3823. * @param {Node | Number} x - The parameter.
  3824. * @returns {Node}
  3825. */
  3826. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  3827. /**
  3828. * Truncates the parameter, removing the fractional part.
  3829. *
  3830. * @function
  3831. * @param {Node | Number} x - The parameter.
  3832. * @returns {Node}
  3833. */
  3834. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  3835. /**
  3836. * Returns the sum of the absolute derivatives in x and y.
  3837. *
  3838. * @function
  3839. * @param {Node | Number} x - The parameter.
  3840. * @returns {Node}
  3841. */
  3842. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  3843. /**
  3844. * Returns the transpose of a matrix.
  3845. *
  3846. * @function
  3847. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  3848. * @returns {Node}
  3849. */
  3850. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  3851. // 2 inputs
  3852. /**
  3853. * Reinterpret the bit representation of a value in one type as a value in another type.
  3854. *
  3855. * @function
  3856. * @param {Node | Number} x - The parameter.
  3857. * @param {String} y - The new type.
  3858. * @returns {Node}
  3859. */
  3860. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  3861. /**
  3862. * Returns `true` if `x` equals `y`.
  3863. *
  3864. * @function
  3865. * @param {Node | Number} x - The first parameter.
  3866. * @param {Node | Number} y - The second parameter.
  3867. * @returns {Node<bool>}
  3868. */
  3869. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  3870. /**
  3871. * Returns the lesser of two values.
  3872. *
  3873. * @function
  3874. * @param {Node | Number} x - The y parameter.
  3875. * @param {Node | Number} y - The x parameter.
  3876. * @returns {Node}
  3877. */
  3878. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  3879. /**
  3880. * Returns the greater of two values.
  3881. *
  3882. * @function
  3883. * @param {Node | Number} x - The y parameter.
  3884. * @param {Node | Number} y - The x parameter.
  3885. * @returns {Node}
  3886. */
  3887. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  3888. /**
  3889. * Computes the remainder of dividing the first node by the second one.
  3890. *
  3891. * @function
  3892. * @param {Node | Number} x - The y parameter.
  3893. * @param {Node | Number} y - The x parameter.
  3894. * @returns {Node}
  3895. */
  3896. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  3897. /**
  3898. * Generate a step function by comparing two values.
  3899. *
  3900. * @function
  3901. * @param {Node | Number} x - The y parameter.
  3902. * @param {Node | Number} y - The x parameter.
  3903. * @returns {Node}
  3904. */
  3905. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  3906. /**
  3907. * Calculates the reflection direction for an incident vector.
  3908. *
  3909. * @function
  3910. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  3911. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  3912. * @returns {Node<vec2|vec3|vec4>}
  3913. */
  3914. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  3915. /**
  3916. * Calculates the distance between two points.
  3917. *
  3918. * @function
  3919. * @param {Node<vec2|vec3|vec4>} x - The first point.
  3920. * @param {Node<vec2|vec3|vec4>} y - The second point.
  3921. * @returns {Node<float>}
  3922. */
  3923. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  3924. /**
  3925. * Calculates the absolute difference between two values.
  3926. *
  3927. * @function
  3928. * @param {Node | Number} x - The first parameter.
  3929. * @param {Node | Number} y - The second parameter.
  3930. * @returns {Node}
  3931. */
  3932. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  3933. /**
  3934. * Calculates the dot product of two vectors.
  3935. *
  3936. * @function
  3937. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  3938. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  3939. * @returns {Node<float>}
  3940. */
  3941. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  3942. /**
  3943. * Calculates the cross product of two vectors.
  3944. *
  3945. * @function
  3946. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  3947. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  3948. * @returns {Node<vec2|vec3|vec4>}
  3949. */
  3950. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  3951. /**
  3952. * Return the value of the first parameter raised to the power of the second one.
  3953. *
  3954. * @function
  3955. * @param {Node | Number} x - The first parameter.
  3956. * @param {Node | Number} y - The second parameter.
  3957. * @returns {Node}
  3958. */
  3959. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  3960. /**
  3961. * Returns the square of the parameter.
  3962. *
  3963. * @function
  3964. * @param {Node | Number} x - The first parameter.
  3965. * @returns {Node}
  3966. */
  3967. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  3968. /**
  3969. * Returns the cube of the parameter.
  3970. *
  3971. * @function
  3972. * @param {Node | Number} x - The first parameter.
  3973. * @returns {Node}
  3974. */
  3975. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  3976. /**
  3977. * Returns the fourth power of the parameter.
  3978. *
  3979. * @function
  3980. * @param {Node | Number} x - The first parameter.
  3981. * @returns {Node}
  3982. */
  3983. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  3984. /**
  3985. * Transforms the direction of a vector by a matrix and then normalizes the result.
  3986. *
  3987. * @function
  3988. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  3989. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  3990. * @returns {Node}
  3991. */
  3992. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  3993. /**
  3994. * Returns the cube root of a number.
  3995. *
  3996. * @function
  3997. * @param {Node | Number} a - The first parameter.
  3998. * @returns {Node}
  3999. */
  4000. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4001. /**
  4002. * Calculate the squared length of a vector.
  4003. *
  4004. * @function
  4005. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4006. * @returns {Node<float>}
  4007. */
  4008. const lengthSq = ( a ) => dot( a, a );
  4009. /**
  4010. * Linearly interpolates between two values.
  4011. *
  4012. * @function
  4013. * @param {Node | Number} a - The first parameter.
  4014. * @param {Node | Number} b - The second parameter.
  4015. * @param {Node | Number} t - The interpolation value.
  4016. * @returns {Node}
  4017. */
  4018. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  4019. /**
  4020. * Constrains a value to lie between two further values.
  4021. *
  4022. * @function
  4023. * @param {Node | Number} value - The value to constrain.
  4024. * @param {Node | Number} [low=0] - The lower bound.
  4025. * @param {Node | Number} [high=1] - The upper bound.
  4026. * @returns {Node}
  4027. */
  4028. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4029. /**
  4030. * Constrains a value between `0` and `1`.
  4031. *
  4032. * @function
  4033. * @param {Node | Number} value - The value to constrain.
  4034. * @returns {Node}
  4035. */
  4036. const saturate = ( value ) => clamp( value );
  4037. /**
  4038. * Calculates the refraction direction for an incident vector.
  4039. *
  4040. * @function
  4041. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4042. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4043. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4044. * @returns {Node<vec2|vec3|vec4>}
  4045. */
  4046. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4047. /**
  4048. * Performs a Hermite interpolation between two values.
  4049. *
  4050. * @function
  4051. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4052. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4053. * @param {Node | Number} x - The source value for interpolation.
  4054. * @returns {Node}
  4055. */
  4056. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4057. /**
  4058. * Returns a vector pointing in the same direction as another.
  4059. *
  4060. * @function
  4061. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4062. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4063. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4064. * @returns {Node<vec2|vec3|vec4>}
  4065. */
  4066. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4067. /**
  4068. * Returns a random value for the given uv.
  4069. *
  4070. * @function
  4071. * @param {Node<vec2>} uv - The uv node.
  4072. * @returns {Node<float>}
  4073. */
  4074. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4075. const a = 12.9898, b = 78.233, c = 43758.5453;
  4076. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4077. return fract( sin( sn ).mul( c ) );
  4078. } );
  4079. /**
  4080. * Alias for `mix()` with a different parameter order.
  4081. *
  4082. * @function
  4083. * @param {Node | Number} t - The interpolation value.
  4084. * @param {Node | Number} e1 - The first parameter.
  4085. * @param {Node | Number} e2 - The second parameter.
  4086. * @returns {Node}
  4087. */
  4088. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4089. /**
  4090. * Alias for `smoothstep()` with a different parameter order.
  4091. *
  4092. * @function
  4093. * @param {Node | Number} x - The source value for interpolation.
  4094. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4095. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4096. * @returns {Node}
  4097. */
  4098. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4099. /**
  4100. * Returns the arc-tangent of the quotient of its parameters.
  4101. *
  4102. * @function
  4103. * @param {Node | Number} y - The y parameter.
  4104. * @param {Node | Number} x - The x parameter.
  4105. * @returns {Node}
  4106. */
  4107. const atan2 = ( y, x ) => { // @deprecated, r172
  4108. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4109. return atan( y, x );
  4110. };
  4111. // GLSL alias function
  4112. const faceforward = faceForward;
  4113. const inversesqrt = inverseSqrt;
  4114. // Method chaining
  4115. addMethodChaining( 'all', all );
  4116. addMethodChaining( 'any', any );
  4117. addMethodChaining( 'equals', equals );
  4118. addMethodChaining( 'radians', radians );
  4119. addMethodChaining( 'degrees', degrees );
  4120. addMethodChaining( 'exp', exp );
  4121. addMethodChaining( 'exp2', exp2 );
  4122. addMethodChaining( 'log', log );
  4123. addMethodChaining( 'log2', log2 );
  4124. addMethodChaining( 'sqrt', sqrt );
  4125. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4126. addMethodChaining( 'floor', floor );
  4127. addMethodChaining( 'ceil', ceil );
  4128. addMethodChaining( 'normalize', normalize );
  4129. addMethodChaining( 'fract', fract );
  4130. addMethodChaining( 'sin', sin );
  4131. addMethodChaining( 'cos', cos );
  4132. addMethodChaining( 'tan', tan );
  4133. addMethodChaining( 'asin', asin );
  4134. addMethodChaining( 'acos', acos );
  4135. addMethodChaining( 'atan', atan );
  4136. addMethodChaining( 'abs', abs );
  4137. addMethodChaining( 'sign', sign );
  4138. addMethodChaining( 'length', length );
  4139. addMethodChaining( 'lengthSq', lengthSq );
  4140. addMethodChaining( 'negate', negate );
  4141. addMethodChaining( 'oneMinus', oneMinus );
  4142. addMethodChaining( 'dFdx', dFdx );
  4143. addMethodChaining( 'dFdy', dFdy );
  4144. addMethodChaining( 'round', round );
  4145. addMethodChaining( 'reciprocal', reciprocal );
  4146. addMethodChaining( 'trunc', trunc );
  4147. addMethodChaining( 'fwidth', fwidth );
  4148. addMethodChaining( 'atan2', atan2 );
  4149. addMethodChaining( 'min', min$1 );
  4150. addMethodChaining( 'max', max$1 );
  4151. addMethodChaining( 'mod', mod );
  4152. addMethodChaining( 'step', step );
  4153. addMethodChaining( 'reflect', reflect );
  4154. addMethodChaining( 'distance', distance );
  4155. addMethodChaining( 'dot', dot );
  4156. addMethodChaining( 'cross', cross );
  4157. addMethodChaining( 'pow', pow );
  4158. addMethodChaining( 'pow2', pow2 );
  4159. addMethodChaining( 'pow3', pow3 );
  4160. addMethodChaining( 'pow4', pow4 );
  4161. addMethodChaining( 'transformDirection', transformDirection );
  4162. addMethodChaining( 'mix', mixElement );
  4163. addMethodChaining( 'clamp', clamp );
  4164. addMethodChaining( 'refract', refract );
  4165. addMethodChaining( 'smoothstep', smoothstepElement );
  4166. addMethodChaining( 'faceForward', faceForward );
  4167. addMethodChaining( 'difference', difference );
  4168. addMethodChaining( 'saturate', saturate );
  4169. addMethodChaining( 'cbrt', cbrt );
  4170. addMethodChaining( 'transpose', transpose );
  4171. addMethodChaining( 'rand', rand );
  4172. /** @module ConditionalNode **/
  4173. /**
  4174. * Represents a logical `if/else` statement. Can be used as an alternative
  4175. * to the `If()`/`Else()` syntax.
  4176. *
  4177. * The corresponding TSL `select()` looks like so:
  4178. * ```js
  4179. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4180. * ```
  4181. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4182. * determine the outcome of the entire statement.
  4183. *
  4184. * @augments Node
  4185. */
  4186. class ConditionalNode extends Node {
  4187. static get type() {
  4188. return 'ConditionalNode';
  4189. }
  4190. /**
  4191. * Constructs a new conditional node.
  4192. *
  4193. * @param {Node} condNode - The node that defines the condition.
  4194. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4195. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4196. */
  4197. constructor( condNode, ifNode, elseNode = null ) {
  4198. super();
  4199. /**
  4200. * The node that defines the condition.
  4201. *
  4202. * @type {Node}
  4203. */
  4204. this.condNode = condNode;
  4205. /**
  4206. * The node that is evaluate when the condition ends up `true`.
  4207. *
  4208. * @type {Node}
  4209. */
  4210. this.ifNode = ifNode;
  4211. /**
  4212. * The node that is evaluate when the condition ends up `false`.
  4213. *
  4214. * @type {Node?}
  4215. * @default null
  4216. */
  4217. this.elseNode = elseNode;
  4218. }
  4219. /**
  4220. * This method is overwritten since the node type is inferred from the if/else
  4221. * nodes.
  4222. *
  4223. * @param {NodeBuilder} builder - The current node builder.
  4224. * @return {String} The node type.
  4225. */
  4226. getNodeType( builder ) {
  4227. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4228. if ( ifNode === undefined ) {
  4229. // fallback setup
  4230. this.setup( builder );
  4231. return this.getNodeType( builder );
  4232. }
  4233. const ifType = ifNode.getNodeType( builder );
  4234. if ( elseNode !== null ) {
  4235. const elseType = elseNode.getNodeType( builder );
  4236. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4237. return elseType;
  4238. }
  4239. }
  4240. return ifType;
  4241. }
  4242. setup( builder ) {
  4243. const condNode = this.condNode.cache();
  4244. const ifNode = this.ifNode.cache();
  4245. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4246. //
  4247. const currentNodeBlock = builder.context.nodeBlock;
  4248. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4249. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4250. //
  4251. const properties = builder.getNodeProperties( this );
  4252. properties.condNode = condNode;
  4253. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4254. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4255. }
  4256. generate( builder, output ) {
  4257. const type = this.getNodeType( builder );
  4258. const nodeData = builder.getDataFromNode( this );
  4259. if ( nodeData.nodeProperty !== undefined ) {
  4260. return nodeData.nodeProperty;
  4261. }
  4262. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4263. const needsOutput = output !== 'void';
  4264. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4265. nodeData.nodeProperty = nodeProperty;
  4266. const nodeSnippet = condNode.build( builder, 'bool' );
  4267. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4268. let ifSnippet = ifNode.build( builder, type );
  4269. if ( ifSnippet ) {
  4270. if ( needsOutput ) {
  4271. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4272. } else {
  4273. ifSnippet = 'return ' + ifSnippet + ';';
  4274. }
  4275. }
  4276. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4277. if ( elseNode !== null ) {
  4278. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4279. let elseSnippet = elseNode.build( builder, type );
  4280. if ( elseSnippet ) {
  4281. if ( needsOutput ) {
  4282. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4283. } else {
  4284. elseSnippet = 'return ' + elseSnippet + ';';
  4285. }
  4286. }
  4287. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4288. } else {
  4289. builder.addFlowCode( '\n\n' );
  4290. }
  4291. return builder.format( nodeProperty, type, output );
  4292. }
  4293. }
  4294. /**
  4295. * TSL function for creating a conditional node.
  4296. *
  4297. * @function
  4298. * @param {Node} condNode - The node that defines the condition.
  4299. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4300. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4301. * @returns {ConditionalNode}
  4302. */
  4303. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4304. addMethodChaining( 'select', select );
  4305. //
  4306. const cond = ( ...params ) => { // @deprecated, r168
  4307. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4308. return select( ...params );
  4309. };
  4310. addMethodChaining( 'cond', cond );
  4311. /** @module ContextNode **/
  4312. /**
  4313. * This node can be used as a context management component for another node.
  4314. * {@link NodeBuilder} performs its node building process in a specific context and
  4315. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4316. *
  4317. * ```js
  4318. *node.context( { getUV: () => customCoord } );
  4319. *```
  4320. * @augments Node
  4321. */
  4322. class ContextNode extends Node {
  4323. static get type() {
  4324. return 'ContextNode';
  4325. }
  4326. /**
  4327. * Constructs a new context node.
  4328. *
  4329. * @param {Node} node - The node whose context should be modified.
  4330. * @param {Object} [value={}] - The modified context data.
  4331. */
  4332. constructor( node, value = {} ) {
  4333. super();
  4334. /**
  4335. * This flag can be used for type testing.
  4336. *
  4337. * @type {Boolean}
  4338. * @readonly
  4339. * @default true
  4340. */
  4341. this.isContextNode = true;
  4342. /**
  4343. * The node whose context should be modified.
  4344. *
  4345. * @type {Node}
  4346. */
  4347. this.node = node;
  4348. /**
  4349. * The modified context data.
  4350. *
  4351. * @type {Object}
  4352. * @default {}
  4353. */
  4354. this.value = value;
  4355. }
  4356. /**
  4357. * This method is overwritten to ensure it returns the reference to {@link module:ContextNode~ContextNode#node}.
  4358. *
  4359. * @return {Node} A reference to {@link module:ContextNode~ContextNode#node}.
  4360. */
  4361. getScope() {
  4362. return this.node.getScope();
  4363. }
  4364. /**
  4365. * This method is overwritten to ensure it returns the type of {@link module:ContextNode~ContextNode#node}.
  4366. *
  4367. * @param {NodeBuilder} builder - The current node builder.
  4368. * @return {String} The node type.
  4369. */
  4370. getNodeType( builder ) {
  4371. return this.node.getNodeType( builder );
  4372. }
  4373. analyze( builder ) {
  4374. this.node.build( builder );
  4375. }
  4376. setup( builder ) {
  4377. const previousContext = builder.getContext();
  4378. builder.setContext( { ...builder.context, ...this.value } );
  4379. const node = this.node.build( builder );
  4380. builder.setContext( previousContext );
  4381. return node;
  4382. }
  4383. generate( builder, output ) {
  4384. const previousContext = builder.getContext();
  4385. builder.setContext( { ...builder.context, ...this.value } );
  4386. const snippet = this.node.build( builder, output );
  4387. builder.setContext( previousContext );
  4388. return snippet;
  4389. }
  4390. }
  4391. /**
  4392. * TSL function for creating a context node.
  4393. *
  4394. * @function
  4395. * @param {Node} node - The node whose context should be modified.
  4396. * @param {Object} [value={}] - The modified context data.
  4397. * @returns {ContextNode}
  4398. */
  4399. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4400. /**
  4401. * TSL function for defining a label context value for a given node.
  4402. *
  4403. * @function
  4404. * @param {Node} node - The node whose context should be modified.
  4405. * @param {String} name - The name/label to set.
  4406. * @returns {ContextNode}
  4407. */
  4408. const label = ( node, name ) => context( node, { label: name } );
  4409. addMethodChaining( 'context', context );
  4410. addMethodChaining( 'label', label );
  4411. /** @module VarNode **/
  4412. /**
  4413. * Class for representing shader variables as nodes. Variables are created from
  4414. * existing nodes like the following:
  4415. *
  4416. * ```js
  4417. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4418. * ```
  4419. *
  4420. * @augments Node
  4421. */
  4422. class VarNode extends Node {
  4423. static get type() {
  4424. return 'VarNode';
  4425. }
  4426. /**
  4427. * Constructs a new variable node.
  4428. *
  4429. * @param {Node} node - The node for which a variable should be created.
  4430. * @param {String?} name - The name of the variable in the shader.
  4431. */
  4432. constructor( node, name = null ) {
  4433. super();
  4434. /**
  4435. * The node for which a variable should be created.
  4436. *
  4437. * @type {Node}
  4438. */
  4439. this.node = node;
  4440. /**
  4441. * The name of the variable in the shader. If no name is defined,
  4442. * the node system auto-generates one.
  4443. *
  4444. * @type {String?}
  4445. * @default null
  4446. */
  4447. this.name = name;
  4448. /**
  4449. * `VarNode` sets this property to `true` by default.
  4450. *
  4451. * @type {Boolean}
  4452. * @default true
  4453. */
  4454. this.global = true;
  4455. /**
  4456. * This flag can be used for type testing.
  4457. *
  4458. * @type {Boolean}
  4459. * @readonly
  4460. * @default true
  4461. */
  4462. this.isVarNode = true;
  4463. }
  4464. getHash( builder ) {
  4465. return this.name || super.getHash( builder );
  4466. }
  4467. getNodeType( builder ) {
  4468. return this.node.getNodeType( builder );
  4469. }
  4470. generate( builder ) {
  4471. const { node, name } = this;
  4472. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  4473. const propertyName = builder.getPropertyName( nodeVar );
  4474. const snippet = node.build( builder, nodeVar.type );
  4475. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  4476. return propertyName;
  4477. }
  4478. }
  4479. /**
  4480. * TSL function for creating a var node.
  4481. *
  4482. * @function
  4483. * @param {Node} node - The node for which a variable should be created.
  4484. * @param {String?} name - The name of the variable in the shader.
  4485. * @returns {VarNode}
  4486. */
  4487. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4488. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  4489. // Deprecated
  4490. const temp = ( node ) => { // @deprecated, r170
  4491. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  4492. return createVar( node );
  4493. };
  4494. addMethodChaining( 'temp', temp );
  4495. /** @module VaryingNode **/
  4496. /**
  4497. * Class for representing shader varyings as nodes. Varyings are create from
  4498. * existing nodes like the following:
  4499. *
  4500. * ```js
  4501. * const positionLocal = positionGeometry.varying( 'vPositionLocal' );
  4502. * ```
  4503. *
  4504. * @augments Node
  4505. */
  4506. class VaryingNode extends Node {
  4507. static get type() {
  4508. return 'VaryingNode';
  4509. }
  4510. /**
  4511. * Constructs a new varying node.
  4512. *
  4513. * @param {Node} node - The node for which a varying should be created.
  4514. * @param {String?} name - The name of the varying in the shader.
  4515. */
  4516. constructor( node, name = null ) {
  4517. super();
  4518. /**
  4519. * The node for which a varying should be created.
  4520. *
  4521. * @type {Node}
  4522. */
  4523. this.node = node;
  4524. /**
  4525. * The name of the varying in the shader. If no name is defined,
  4526. * the node system auto-generates one.
  4527. *
  4528. * @type {String?}
  4529. * @default null
  4530. */
  4531. this.name = name;
  4532. /**
  4533. * This flag can be used for type testing.
  4534. *
  4535. * @type {Boolean}
  4536. * @readonly
  4537. * @default true
  4538. */
  4539. this.isVaryingNode = true;
  4540. }
  4541. /**
  4542. * The method is overwritten so it always returns `true`.
  4543. *
  4544. * @param {NodeBuilder} builder - The current node builder.
  4545. * @return {Boolean} Whether this node is global or not.
  4546. */
  4547. isGlobal( /*builder*/ ) {
  4548. return true;
  4549. }
  4550. getHash( builder ) {
  4551. return this.name || super.getHash( builder );
  4552. }
  4553. getNodeType( builder ) {
  4554. // VaryingNode is auto type
  4555. return this.node.getNodeType( builder );
  4556. }
  4557. /**
  4558. * This method performs the setup of a varying node with the current node builder.
  4559. *
  4560. * @param {NodeBuilder} builder - The current node builder.
  4561. * @return {NodeVarying} The node varying from the node builder.
  4562. */
  4563. setupVarying( builder ) {
  4564. const properties = builder.getNodeProperties( this );
  4565. let varying = properties.varying;
  4566. if ( varying === undefined ) {
  4567. const name = this.name;
  4568. const type = this.getNodeType( builder );
  4569. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  4570. properties.node = this.node;
  4571. }
  4572. // this property can be used to check if the varying can be optimized for a variable
  4573. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  4574. return varying;
  4575. }
  4576. setup( builder ) {
  4577. this.setupVarying( builder );
  4578. }
  4579. analyze( builder ) {
  4580. this.setupVarying( builder );
  4581. return this.node.analyze( builder );
  4582. }
  4583. generate( builder ) {
  4584. const properties = builder.getNodeProperties( this );
  4585. const varying = this.setupVarying( builder );
  4586. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  4587. if ( properties.propertyName === undefined || needsReassign ) {
  4588. const type = this.getNodeType( builder );
  4589. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  4590. // force node run in vertex stage
  4591. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  4592. properties.propertyName = propertyName;
  4593. if ( needsReassign ) {
  4594. // once reassign varying in fragment stage
  4595. properties.reassignPosition = false;
  4596. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  4597. properties.reassignPosition = true;
  4598. }
  4599. }
  4600. return builder.getPropertyName( varying );
  4601. }
  4602. }
  4603. /**
  4604. * TSL function for creating a varying node.
  4605. *
  4606. * @function
  4607. * @param {Node} node - The node for which a varying should be created.
  4608. * @param {String?} name - The name of the varying in the shader.
  4609. * @returns {VaryingNode}
  4610. */
  4611. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  4612. /**
  4613. * Computes a node in the vertex stage.
  4614. *
  4615. * @function
  4616. * @param {Node} node - The node which should be executed in the vertex stage.
  4617. * @returns {VaryingNode}
  4618. */
  4619. const vertexStage = ( node ) => varying( node );
  4620. addMethodChaining( 'varying', varying );
  4621. addMethodChaining( 'vertexStage', vertexStage );
  4622. /** @module ColorSpaceFunctions **/
  4623. /**
  4624. * Converts the given color value from sRGB to linear-sRGB color space.
  4625. *
  4626. * @method
  4627. * @param {Node<vec3>} color - The sRGB color.
  4628. * @return {Node<vec3>} The linear-sRGB color.
  4629. */
  4630. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4631. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  4632. const b = color.mul( 0.0773993808 );
  4633. const factor = color.lessThanEqual( 0.04045 );
  4634. const rgbResult = mix( a, b, factor );
  4635. return rgbResult;
  4636. } ).setLayout( {
  4637. name: 'sRGBTransferEOTF',
  4638. type: 'vec3',
  4639. inputs: [
  4640. { name: 'color', type: 'vec3' }
  4641. ]
  4642. } );
  4643. /**
  4644. * Converts the given color value from linear-sRGB to sRGB color space.
  4645. *
  4646. * @method
  4647. * @param {Node<vec3>} color - The linear-sRGB color.
  4648. * @return {Node<vec3>} The sRGB color.
  4649. */
  4650. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4651. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  4652. const b = color.mul( 12.92 );
  4653. const factor = color.lessThanEqual( 0.0031308 );
  4654. const rgbResult = mix( a, b, factor );
  4655. return rgbResult;
  4656. } ).setLayout( {
  4657. name: 'sRGBTransferOETF',
  4658. type: 'vec3',
  4659. inputs: [
  4660. { name: 'color', type: 'vec3' }
  4661. ]
  4662. } );
  4663. /** @module ColorSpaceNode **/
  4664. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  4665. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  4666. /**
  4667. * This node represents a color space conversion. Meaning it converts
  4668. * a color value from a source to a target color space.
  4669. *
  4670. * @augments TempNode
  4671. */
  4672. class ColorSpaceNode extends TempNode {
  4673. static get type() {
  4674. return 'ColorSpaceNode';
  4675. }
  4676. /**
  4677. * Constructs a new color space node.
  4678. *
  4679. * @param {Node} colorNode - Represents the color to convert.
  4680. * @param {String} source - The source color space.
  4681. * @param {String} target - The target color space.
  4682. */
  4683. constructor( colorNode, source, target ) {
  4684. super( 'vec4' );
  4685. /**
  4686. * Represents the color to convert.
  4687. *
  4688. * @type {Node}
  4689. */
  4690. this.colorNode = colorNode;
  4691. /**
  4692. * The source color space.
  4693. *
  4694. * @type {String}
  4695. */
  4696. this.source = source;
  4697. /**
  4698. * The target color space.
  4699. *
  4700. * @type {String}
  4701. */
  4702. this.target = target;
  4703. }
  4704. /**
  4705. * This method resolves the constants `WORKING_COLOR_SPACE` and
  4706. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  4707. * color management and renderer.
  4708. *
  4709. * @param {NodeBuilder} builder - The current node builder.
  4710. * @param {String} colorSpace - The color space to resolve.
  4711. * @return {String} The resolved color space.
  4712. */
  4713. resolveColorSpace( builder, colorSpace ) {
  4714. if ( colorSpace === WORKING_COLOR_SPACE ) {
  4715. return ColorManagement.workingColorSpace;
  4716. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  4717. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  4718. }
  4719. return colorSpace;
  4720. }
  4721. setup( builder ) {
  4722. const { colorNode } = this;
  4723. const source = this.resolveColorSpace( builder, this.source );
  4724. const target = this.resolveColorSpace( builder, this.target );
  4725. let outputNode = colorNode;
  4726. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  4727. return outputNode;
  4728. }
  4729. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  4730. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  4731. }
  4732. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  4733. outputNode = vec4(
  4734. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  4735. outputNode.a
  4736. );
  4737. }
  4738. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  4739. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  4740. }
  4741. return outputNode;
  4742. }
  4743. }
  4744. /**
  4745. * TSL function for converting a given color node to the current output color space.
  4746. *
  4747. * @function
  4748. * @param {Node} node - Represents the node to convert.
  4749. * @returns {ColorSpaceNode}
  4750. */
  4751. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  4752. /**
  4753. * TSL function for converting a given color node to the current working color space.
  4754. *
  4755. * @function
  4756. * @param {Node} node - Represents the node to convert.
  4757. * @returns {ColorSpaceNode}
  4758. */
  4759. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  4760. /**
  4761. * TSL function for converting a given color node from the current working color space to the given color space.
  4762. *
  4763. * @function
  4764. * @param {Node} node - Represents the node to convert.
  4765. * @param {String} colorSpace - The target color space.
  4766. * @returns {ColorSpaceNode}
  4767. */
  4768. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  4769. /**
  4770. * TSL function for converting a given color node from the given color space to the current working color space.
  4771. *
  4772. * @function
  4773. * @param {Node} node - Represents the node to convert.
  4774. * @param {String} colorSpace - The source color space.
  4775. * @returns {ColorSpaceNode}
  4776. */
  4777. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  4778. /**
  4779. * TSL function for converting a given color node from one color space to another one.
  4780. *
  4781. * @function
  4782. * @param {Node} node - Represents the node to convert.
  4783. * @param {String} sourceColorSpace - The source color space.
  4784. * @param {String} targetColorSpace - The target color space.
  4785. * @returns {ColorSpaceNode}
  4786. */
  4787. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  4788. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  4789. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  4790. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  4791. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  4792. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  4793. /** @module ReferenceBaseNode **/
  4794. /**
  4795. * This class is only relevant if the referenced property is array-like.
  4796. * In this case, `ReferenceElementNode` allows to refer to a specific
  4797. * element inside the data structure via an index.
  4798. *
  4799. * @augments ArrayElementNode
  4800. */
  4801. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  4802. static get type() {
  4803. return 'ReferenceElementNode';
  4804. }
  4805. /**
  4806. * Constructs a new reference element node.
  4807. *
  4808. * @param {Node?} referenceNode - The reference node.
  4809. * @param {Node} indexNode - The index node that defines the element access.
  4810. */
  4811. constructor( referenceNode, indexNode ) {
  4812. super( referenceNode, indexNode );
  4813. /**
  4814. * Similar to {@link module:ReferenceBaseNode~ReferenceBaseNode#reference}, an additional
  4815. * property references to the current node.
  4816. *
  4817. * @type {Node?}
  4818. * @default null
  4819. */
  4820. this.referenceNode = referenceNode;
  4821. /**
  4822. * This flag can be used for type testing.
  4823. *
  4824. * @type {Boolean}
  4825. * @readonly
  4826. * @default true
  4827. */
  4828. this.isReferenceElementNode = true;
  4829. }
  4830. /**
  4831. * This method is overwritten since the node type is inferred from
  4832. * the uniform type of the reference node.
  4833. *
  4834. * @param {NodeBuilder} builder - The current node builder.
  4835. * @return {String} The node type.
  4836. */
  4837. getNodeType() {
  4838. return this.referenceNode.uniformType;
  4839. }
  4840. generate( builder ) {
  4841. const snippet = super.generate( builder );
  4842. const arrayType = this.referenceNode.getNodeType();
  4843. const elementType = this.getNodeType();
  4844. return builder.format( snippet, arrayType, elementType );
  4845. }
  4846. };
  4847. /**
  4848. * Base class for nodes which establishes a reference to a property of another object.
  4849. * In this way, the value of the node is automatically linked to the value of
  4850. * referenced object. Reference nodes internally represent the linked value
  4851. * as a uniform.
  4852. *
  4853. * @augments Node
  4854. */
  4855. class ReferenceBaseNode extends Node {
  4856. static get type() {
  4857. return 'ReferenceBaseNode';
  4858. }
  4859. /**
  4860. * Constructs a new reference base node.
  4861. *
  4862. * @param {String} property - The name of the property the node refers to.
  4863. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  4864. * @param {Object?} [object=null] - The object the property belongs to.
  4865. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  4866. */
  4867. constructor( property, uniformType, object = null, count = null ) {
  4868. super();
  4869. /**
  4870. * The name of the property the node refers to.
  4871. *
  4872. * @type {String}
  4873. */
  4874. this.property = property;
  4875. /**
  4876. * The uniform type that should be used to represent the property value.
  4877. *
  4878. * @type {String}
  4879. */
  4880. this.uniformType = uniformType;
  4881. /**
  4882. * The object the property belongs to.
  4883. *
  4884. * @type {Object?}
  4885. * @default null
  4886. */
  4887. this.object = object;
  4888. /**
  4889. * When the linked property is an array, this parameter defines its length.
  4890. *
  4891. * @type {Number?}
  4892. * @default null
  4893. */
  4894. this.count = count;
  4895. /**
  4896. * The property name might have dots so nested properties can be referred.
  4897. * The hierarchy of the names is stored inside this array.
  4898. *
  4899. * @type {Array<String>}
  4900. */
  4901. this.properties = property.split( '.' );
  4902. /**
  4903. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  4904. * since the final reference might be updated from calling code.
  4905. *
  4906. * @type {Object?}
  4907. * @default null
  4908. */
  4909. this.reference = object;
  4910. /**
  4911. * The uniform node that holds the value of the reference node.
  4912. *
  4913. * @type {UniformNode}
  4914. * @default null
  4915. */
  4916. this.node = null;
  4917. /**
  4918. * The uniform group of the internal uniform.
  4919. *
  4920. * @type {UniformGroupNode}
  4921. * @default null
  4922. */
  4923. this.group = null;
  4924. /**
  4925. * Overwritten since reference nodes are updated per object.
  4926. *
  4927. * @type {String}
  4928. * @default 'object'
  4929. */
  4930. this.updateType = NodeUpdateType.OBJECT;
  4931. }
  4932. /**
  4933. * Sets the uniform group for this reference node.
  4934. *
  4935. * @param {UniformGroupNode} group - The uniform group to set.
  4936. * @return {ReferenceBaseNode} A reference to this node.
  4937. */
  4938. setGroup( group ) {
  4939. this.group = group;
  4940. return this;
  4941. }
  4942. /**
  4943. * When the referred property is array-like, this method can be used
  4944. * to access elements via an index node.
  4945. *
  4946. * @param {IndexNode} indexNode - indexNode.
  4947. * @return {ReferenceElementNode} A reference to an element.
  4948. */
  4949. element( indexNode ) {
  4950. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  4951. }
  4952. /**
  4953. * Sets the node type which automatically defines the internal
  4954. * uniform type.
  4955. *
  4956. * @param {String} uniformType - The type to set.
  4957. */
  4958. setNodeType( uniformType ) {
  4959. const node = uniform( null, uniformType ).getSelf();
  4960. if ( this.group !== null ) {
  4961. node.setGroup( this.group );
  4962. }
  4963. this.node = node;
  4964. }
  4965. /**
  4966. * This method is overwritten since the node type is inferred from
  4967. * the type of the reference node.
  4968. *
  4969. * @param {NodeBuilder} builder - The current node builder.
  4970. * @return {String} The node type.
  4971. */
  4972. getNodeType( builder ) {
  4973. if ( this.node === null ) {
  4974. this.updateReference( builder );
  4975. this.updateValue();
  4976. }
  4977. return this.node.getNodeType( builder );
  4978. }
  4979. /**
  4980. * Returns the property value from the given referred object.
  4981. *
  4982. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  4983. * @return {Any} The value.
  4984. */
  4985. getValueFromReference( object = this.reference ) {
  4986. const { properties } = this;
  4987. let value = object[ properties[ 0 ] ];
  4988. for ( let i = 1; i < properties.length; i ++ ) {
  4989. value = value[ properties[ i ] ];
  4990. }
  4991. return value;
  4992. }
  4993. /**
  4994. * Allows to update the reference based on the given state. The state is only
  4995. * evaluated {@link module:ReferenceBaseNode~ReferenceBaseNode#object} is not set.
  4996. *
  4997. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  4998. * @return {Object} The updated reference.
  4999. */
  5000. updateReference( state ) {
  5001. this.reference = this.object !== null ? this.object : state.object;
  5002. return this.reference;
  5003. }
  5004. /**
  5005. * The output of the reference node is the internal uniform node.
  5006. *
  5007. * @param {NodeBuilder} builder - The current node builder.
  5008. * @return {UniformNode} The output node.
  5009. */
  5010. setup() {
  5011. this.updateValue();
  5012. return this.node;
  5013. }
  5014. /**
  5015. * Overwritten to to update the internal uniform value.
  5016. *
  5017. * @param {NodeFrame} frame - A reference to the current node frame.
  5018. */
  5019. update( /*frame*/ ) {
  5020. this.updateValue();
  5021. }
  5022. /**
  5023. * Retrieves the value from the referred object property and uses it
  5024. * to updated the internal uniform.
  5025. */
  5026. updateValue() {
  5027. if ( this.node === null ) this.setNodeType( this.uniformType );
  5028. const value = this.getValueFromReference();
  5029. if ( Array.isArray( value ) ) {
  5030. this.node.array = value;
  5031. } else {
  5032. this.node.value = value;
  5033. }
  5034. }
  5035. }
  5036. /**
  5037. * TSL function for creating a reference base node.
  5038. *
  5039. * @function
  5040. * @param {String} name - The name of the property the node refers to.
  5041. * @param {String} type - The uniform type that should be used to represent the property value.
  5042. * @param {Object} object - The object the property belongs to.
  5043. * @returns {ReferenceBaseNode}
  5044. */
  5045. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5046. /** @module RendererReferenceNode **/
  5047. /**
  5048. * This node is a special type of reference node which is intended
  5049. * for linking renderer properties with node values.
  5050. * ```js
  5051. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5052. * ```
  5053. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5054. * automatically be updated.
  5055. *
  5056. * @augments ReferenceBaseNode
  5057. */
  5058. class RendererReferenceNode extends ReferenceBaseNode {
  5059. static get type() {
  5060. return 'RendererReferenceNode';
  5061. }
  5062. /**
  5063. * Constructs a new renderer reference node.
  5064. *
  5065. * @param {String} property - The name of the property the node refers to.
  5066. * @param {String} inputType - The uniform type that should be used to represent the property value.
  5067. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5068. * the node refers to the renderer of the current state.
  5069. */
  5070. constructor( property, inputType, renderer = null ) {
  5071. super( property, inputType, renderer );
  5072. /**
  5073. * The renderer the property belongs to. When no renderer is set,
  5074. * the node refers to the renderer of the current state.
  5075. *
  5076. * @type {Renderer?}
  5077. * @default null
  5078. */
  5079. this.renderer = renderer;
  5080. this.setGroup( renderGroup );
  5081. }
  5082. /**
  5083. * Updates the reference based on the given state. The state is only evaluated
  5084. * {@link module:RendererReferenceNode~RendererReferenceNode#renderer} is not set.
  5085. *
  5086. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5087. * @return {Object} The updated reference.
  5088. */
  5089. updateReference( state ) {
  5090. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5091. return this.reference;
  5092. }
  5093. }
  5094. /**
  5095. * TSL function for creating a renderer reference node.
  5096. *
  5097. * @function
  5098. * @param {String} name - The name of the property the node refers to.
  5099. * @param {String} type - The uniform type that should be used to represent the property value.
  5100. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5101. * the node refers to the renderer of the current state.
  5102. * @returns {RendererReferenceNode}
  5103. */
  5104. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5105. /** @module ToneMappingNode **/
  5106. /**
  5107. * This node represents a tone mapping operation.
  5108. *
  5109. * @augments TempNode
  5110. */
  5111. class ToneMappingNode extends TempNode {
  5112. static get type() {
  5113. return 'ToneMappingNode';
  5114. }
  5115. /**
  5116. * Constructs a new tone mapping node.
  5117. *
  5118. * @param {Number} toneMapping - The tone mapping type.
  5119. * @param {Node} exposureNode - The tone mapping exposure.
  5120. * @param {Node} [colorNode=null] - The color node to process.
  5121. */
  5122. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5123. super( 'vec3' );
  5124. /**
  5125. * The tone mapping type.
  5126. *
  5127. * @type {Number}
  5128. */
  5129. this.toneMapping = toneMapping;
  5130. /**
  5131. * The tone mapping exposure.
  5132. *
  5133. * @type {Node}
  5134. * @default null
  5135. */
  5136. this.exposureNode = exposureNode;
  5137. /**
  5138. * Represents the color to process.
  5139. *
  5140. * @type {Node?}
  5141. * @default null
  5142. */
  5143. this.colorNode = colorNode;
  5144. }
  5145. /**
  5146. * Overwrites the default `customCacheKey()` implementation by including the tone
  5147. * mapping type into the cache key.
  5148. *
  5149. * @return {Number} The hash.
  5150. */
  5151. customCacheKey() {
  5152. return hash$1( this.toneMapping );
  5153. }
  5154. setup( builder ) {
  5155. const colorNode = this.colorNode || builder.context.color;
  5156. const toneMapping = this.toneMapping;
  5157. if ( toneMapping === NoToneMapping ) return colorNode;
  5158. let outputNode = null;
  5159. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5160. if ( toneMappingFn !== null ) {
  5161. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5162. } else {
  5163. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5164. outputNode = colorNode;
  5165. }
  5166. return outputNode;
  5167. }
  5168. }
  5169. /**
  5170. * TSL function for creating a tone mapping node.
  5171. *
  5172. * @function
  5173. * @param {Number} mapping - The tone mapping type.
  5174. * @param {Node<float> | Number} exposure - The tone mapping exposure.
  5175. * @param {Node<vec3> | Color} color - The color node to process.
  5176. * @returns {ToneMappingNode<vec3>}
  5177. */
  5178. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5179. /**
  5180. * TSL object that represents the global tone mapping exposure of the renderer.
  5181. *
  5182. * @type {RendererReferenceNode<vec3>}
  5183. */
  5184. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5185. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5186. /** @module BufferAttributeNode **/
  5187. /**
  5188. * In earlier `three.js` versions it was only possible to define attribute data
  5189. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5190. * on the node level.
  5191. * ```js
  5192. * const geometry = new THREE.PlaneGeometry();
  5193. * const positionAttribute = geometry.getAttribute( 'position' );
  5194. *
  5195. * const colors = [];
  5196. * for ( let i = 0; i < position.count; i ++ ) {
  5197. * colors.push( 1, 0, 0 );
  5198. * }
  5199. *
  5200. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5201. * ```
  5202. * This new approach is especially interesting when geometry data are generated via
  5203. * compute shaders. The below line converts a storage buffer into an attribute node.
  5204. * ```js
  5205. * material.positionNode = positionBuffer.toAttribute();
  5206. * ```
  5207. * @augments InputNode
  5208. */
  5209. class BufferAttributeNode extends InputNode {
  5210. static get type() {
  5211. return 'BufferAttributeNode';
  5212. }
  5213. /**
  5214. * Constructs a new buffer attribute node.
  5215. *
  5216. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5217. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5218. * @param {Number} [bufferStride=0] - The buffer stride.
  5219. * @param {Number} [bufferOffset=0] - The buffer offset.
  5220. */
  5221. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5222. super( value, bufferType );
  5223. /**
  5224. * This flag can be used for type testing.
  5225. *
  5226. * @type {Boolean}
  5227. * @readonly
  5228. * @default true
  5229. */
  5230. this.isBufferNode = true;
  5231. /**
  5232. * The buffer type (e.g. `'vec3'`).
  5233. *
  5234. * @type {String}
  5235. * @default null
  5236. */
  5237. this.bufferType = bufferType;
  5238. /**
  5239. * The buffer stride.
  5240. *
  5241. * @type {Number}
  5242. * @default 0
  5243. */
  5244. this.bufferStride = bufferStride;
  5245. /**
  5246. * The buffer offset.
  5247. *
  5248. * @type {Number}
  5249. * @default 0
  5250. */
  5251. this.bufferOffset = bufferOffset;
  5252. /**
  5253. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5254. * if you are planning to update the attribute data per frame.
  5255. *
  5256. * @type {Number}
  5257. * @default StaticDrawUsage
  5258. */
  5259. this.usage = StaticDrawUsage;
  5260. /**
  5261. * Whether the attribute is instanced or not.
  5262. *
  5263. * @type {Boolean}
  5264. * @default false
  5265. */
  5266. this.instanced = false;
  5267. /**
  5268. * A reference to the buffer attribute.
  5269. *
  5270. * @type {BufferAttribute?}
  5271. * @default null
  5272. */
  5273. this.attribute = null;
  5274. /**
  5275. * `BufferAttributeNode` sets this property to `true` by default.
  5276. *
  5277. * @type {Boolean}
  5278. * @default true
  5279. */
  5280. this.global = true;
  5281. if ( value && value.isBufferAttribute === true ) {
  5282. this.attribute = value;
  5283. this.usage = value.usage;
  5284. this.instanced = value.isInstancedBufferAttribute;
  5285. }
  5286. }
  5287. /**
  5288. * This method is overwritten since the attribute data might be shared
  5289. * and thus the hash should be shared as well.
  5290. *
  5291. * @param {NodeBuilder} builder - The current node builder.
  5292. * @return {String} The hash.
  5293. */
  5294. getHash( builder ) {
  5295. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5296. let bufferData = builder.globalCache.getData( this.value );
  5297. if ( bufferData === undefined ) {
  5298. bufferData = {
  5299. node: this
  5300. };
  5301. builder.globalCache.setData( this.value, bufferData );
  5302. }
  5303. return bufferData.node.uuid;
  5304. }
  5305. return this.uuid;
  5306. }
  5307. /**
  5308. * This method is overwritten since the node type is inferred from
  5309. * the buffer attribute.
  5310. *
  5311. * @param {NodeBuilder} builder - The current node builder.
  5312. * @return {String} The node type.
  5313. */
  5314. getNodeType( builder ) {
  5315. if ( this.bufferType === null ) {
  5316. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5317. }
  5318. return this.bufferType;
  5319. }
  5320. /**
  5321. * Depending on which value was passed to the node, `setup()` behaves
  5322. * differently. If no instance of `BufferAttribute` was passed, the method
  5323. * creates an internal attribute and configures it respectively.
  5324. *
  5325. * @param {NodeBuilder} builder - The current node builder.
  5326. */
  5327. setup( builder ) {
  5328. if ( this.attribute !== null ) return;
  5329. const type = this.getNodeType( builder );
  5330. const array = this.value;
  5331. const itemSize = builder.getTypeLength( type );
  5332. const stride = this.bufferStride || itemSize;
  5333. const offset = this.bufferOffset;
  5334. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5335. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5336. buffer.setUsage( this.usage );
  5337. this.attribute = bufferAttribute;
  5338. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5339. }
  5340. /**
  5341. * Generates the code snippet of the buffer attribute node.
  5342. *
  5343. * @param {NodeBuilder} builder - The current node builder.
  5344. * @return {String} The generated code snippet.
  5345. */
  5346. generate( builder ) {
  5347. const nodeType = this.getNodeType( builder );
  5348. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5349. const propertyName = builder.getPropertyName( nodeAttribute );
  5350. let output = null;
  5351. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5352. this.name = propertyName;
  5353. output = propertyName;
  5354. } else {
  5355. const nodeVarying = varying( this );
  5356. output = nodeVarying.build( builder, nodeType );
  5357. }
  5358. return output;
  5359. }
  5360. /**
  5361. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5362. *
  5363. * @param {NodeBuilder} builder - The current node builder.
  5364. * @return {String} The input type.
  5365. */
  5366. getInputType( /*builder*/ ) {
  5367. return 'bufferAttribute';
  5368. }
  5369. /**
  5370. * Sets the `usage` property to the given value.
  5371. *
  5372. * @param {Number} value - The usage to set.
  5373. * @return {BufferAttributeNode} A reference to this node.
  5374. */
  5375. setUsage( value ) {
  5376. this.usage = value;
  5377. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5378. this.attribute.usage = value;
  5379. }
  5380. return this;
  5381. }
  5382. /**
  5383. * Sets the `instanced` property to the given value.
  5384. *
  5385. * @param {Number} value - The value to set.
  5386. * @return {BufferAttributeNode} A reference to this node.
  5387. */
  5388. setInstanced( value ) {
  5389. this.instanced = value;
  5390. return this;
  5391. }
  5392. }
  5393. /**
  5394. * TSL function for creating a buffer attribute node.
  5395. *
  5396. * @function
  5397. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5398. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5399. * @param {Number} [stride=0] - The buffer stride.
  5400. * @param {Number} [offset=0] - The buffer offset.
  5401. * @returns {BufferAttributeNode}
  5402. */
  5403. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5404. /**
  5405. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5406. * Use this function if attribute data are updated per frame.
  5407. *
  5408. * @function
  5409. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5410. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5411. * @param {Number} [stride=0] - The buffer stride.
  5412. * @param {Number} [offset=0] - The buffer offset.
  5413. * @returns {BufferAttributeNode}
  5414. */
  5415. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5416. /**
  5417. * TSL function for creating a buffer attribute node but with enabled instancing
  5418. *
  5419. * @function
  5420. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5421. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5422. * @param {Number} [stride=0] - The buffer stride.
  5423. * @param {Number} [offset=0] - The buffer offset.
  5424. * @returns {BufferAttributeNode}
  5425. */
  5426. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5427. /**
  5428. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5429. *
  5430. * @function
  5431. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5432. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5433. * @param {Number} [stride=0] - The buffer stride.
  5434. * @param {Number} [offset=0] - The buffer offset.
  5435. * @returns {BufferAttributeNode}
  5436. */
  5437. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5438. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5439. /** @module ComputeNode **/
  5440. /**
  5441. * TODO
  5442. *
  5443. * @augments Node
  5444. */
  5445. class ComputeNode extends Node {
  5446. static get type() {
  5447. return 'ComputeNode';
  5448. }
  5449. /**
  5450. * Constructs a new compute node.
  5451. *
  5452. * @param {Node} computeNode - TODO
  5453. * @param {Number} count - TODO.
  5454. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5455. */
  5456. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5457. super( 'void' );
  5458. /**
  5459. * This flag can be used for type testing.
  5460. *
  5461. * @type {Boolean}
  5462. * @readonly
  5463. * @default true
  5464. */
  5465. this.isComputeNode = true;
  5466. /**
  5467. * TODO
  5468. *
  5469. * @type {Node}
  5470. */
  5471. this.computeNode = computeNode;
  5472. /**
  5473. * TODO
  5474. *
  5475. * @type {Number}
  5476. */
  5477. this.count = count;
  5478. /**
  5479. * TODO
  5480. *
  5481. * @type {Array<Number>}
  5482. * @default [64]
  5483. */
  5484. this.workgroupSize = workgroupSize;
  5485. /**
  5486. * TODO
  5487. *
  5488. * @type {Number}
  5489. */
  5490. this.dispatchCount = 0;
  5491. /**
  5492. * TODO
  5493. *
  5494. * @type {Number}
  5495. */
  5496. this.version = 1;
  5497. /**
  5498. * The name or label of the uniform.
  5499. *
  5500. * @type {String}
  5501. * @default ''
  5502. */
  5503. this.name = '';
  5504. /**
  5505. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5506. * is executed once per object by default.
  5507. *
  5508. * @type {String}
  5509. * @default 'object'
  5510. */
  5511. this.updateBeforeType = NodeUpdateType.OBJECT;
  5512. /**
  5513. * TODO
  5514. *
  5515. * @type {Function}
  5516. */
  5517. this.onInitFunction = null;
  5518. this.updateDispatchCount();
  5519. }
  5520. /**
  5521. * Executes the `dispose` event for this node.
  5522. */
  5523. dispose() {
  5524. this.dispatchEvent( { type: 'dispose' } );
  5525. }
  5526. /**
  5527. * Sets the {@link ComputeNode#name} property.
  5528. *
  5529. * @param {String} name - The name of the uniform.
  5530. * @return {ComputeNode} A reference to this node.
  5531. */
  5532. label( name ) {
  5533. this.name = name;
  5534. return this;
  5535. }
  5536. /**
  5537. * TODO
  5538. */
  5539. updateDispatchCount() {
  5540. const { count, workgroupSize } = this;
  5541. let size = workgroupSize[ 0 ];
  5542. for ( let i = 1; i < workgroupSize.length; i ++ )
  5543. size *= workgroupSize[ i ];
  5544. this.dispatchCount = Math.ceil( count / size );
  5545. }
  5546. /**
  5547. * TODO
  5548. *
  5549. * @param {Function} callback - TODO.
  5550. * @return {ComputeNode} A reference to this node.
  5551. */
  5552. onInit( callback ) {
  5553. this.onInitFunction = callback;
  5554. return this;
  5555. }
  5556. /**
  5557. * The method execute the compute for this node.
  5558. *
  5559. * @param {NodeFrame} frame - A reference to the current node frame.
  5560. */
  5561. updateBefore( { renderer } ) {
  5562. renderer.compute( this );
  5563. }
  5564. generate( builder ) {
  5565. const { shaderStage } = builder;
  5566. if ( shaderStage === 'compute' ) {
  5567. const snippet = this.computeNode.build( builder, 'void' );
  5568. if ( snippet !== '' ) {
  5569. builder.addLineFlowCode( snippet, this );
  5570. }
  5571. }
  5572. }
  5573. }
  5574. /**
  5575. * TSL function for creating a compute node.
  5576. *
  5577. * @function
  5578. * @param {Node} node - TODO
  5579. * @param {Number} count - TODO.
  5580. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5581. * @returns {AtomicFunctionNode}
  5582. */
  5583. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  5584. addMethodChaining( 'compute', compute );
  5585. /** @module CacheNode **/
  5586. /**
  5587. * This node can be used as a cache management component for another node.
  5588. * Caching is in general used by default in {@link NodeBuilder} but this node
  5589. * allows the usage of a shared parent cache during the build process.
  5590. *
  5591. * @augments Node
  5592. */
  5593. class CacheNode extends Node {
  5594. static get type() {
  5595. return 'CacheNode';
  5596. }
  5597. /**
  5598. * Constructs a new cache node.
  5599. *
  5600. * @param {Node} node - The node that should be cached.
  5601. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  5602. */
  5603. constructor( node, parent = true ) {
  5604. super();
  5605. /**
  5606. * The node that should be cached.
  5607. *
  5608. * @type {Node}
  5609. */
  5610. this.node = node;
  5611. /**
  5612. * Whether this node refers to a shared parent cache or not.
  5613. *
  5614. * @type {Boolean}
  5615. * @default true
  5616. */
  5617. this.parent = parent;
  5618. /**
  5619. * This flag can be used for type testing.
  5620. *
  5621. * @type {Boolean}
  5622. * @readonly
  5623. * @default true
  5624. */
  5625. this.isCacheNode = true;
  5626. }
  5627. getNodeType( builder ) {
  5628. const previousCache = builder.getCache();
  5629. const cache = builder.getCacheFromNode( this, this.parent );
  5630. builder.setCache( cache );
  5631. const nodeType = this.node.getNodeType( builder );
  5632. builder.setCache( previousCache );
  5633. return nodeType;
  5634. }
  5635. build( builder, ...params ) {
  5636. const previousCache = builder.getCache();
  5637. const cache = builder.getCacheFromNode( this, this.parent );
  5638. builder.setCache( cache );
  5639. const data = this.node.build( builder, ...params );
  5640. builder.setCache( previousCache );
  5641. return data;
  5642. }
  5643. }
  5644. /**
  5645. * TSL function for creating a cache node.
  5646. *
  5647. * @function
  5648. * @param {Node} node - The node that should be cached.
  5649. * @param {Boolean} parent - Whether this node refers to a shared parent cache or not.
  5650. * @returns {CacheNode}
  5651. */
  5652. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  5653. addMethodChaining( 'cache', cache );
  5654. /** @module BypassNode **/
  5655. /**
  5656. * The class generates the code of a given node but returns another node in the output.
  5657. * This can be used to call a method or node that does not return a value, i.e.
  5658. * type `void` on an input where returning a value is required. Example:
  5659. *
  5660. * ```js
  5661. * material.colorNode = myColor.bypass( runVoidFn() )
  5662. *```
  5663. *
  5664. * @augments Node
  5665. */
  5666. class BypassNode extends Node {
  5667. static get type() {
  5668. return 'BypassNode';
  5669. }
  5670. /**
  5671. * Constructs a new bypass node.
  5672. *
  5673. * @param {Node} outputNode - The output node.
  5674. * @param {Node} callNode - The call node.
  5675. */
  5676. constructor( outputNode, callNode ) {
  5677. super();
  5678. /**
  5679. * This flag can be used for type testing.
  5680. *
  5681. * @type {Boolean}
  5682. * @readonly
  5683. * @default true
  5684. */
  5685. this.isBypassNode = true;
  5686. /**
  5687. * The output node.
  5688. *
  5689. * @type {Node}
  5690. */
  5691. this.outputNode = outputNode;
  5692. /**
  5693. * The call node.
  5694. *
  5695. * @type {Node}
  5696. */
  5697. this.callNode = callNode;
  5698. }
  5699. getNodeType( builder ) {
  5700. return this.outputNode.getNodeType( builder );
  5701. }
  5702. generate( builder ) {
  5703. const snippet = this.callNode.build( builder, 'void' );
  5704. if ( snippet !== '' ) {
  5705. builder.addLineFlowCode( snippet, this );
  5706. }
  5707. return this.outputNode.build( builder );
  5708. }
  5709. }
  5710. /**
  5711. * TSL function for creating a bypass node.
  5712. *
  5713. * @function
  5714. * @param {Node} outputNode - The output node.
  5715. * @param {Node} callNode - The call node.
  5716. * @returns {BypassNode}
  5717. */
  5718. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  5719. addMethodChaining( 'bypass', bypass );
  5720. /** @module RemapNode **/
  5721. /**
  5722. * This node allows to remap a node value from one range into another. E.g a value of
  5723. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  5724. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  5725. *
  5726. * @augments Node
  5727. */
  5728. class RemapNode extends Node {
  5729. static get type() {
  5730. return 'RemapNode';
  5731. }
  5732. /**
  5733. * Constructs a new remap node.
  5734. *
  5735. * @param {Node} node - The node that should be remapped.
  5736. * @param {Node} inLowNode - The source or current lower bound of the range.
  5737. * @param {Node} inHighNode - The source or current upper bound of the range.
  5738. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5739. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5740. */
  5741. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  5742. super();
  5743. /**
  5744. * The node that should be remapped.
  5745. *
  5746. * @type {Node}
  5747. */
  5748. this.node = node;
  5749. /**
  5750. * The source or current lower bound of the range.
  5751. *
  5752. * @type {Node}
  5753. */
  5754. this.inLowNode = inLowNode;
  5755. /**
  5756. * The source or current upper bound of the range.
  5757. *
  5758. * @type {Node}
  5759. */
  5760. this.inHighNode = inHighNode;
  5761. /**
  5762. * The target lower bound of the range.
  5763. *
  5764. * @type {Node}
  5765. * @default float(0)
  5766. */
  5767. this.outLowNode = outLowNode;
  5768. /**
  5769. * The target upper bound of the range.
  5770. *
  5771. * @type {Node}
  5772. * @default float(1)
  5773. */
  5774. this.outHighNode = outHighNode;
  5775. /**
  5776. * Whether the node value should be clamped before
  5777. * remapping it to the target range.
  5778. *
  5779. * @type {Boolean}
  5780. * @default true
  5781. */
  5782. this.doClamp = true;
  5783. }
  5784. setup() {
  5785. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  5786. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  5787. if ( doClamp === true ) t = t.clamp();
  5788. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  5789. }
  5790. }
  5791. /**
  5792. * TSL function for creating a remap node.
  5793. *
  5794. * @function
  5795. * @param {Node} node - The node that should be remapped.
  5796. * @param {Node} inLowNode - The source or current lower bound of the range.
  5797. * @param {Node} inHighNode - The source or current upper bound of the range.
  5798. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5799. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5800. * @returns {RemapNode}
  5801. */
  5802. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  5803. /**
  5804. * TSL function for creating a remap node, but with enabled clamping.
  5805. *
  5806. * @function
  5807. * @param {Node} node - The node that should be remapped.
  5808. * @param {Node} inLowNode - The source or current lower bound of the range.
  5809. * @param {Node} inHighNode - The source or current upper bound of the range.
  5810. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5811. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5812. * @returns {RemapNode}
  5813. */
  5814. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  5815. addMethodChaining( 'remap', remap );
  5816. addMethodChaining( 'remapClamp', remapClamp );
  5817. /** @module ExpressionNode **/
  5818. /**
  5819. * This class can be used to implement basic expressions in shader code.
  5820. * Basic examples for that are `return`, `continue` or `discard` statements.
  5821. *
  5822. * @augments Node
  5823. */
  5824. class ExpressionNode extends Node {
  5825. static get type() {
  5826. return 'ExpressionNode';
  5827. }
  5828. /**
  5829. * Constructs a new expression node.
  5830. *
  5831. * @param {String} [snippet=''] - The native code snippet.
  5832. * @param {String} [nodeType='void'] - The node type.
  5833. */
  5834. constructor( snippet = '', nodeType = 'void' ) {
  5835. super( nodeType );
  5836. /**
  5837. * The native code snippet.
  5838. *
  5839. * @type {String}
  5840. * @default ''
  5841. */
  5842. this.snippet = snippet;
  5843. }
  5844. generate( builder, output ) {
  5845. const type = this.getNodeType( builder );
  5846. const snippet = this.snippet;
  5847. if ( type === 'void' ) {
  5848. builder.addLineFlowCode( snippet, this );
  5849. } else {
  5850. return builder.format( `( ${ snippet } )`, type, output );
  5851. }
  5852. }
  5853. }
  5854. /**
  5855. * TSL function for creating an expression node.
  5856. *
  5857. * @function
  5858. * @param {String} [snippet=''] - The native code snippet.
  5859. * @param {String} [nodeType='void'] - The node type.
  5860. * @returns {ExpressionNode}
  5861. */
  5862. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  5863. /** @module Discard **/
  5864. /**
  5865. * Represents a `discard` shader operation in TSL.
  5866. *
  5867. * @method
  5868. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  5869. * @return {Node} The `discard` expression.
  5870. */
  5871. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  5872. /**
  5873. * Represents a `return` shader operation in TSL.
  5874. *
  5875. * @method
  5876. * @return {ExpressionNode} The `return` expression.
  5877. */
  5878. const Return = () => expression( 'return' ).append();
  5879. addMethodChaining( 'discard', Discard );
  5880. /** @module RenderOutputNode **/
  5881. /**
  5882. * Normally, tone mapping and color conversion happens automatically
  5883. * before outputting pixel too the default (screen) framebuffer. In certain
  5884. * post processing setups this happens to late because certain effects
  5885. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  5886. * to apply tone mapping and color space conversion at an arbitrary point
  5887. * in the effect chain.
  5888. *
  5889. * When applying tone mapping and color space conversion manually with this node,
  5890. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  5891. *
  5892. * ```js
  5893. * const postProcessing = new PostProcessing( renderer );
  5894. * postProcessing.outputColorTransform = false;
  5895. *
  5896. * const scenePass = pass( scene, camera );
  5897. * const outputPass = renderOutput( scenePass );
  5898. *
  5899. * postProcessing.outputNode = outputPass;
  5900. * ```
  5901. *
  5902. * @augments TempNode
  5903. */
  5904. class RenderOutputNode extends TempNode {
  5905. static get type() {
  5906. return 'RenderOutputNode';
  5907. }
  5908. /**
  5909. * Constructs a new render output node.
  5910. *
  5911. * @param {Node} colorNode - The color node to process.
  5912. * @param {Number} toneMapping - The tone mapping type.
  5913. * @param {String} outputColorSpace - The output color space.
  5914. */
  5915. constructor( colorNode, toneMapping, outputColorSpace ) {
  5916. super( 'vec4' );
  5917. /**
  5918. * The color node to process.
  5919. *
  5920. * @type {Node}
  5921. */
  5922. this.colorNode = colorNode;
  5923. /**
  5924. * The tone mapping type.
  5925. *
  5926. * @type {Number?}
  5927. */
  5928. this.toneMapping = toneMapping;
  5929. /**
  5930. * The output color space.
  5931. *
  5932. * @type {String?}
  5933. */
  5934. this.outputColorSpace = outputColorSpace;
  5935. /**
  5936. * This flag can be used for type testing.
  5937. *
  5938. * @type {Boolean}
  5939. * @readonly
  5940. * @default true
  5941. */
  5942. this.isRenderOutputNode = true;
  5943. }
  5944. setup( { context } ) {
  5945. let outputNode = this.colorNode || context.color;
  5946. // tone mapping
  5947. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  5948. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  5949. if ( toneMapping !== NoToneMapping ) {
  5950. outputNode = outputNode.toneMapping( toneMapping );
  5951. }
  5952. // working to output color space
  5953. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  5954. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  5955. }
  5956. return outputNode;
  5957. }
  5958. }
  5959. /**
  5960. * TSL function for creating a posterize node.
  5961. *
  5962. * @function
  5963. * @param {Node} color - The color node to process.
  5964. * @param {Number?} [toneMapping=null] - The tone mapping type.
  5965. * @param {String?} [outputColorSpace=null] - The output color space.
  5966. * @returns {RenderOutputNode}
  5967. */
  5968. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  5969. addMethodChaining( 'renderOutput', renderOutput );
  5970. // Non-PURE exports list, side-effects are required here.
  5971. // TSL Base Syntax
  5972. function addNodeElement( name/*, nodeElement*/ ) {
  5973. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  5974. }
  5975. /** @module AttributeNode **/
  5976. /**
  5977. * Base class for representing shader attributes as nodes.
  5978. *
  5979. * @augments Node
  5980. */
  5981. class AttributeNode extends Node {
  5982. static get type() {
  5983. return 'AttributeNode';
  5984. }
  5985. /**
  5986. * Constructs a new attribute node.
  5987. *
  5988. * @param {String} attributeName - The name of the attribute.
  5989. * @param {String?} nodeType - The node type.
  5990. */
  5991. constructor( attributeName, nodeType = null ) {
  5992. super( nodeType );
  5993. /**
  5994. * `AttributeNode` sets this property to `true` by default.
  5995. *
  5996. * @type {Boolean}
  5997. * @default true
  5998. */
  5999. this.global = true;
  6000. this._attributeName = attributeName;
  6001. }
  6002. getHash( builder ) {
  6003. return this.getAttributeName( builder );
  6004. }
  6005. getNodeType( builder ) {
  6006. let nodeType = this.nodeType;
  6007. if ( nodeType === null ) {
  6008. const attributeName = this.getAttributeName( builder );
  6009. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6010. const attribute = builder.geometry.getAttribute( attributeName );
  6011. nodeType = builder.getTypeFromAttribute( attribute );
  6012. } else {
  6013. nodeType = 'float';
  6014. }
  6015. }
  6016. return nodeType;
  6017. }
  6018. /**
  6019. * Sets the attribute name to the given value. The method can be
  6020. * overwritten in derived classes if the final name must be computed
  6021. * analytically.
  6022. *
  6023. * @param {String} attributeName - The name of the attribute.
  6024. * @return {AttributeNode} A reference to this node.
  6025. */
  6026. setAttributeName( attributeName ) {
  6027. this._attributeName = attributeName;
  6028. return this;
  6029. }
  6030. /**
  6031. * Returns the attribute name of this node. The method can be
  6032. * overwritten in derived classes if the final name must be computed
  6033. * analytically.
  6034. *
  6035. * @param {NodeBuilder} builder - The current node builder.
  6036. * @return {String} The attribute name.
  6037. */
  6038. getAttributeName( /*builder*/ ) {
  6039. return this._attributeName;
  6040. }
  6041. generate( builder ) {
  6042. const attributeName = this.getAttributeName( builder );
  6043. const nodeType = this.getNodeType( builder );
  6044. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6045. if ( geometryAttribute === true ) {
  6046. const attribute = builder.geometry.getAttribute( attributeName );
  6047. const attributeType = builder.getTypeFromAttribute( attribute );
  6048. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6049. if ( builder.shaderStage === 'vertex' ) {
  6050. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6051. } else {
  6052. const nodeVarying = varying( this );
  6053. return nodeVarying.build( builder, nodeType );
  6054. }
  6055. } else {
  6056. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6057. return builder.generateConst( nodeType );
  6058. }
  6059. }
  6060. serialize( data ) {
  6061. super.serialize( data );
  6062. data.global = this.global;
  6063. data._attributeName = this._attributeName;
  6064. }
  6065. deserialize( data ) {
  6066. super.deserialize( data );
  6067. this.global = data.global;
  6068. this._attributeName = data._attributeName;
  6069. }
  6070. }
  6071. /**
  6072. * TSL function for creating an attribute node.
  6073. *
  6074. * @function
  6075. * @param {String} name - The name of the attribute.
  6076. * @param {String?} nodeType - The node type.
  6077. * @returns {AttributeNode}
  6078. */
  6079. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6080. /** @module UV **/
  6081. /**
  6082. * TSL function for creating an uv attribute node with the given index.
  6083. *
  6084. * @function
  6085. * @param {Number} [index=0] - The uv index.
  6086. * @return {AttributeNode<vec2>} The uv attribute node.
  6087. */
  6088. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6089. /** @module TextureSizeNode **/
  6090. /**
  6091. * A node that represents the dimensions of a texture. The texture size is
  6092. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6093. * or `textureSize()`.
  6094. *
  6095. * @augments Node
  6096. */
  6097. class TextureSizeNode extends Node {
  6098. static get type() {
  6099. return 'TextureSizeNode';
  6100. }
  6101. /**
  6102. * Constructs a new texture size node.
  6103. *
  6104. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6105. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6106. */
  6107. constructor( textureNode, levelNode = null ) {
  6108. super( 'uvec2' );
  6109. /**
  6110. * This flag can be used for type testing.
  6111. *
  6112. * @type {Boolean}
  6113. * @readonly
  6114. * @default true
  6115. */
  6116. this.isTextureSizeNode = true;
  6117. /**
  6118. * A texture node which size should be retrieved.
  6119. *
  6120. * @type {TextureNode}
  6121. */
  6122. this.textureNode = textureNode;
  6123. /**
  6124. * A level node which defines the requested mip.
  6125. *
  6126. * @type {Node<int>}
  6127. * @default null
  6128. */
  6129. this.levelNode = levelNode;
  6130. }
  6131. generate( builder, output ) {
  6132. const textureProperty = this.textureNode.build( builder, 'property' );
  6133. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6134. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6135. }
  6136. }
  6137. /**
  6138. * TSL function for creating a texture size node.
  6139. *
  6140. * @function
  6141. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6142. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6143. * @returns {TextureSizeNode}
  6144. */
  6145. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6146. /** @module MatcapUVNode **/
  6147. /**
  6148. * A special type of uniform node that computes the
  6149. * maximum mipmap level for a given texture node.
  6150. *
  6151. * ```js
  6152. * const level = maxMipLevel( textureNode );
  6153. * ```
  6154. *
  6155. * @augments module:UniformNode~UniformNode
  6156. */
  6157. class MaxMipLevelNode extends UniformNode {
  6158. static get type() {
  6159. return 'MaxMipLevelNode';
  6160. }
  6161. /**
  6162. * Constructs a new max mip level node.
  6163. *
  6164. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6165. */
  6166. constructor( textureNode ) {
  6167. super( 0 );
  6168. /**
  6169. * The texture node to compute the max mip level for.
  6170. *
  6171. * @private
  6172. * @type {TextureNode}
  6173. */
  6174. this._textureNode = textureNode;
  6175. /**
  6176. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6177. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6178. *
  6179. * @type {String}
  6180. * @default 'frame'
  6181. */
  6182. this.updateType = NodeUpdateType.FRAME;
  6183. }
  6184. /**
  6185. * The texture node to compute the max mip level for.
  6186. *
  6187. * @readonly
  6188. * @type {TextureNode}
  6189. */
  6190. get textureNode() {
  6191. return this._textureNode;
  6192. }
  6193. /**
  6194. * The texture.
  6195. *
  6196. * @readonly
  6197. * @type {Texture}
  6198. */
  6199. get texture() {
  6200. return this._textureNode.value;
  6201. }
  6202. update() {
  6203. const texture = this.texture;
  6204. const images = texture.images;
  6205. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6206. if ( image && image.width !== undefined ) {
  6207. const { width, height } = image;
  6208. this.value = Math.log2( Math.max( width, height ) );
  6209. }
  6210. }
  6211. }
  6212. /**
  6213. * TSL function for creating a max mip level node.
  6214. *
  6215. * @function
  6216. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6217. * @returns {MaxMipLevelNode}
  6218. */
  6219. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6220. /** @module TextureNode **/
  6221. /**
  6222. * This type of uniform node represents a 2D texture.
  6223. *
  6224. * @augments module:UniformNode~UniformNode
  6225. */
  6226. class TextureNode extends UniformNode {
  6227. static get type() {
  6228. return 'TextureNode';
  6229. }
  6230. /**
  6231. * Constructs a new texture node.
  6232. *
  6233. * @param {Texture} value - The texture.
  6234. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6235. * @param {Node<int>?} [levelNode=null] - The level node.
  6236. * @param {Node<float>?} [biasNode=null] - The bias node.
  6237. */
  6238. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6239. super( value );
  6240. /**
  6241. * This flag can be used for type testing.
  6242. *
  6243. * @type {Boolean}
  6244. * @readonly
  6245. * @default true
  6246. */
  6247. this.isTextureNode = true;
  6248. /**
  6249. * Represents the texture coordinates.
  6250. *
  6251. * @type {Node<vec2|vec3>?}
  6252. * @default null
  6253. */
  6254. this.uvNode = uvNode;
  6255. /**
  6256. * Represents the mip level that should be selected.
  6257. *
  6258. * @type {Node<int>?}
  6259. * @default null
  6260. */
  6261. this.levelNode = levelNode;
  6262. /**
  6263. * Represents the bias to be applied during level-of-detail computation.
  6264. *
  6265. * @type {Node<float>?}
  6266. * @default null
  6267. */
  6268. this.biasNode = biasNode;
  6269. /**
  6270. * Represents a reference value a texture sample is compared to.
  6271. *
  6272. * @type {Node<float>?}
  6273. * @default null
  6274. */
  6275. this.compareNode = null;
  6276. /**
  6277. * When using texture arrays, the depth node defines the layer to select.
  6278. *
  6279. * @type {Node<int>?}
  6280. * @default null
  6281. */
  6282. this.depthNode = null;
  6283. /**
  6284. * When defined, a texture is sampled using explicit gradients.
  6285. *
  6286. * @type {Array<Node<vec2>>?}
  6287. * @default null
  6288. */
  6289. this.gradNode = null;
  6290. /**
  6291. * Whether texture values should be sampled or fetched.
  6292. *
  6293. * @type {Boolean}
  6294. * @default true
  6295. */
  6296. this.sampler = true;
  6297. /**
  6298. * Whether the uv transformation matrix should be
  6299. * automatically updated or not. Use `setUpdateMatrix()`
  6300. * if you want to change the value of the property.
  6301. *
  6302. * @type {Boolean}
  6303. * @default false
  6304. */
  6305. this.updateMatrix = false;
  6306. /**
  6307. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6308. * sets the value to `frame` when the uv transformation matrix should
  6309. * automatically be updated.
  6310. *
  6311. * @type {String}
  6312. * @default 'none'
  6313. */
  6314. this.updateType = NodeUpdateType.NONE;
  6315. /**
  6316. * The reference node.
  6317. *
  6318. * @type {Node?}
  6319. * @default null
  6320. */
  6321. this.referenceNode = null;
  6322. /**
  6323. * The texture value is stored in a private property.
  6324. *
  6325. * @private
  6326. * @type {Texture}
  6327. */
  6328. this._value = value;
  6329. /**
  6330. * The uniform node that represents the uv transformation matrix.
  6331. *
  6332. * @private
  6333. * @type {UniformNode<mat3>?}
  6334. */
  6335. this._matrixUniform = null;
  6336. this.setUpdateMatrix( uvNode === null );
  6337. }
  6338. set value( value ) {
  6339. if ( this.referenceNode ) {
  6340. this.referenceNode.value = value;
  6341. } else {
  6342. this._value = value;
  6343. }
  6344. }
  6345. /**
  6346. * The texture value.
  6347. *
  6348. * @type {Texture}
  6349. */
  6350. get value() {
  6351. return this.referenceNode ? this.referenceNode.value : this._value;
  6352. }
  6353. /**
  6354. * Overwritten since the uniform hash is defined by the texture's UUID.
  6355. *
  6356. * @param {NodeBuilder} builder - The current node builder.
  6357. * @return {String} The uniform hash.
  6358. */
  6359. getUniformHash( /*builder*/ ) {
  6360. return this.value.uuid;
  6361. }
  6362. /**
  6363. * Overwritten since the node type is inferred from the texture type.
  6364. *
  6365. * @param {NodeBuilder} builder - The current node builder.
  6366. * @return {String} The node type.
  6367. */
  6368. getNodeType( /*builder*/ ) {
  6369. if ( this.value.isDepthTexture === true ) return 'float';
  6370. if ( this.value.type === UnsignedIntType ) {
  6371. return 'uvec4';
  6372. } else if ( this.value.type === IntType ) {
  6373. return 'ivec4';
  6374. }
  6375. return 'vec4';
  6376. }
  6377. /**
  6378. * Overwrites the default implementation to return a fixed value `'texture'`.
  6379. *
  6380. * @param {NodeBuilder} builder - The current node builder.
  6381. * @return {String} The input type.
  6382. */
  6383. getInputType( /*builder*/ ) {
  6384. return 'texture';
  6385. }
  6386. /**
  6387. * Returns a default uvs based on the current texture's channel.
  6388. *
  6389. * @return {AttributeNode<vec2>} The default uvs.
  6390. */
  6391. getDefaultUV() {
  6392. return uv( this.value.channel );
  6393. }
  6394. /**
  6395. * Overwritten to always return the texture reference of the node.
  6396. *
  6397. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6398. * @return {Texture} The texture reference.
  6399. */
  6400. updateReference( /*state*/ ) {
  6401. return this.value;
  6402. }
  6403. /**
  6404. * Transforms the given uv node with the texture transformation matrix.
  6405. *
  6406. * @param {Node} uvNode - The uv node to transform.
  6407. * @return {Node} The transformed uv node.
  6408. */
  6409. getTransformedUV( uvNode ) {
  6410. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6411. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6412. }
  6413. /**
  6414. * Defines whether the uv transformation matrix should automatically be updated or not.
  6415. *
  6416. * @param {Boolean} value - The update toggle.
  6417. * @return {TextureNode} A reference to this node.
  6418. */
  6419. setUpdateMatrix( value ) {
  6420. this.updateMatrix = value;
  6421. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6422. return this;
  6423. }
  6424. /**
  6425. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6426. * to modify the uv node for correct sampling.
  6427. *
  6428. * @param {NodeBuilder} builder - The current node builder.
  6429. * @param {Node} uvNode - The uv node to setup.
  6430. * @return {Node} The updated uv node.
  6431. */
  6432. setupUV( builder, uvNode ) {
  6433. const texture = this.value;
  6434. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6435. if ( this.sampler ) {
  6436. uvNode = uvNode.flipY();
  6437. } else {
  6438. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6439. }
  6440. }
  6441. return uvNode;
  6442. }
  6443. /**
  6444. * Setups texture node by preparing the internal nodes for code generation.
  6445. *
  6446. * @param {NodeBuilder} builder - The current node builder.
  6447. */
  6448. setup( builder ) {
  6449. const properties = builder.getNodeProperties( this );
  6450. properties.referenceNode = this.referenceNode;
  6451. //
  6452. const texture = this.value;
  6453. if ( ! texture || texture.isTexture !== true ) {
  6454. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6455. }
  6456. //
  6457. let uvNode = this.uvNode;
  6458. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6459. uvNode = builder.context.getUV( this );
  6460. }
  6461. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6462. if ( this.updateMatrix === true ) {
  6463. uvNode = this.getTransformedUV( uvNode );
  6464. }
  6465. uvNode = this.setupUV( builder, uvNode );
  6466. //
  6467. let levelNode = this.levelNode;
  6468. if ( levelNode === null && builder.context.getTextureLevel ) {
  6469. levelNode = builder.context.getTextureLevel( this );
  6470. }
  6471. //
  6472. properties.uvNode = uvNode;
  6473. properties.levelNode = levelNode;
  6474. properties.biasNode = this.biasNode;
  6475. properties.compareNode = this.compareNode;
  6476. properties.gradNode = this.gradNode;
  6477. properties.depthNode = this.depthNode;
  6478. }
  6479. /**
  6480. * Generates the uv code snippet.
  6481. *
  6482. * @param {NodeBuilder} builder - The current node builder.
  6483. * @param {Node} uvNode - The uv node to generate code for.
  6484. * @return {String} The generated code snippet.
  6485. */
  6486. generateUV( builder, uvNode ) {
  6487. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6488. }
  6489. /**
  6490. * Generates the snippet for the texture sampling.
  6491. *
  6492. * @param {NodeBuilder} builder - The current node builder.
  6493. * @param {String} textureProperty - The texture property.
  6494. * @param {String} uvSnippet - The uv snippet.
  6495. * @param {String} levelSnippet - The level snippet.
  6496. * @param {String} biasSnippet - The bias snippet.
  6497. * @param {String} depthSnippet - The depth snippet.
  6498. * @param {String} compareSnippet - The compare snippet.
  6499. * @param {String} gradSnippet - The grad snippet.
  6500. * @return {String} The generated code snippet.
  6501. */
  6502. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6503. const texture = this.value;
  6504. let snippet;
  6505. if ( levelSnippet ) {
  6506. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6507. } else if ( biasSnippet ) {
  6508. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6509. } else if ( gradSnippet ) {
  6510. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6511. } else if ( compareSnippet ) {
  6512. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6513. } else if ( this.sampler === false ) {
  6514. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6515. } else {
  6516. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6517. }
  6518. return snippet;
  6519. }
  6520. /**
  6521. * Generates the code snippet of the texture node.
  6522. *
  6523. * @param {NodeBuilder} builder - The current node builder.
  6524. * @param {String} output - The current output.
  6525. * @return {String} The generated code snippet.
  6526. */
  6527. generate( builder, output ) {
  6528. const texture = this.value;
  6529. const properties = builder.getNodeProperties( this );
  6530. const textureProperty = super.generate( builder, 'property' );
  6531. if ( output === 'sampler' ) {
  6532. return textureProperty + '_sampler';
  6533. } else if ( builder.isReference( output ) ) {
  6534. return textureProperty;
  6535. } else {
  6536. const nodeData = builder.getDataFromNode( this );
  6537. let propertyName = nodeData.propertyName;
  6538. if ( propertyName === undefined ) {
  6539. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6540. const uvSnippet = this.generateUV( builder, uvNode );
  6541. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6542. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6543. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6544. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6545. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6546. const nodeVar = builder.getVarFromNode( this );
  6547. propertyName = builder.getPropertyName( nodeVar );
  6548. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  6549. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  6550. nodeData.snippet = snippet;
  6551. nodeData.propertyName = propertyName;
  6552. }
  6553. let snippet = propertyName;
  6554. const nodeType = this.getNodeType( builder );
  6555. if ( builder.needsToWorkingColorSpace( texture ) ) {
  6556. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  6557. }
  6558. return builder.format( snippet, nodeType, output );
  6559. }
  6560. }
  6561. /**
  6562. * Sets the sampler value.
  6563. *
  6564. * @param {Boolean} value - The sampler value to set.
  6565. * @return {TextureNode} A reference to this texture node.
  6566. */
  6567. setSampler( value ) {
  6568. this.sampler = value;
  6569. return this;
  6570. }
  6571. /**
  6572. * Returns the sampler value.
  6573. *
  6574. * @return {Boolean} The sampler value.
  6575. */
  6576. getSampler() {
  6577. return this.sampler;
  6578. }
  6579. // @TODO: Move to TSL
  6580. uv( uvNode ) { // @deprecated, r172
  6581. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  6582. return this.sample( uvNode );
  6583. }
  6584. /**
  6585. * Samples the texture with the given uv node.
  6586. *
  6587. * @param {Node} uvNode - The uv node.
  6588. * @return {TextureNode} A texture node representing the texture sample.
  6589. */
  6590. sample( uvNode ) {
  6591. const textureNode = this.clone();
  6592. textureNode.uvNode = nodeObject( uvNode );
  6593. textureNode.referenceNode = this.getSelf();
  6594. return nodeObject( textureNode );
  6595. }
  6596. /**
  6597. * Samples a blurred version of the texture by defining an internal bias.
  6598. *
  6599. * @param {Node<float>} amountNode - How blurred the texture should be.
  6600. * @return {TextureNode} A texture node representing the texture sample.
  6601. */
  6602. blur( amountNode ) {
  6603. const textureNode = this.clone();
  6604. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  6605. textureNode.referenceNode = this.getSelf();
  6606. return nodeObject( textureNode );
  6607. }
  6608. /**
  6609. * Samples a specific mip of the texture.
  6610. *
  6611. * @param {Node<int>} levelNode - The mip level to sample.
  6612. * @return {TextureNode} A texture node representing the texture sample.
  6613. */
  6614. level( levelNode ) {
  6615. const textureNode = this.clone();
  6616. textureNode.levelNode = nodeObject( levelNode );
  6617. textureNode.referenceNode = this.getSelf();
  6618. return nodeObject( textureNode );
  6619. }
  6620. /**
  6621. * Returns the texture size of the requested level.
  6622. *
  6623. * @param {Node<int>} levelNode - The level to compute the size for.
  6624. * @return {TextureSizeNode} The texture size.
  6625. */
  6626. size( levelNode ) {
  6627. return textureSize( this, levelNode );
  6628. }
  6629. /**
  6630. * Samples the texture with the given bias.
  6631. *
  6632. * @param {Node<float>} biasNode - The bias node.
  6633. * @return {TextureNode} A texture node representing the texture sample.
  6634. */
  6635. bias( biasNode ) {
  6636. const textureNode = this.clone();
  6637. textureNode.biasNode = nodeObject( biasNode );
  6638. textureNode.referenceNode = this.getSelf();
  6639. return nodeObject( textureNode );
  6640. }
  6641. /**
  6642. * Samples the texture by executing a compare operation.
  6643. *
  6644. * @param {Node<float>} compareNode - The node that defines the compare value.
  6645. * @return {TextureNode} A texture node representing the texture sample.
  6646. */
  6647. compare( compareNode ) {
  6648. const textureNode = this.clone();
  6649. textureNode.compareNode = nodeObject( compareNode );
  6650. textureNode.referenceNode = this.getSelf();
  6651. return nodeObject( textureNode );
  6652. }
  6653. /**
  6654. * Samples the texture using an explicit gradient.
  6655. *
  6656. * @param {Node<vec2>} gradNodeX - The gradX node.
  6657. * @param {Node<vec2>} gradNodeY - The gradY node.
  6658. * @return {TextureNode} A texture node representing the texture sample.
  6659. */
  6660. grad( gradNodeX, gradNodeY ) {
  6661. const textureNode = this.clone();
  6662. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  6663. textureNode.referenceNode = this.getSelf();
  6664. return nodeObject( textureNode );
  6665. }
  6666. /**
  6667. * Samples the texture by defining a depth node.
  6668. *
  6669. * @param {Node<int>} depthNode - The depth node.
  6670. * @return {TextureNode} A texture node representing the texture sample.
  6671. */
  6672. depth( depthNode ) {
  6673. const textureNode = this.clone();
  6674. textureNode.depthNode = nodeObject( depthNode );
  6675. textureNode.referenceNode = this.getSelf();
  6676. return nodeObject( textureNode );
  6677. }
  6678. // --
  6679. serialize( data ) {
  6680. super.serialize( data );
  6681. data.value = this.value.toJSON( data.meta ).uuid;
  6682. data.sampler = this.sampler;
  6683. data.updateMatrix = this.updateMatrix;
  6684. data.updateType = this.updateType;
  6685. }
  6686. deserialize( data ) {
  6687. super.deserialize( data );
  6688. this.value = data.meta.textures[ data.value ];
  6689. this.sampler = data.sampler;
  6690. this.updateMatrix = data.updateMatrix;
  6691. this.updateType = data.updateType;
  6692. }
  6693. /**
  6694. * The update is used to implement the update of the uv transformation matrix.
  6695. */
  6696. update() {
  6697. const texture = this.value;
  6698. const matrixUniform = this._matrixUniform;
  6699. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  6700. if ( texture.matrixAutoUpdate === true ) {
  6701. texture.updateMatrix();
  6702. }
  6703. }
  6704. /**
  6705. * Clones the texture node.
  6706. *
  6707. * @return {TextureNode} The cloned texture node.
  6708. */
  6709. clone() {
  6710. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  6711. newNode.sampler = this.sampler;
  6712. return newNode;
  6713. }
  6714. }
  6715. /**
  6716. * TSL function for creating a texture node.
  6717. *
  6718. * @function
  6719. * @param {Texture} value - The texture.
  6720. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6721. * @param {Node<int>?} [levelNode=null] - The level node.
  6722. * @param {Node<float>?} [biasNode=null] - The bias node.
  6723. * @returns {TextureNode}
  6724. */
  6725. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  6726. /**
  6727. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  6728. *
  6729. * @function
  6730. * @param {Texture} value - The texture.
  6731. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6732. * @param {Node<int>?} [levelNode=null] - The level node.
  6733. * @param {Node<float>?} [biasNode=null] - The bias node.
  6734. * @returns {TextureNode}
  6735. */
  6736. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  6737. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  6738. /**
  6739. * Converts a texture or texture node to a sampler.
  6740. *
  6741. * @function
  6742. * @param {TextureNode|Texture} aTexture - The texture or texture node to convert.
  6743. * @returns {Node}
  6744. */
  6745. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  6746. /** @module Camera **/
  6747. /**
  6748. * TSL object that represents the `near` value of the camera used for the current render.
  6749. *
  6750. * @type {UniformNode<float>}
  6751. */
  6752. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  6753. /**
  6754. * TSL object that represents the `far` value of the camera used for the current render.
  6755. *
  6756. * @type {UniformNode<float>}
  6757. */
  6758. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  6759. /**
  6760. * TSL object that represents the projection matrix of the camera used for the current render.
  6761. *
  6762. * @type {UniformNode<mat4>}
  6763. */
  6764. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  6765. /**
  6766. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  6767. *
  6768. * @type {UniformNode<mat4>}
  6769. */
  6770. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  6771. /**
  6772. * TSL object that represents the view matrix of the camera used for the current render.
  6773. *
  6774. * @type {UniformNode<mat4>}
  6775. */
  6776. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  6777. /**
  6778. * TSL object that represents the world matrix of the camera used for the current render.
  6779. *
  6780. * @type {UniformNode<mat4>}
  6781. */
  6782. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  6783. /**
  6784. * TSL object that represents the normal matrix of the camera used for the current render.
  6785. *
  6786. * @type {UniformNode<mat3>}
  6787. */
  6788. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  6789. /**
  6790. * TSL object that represents the position in world space of the camera used for the current render.
  6791. *
  6792. * @type {UniformNode<vec3>}
  6793. */
  6794. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  6795. /** @module Object3DNode **/
  6796. /**
  6797. * This node can be used to access transformation related metrics of 3D objects.
  6798. * Depending on the selected scope, a different metric is represented as a uniform
  6799. * in the shader. The following scopes are supported:
  6800. *
  6801. * - `POSITION`: The object's position in world space.
  6802. * - `VIEW_POSITION`: The object's position in view/camera space.
  6803. * - `DIRECTION`: The object's direction in world space.
  6804. * - `SCALE`: The object's scale in world space.
  6805. * - `WORLD_MATRIX`: The object's matrix in world space.
  6806. *
  6807. * @augments Node
  6808. */
  6809. class Object3DNode extends Node {
  6810. static get type() {
  6811. return 'Object3DNode';
  6812. }
  6813. /**
  6814. * Constructs a new object 3D node.
  6815. *
  6816. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  6817. * @param {Object3D?} [object3d=null] - The 3D object.
  6818. */
  6819. constructor( scope, object3d = null ) {
  6820. super();
  6821. /**
  6822. * The node reports a different type of transformation depending on the scope.
  6823. *
  6824. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  6825. */
  6826. this.scope = scope;
  6827. /**
  6828. * The 3D object.
  6829. *
  6830. * @type {Object3D?}
  6831. * @default null
  6832. */
  6833. this.object3d = object3d;
  6834. /**
  6835. * Overwritten since this type of node is updated per object.
  6836. *
  6837. * @type {String}
  6838. * @default 'object'
  6839. */
  6840. this.updateType = NodeUpdateType.OBJECT;
  6841. /**
  6842. * Holds the value of the node as a uniform.
  6843. *
  6844. * @private
  6845. * @type {UniformNode}
  6846. */
  6847. this._uniformNode = new UniformNode( null );
  6848. }
  6849. /**
  6850. * Overwritten since the node type is inferred from the scope.
  6851. *
  6852. * @param {NodeBuilder} builder - The current node builder.
  6853. * @return {String} The node type.
  6854. */
  6855. getNodeType() {
  6856. const scope = this.scope;
  6857. if ( scope === Object3DNode.WORLD_MATRIX ) {
  6858. return 'mat4';
  6859. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  6860. return 'vec3';
  6861. }
  6862. }
  6863. /**
  6864. * Updates the uniform value depending on the scope.
  6865. *
  6866. * @param {NodeFrame} frame - The current node frame.
  6867. */
  6868. update( frame ) {
  6869. const object = this.object3d;
  6870. const uniformNode = this._uniformNode;
  6871. const scope = this.scope;
  6872. if ( scope === Object3DNode.WORLD_MATRIX ) {
  6873. uniformNode.value = object.matrixWorld;
  6874. } else if ( scope === Object3DNode.POSITION ) {
  6875. uniformNode.value = uniformNode.value || new Vector3();
  6876. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  6877. } else if ( scope === Object3DNode.SCALE ) {
  6878. uniformNode.value = uniformNode.value || new Vector3();
  6879. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  6880. } else if ( scope === Object3DNode.DIRECTION ) {
  6881. uniformNode.value = uniformNode.value || new Vector3();
  6882. object.getWorldDirection( uniformNode.value );
  6883. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  6884. const camera = frame.camera;
  6885. uniformNode.value = uniformNode.value || new Vector3();
  6886. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  6887. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  6888. }
  6889. }
  6890. /**
  6891. * Generates the code snippet of the uniform node. The node type of the uniform
  6892. * node also depends on the selected scope.
  6893. *
  6894. * @param {NodeBuilder} builder - The current node builder.
  6895. * @return {String} The generated code snippet.
  6896. */
  6897. generate( builder ) {
  6898. const scope = this.scope;
  6899. if ( scope === Object3DNode.WORLD_MATRIX ) {
  6900. this._uniformNode.nodeType = 'mat4';
  6901. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  6902. this._uniformNode.nodeType = 'vec3';
  6903. }
  6904. return this._uniformNode.build( builder );
  6905. }
  6906. serialize( data ) {
  6907. super.serialize( data );
  6908. data.scope = this.scope;
  6909. }
  6910. deserialize( data ) {
  6911. super.deserialize( data );
  6912. this.scope = data.scope;
  6913. }
  6914. }
  6915. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  6916. Object3DNode.POSITION = 'position';
  6917. Object3DNode.SCALE = 'scale';
  6918. Object3DNode.VIEW_POSITION = 'viewPosition';
  6919. Object3DNode.DIRECTION = 'direction';
  6920. /**
  6921. * TSL function for creating an object 3D node that represents the object's direction in world space.
  6922. *
  6923. * @function
  6924. * @param {Object3D?} [object3d=null] - The 3D object.
  6925. * @returns {Object3DNode<vec3>}
  6926. */
  6927. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  6928. /**
  6929. * TSL function for creating an object 3D node that represents the object's world matrix.
  6930. *
  6931. * @function
  6932. * @param {Object3D?} [object3d=null] - The 3D object.
  6933. * @returns {Object3DNode<mat4>}
  6934. */
  6935. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  6936. /**
  6937. * TSL function for creating an object 3D node that represents the object's position in world space.
  6938. *
  6939. * @function
  6940. * @param {Object3D?} [object3d=null] - The 3D object.
  6941. * @returns {Object3DNode<vec3>}
  6942. */
  6943. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  6944. /**
  6945. * TSL function for creating an object 3D node that represents the object's scale in world space.
  6946. *
  6947. * @function
  6948. * @param {Object3D?} [object3d=null] - The 3D object.
  6949. * @returns {Object3DNode<vec3>}
  6950. */
  6951. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  6952. /**
  6953. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  6954. *
  6955. * @function
  6956. * @param {Object3D?} [object3d=null] - The 3D object.
  6957. * @returns {Object3DNode<vec3>}
  6958. */
  6959. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  6960. /** @module ModelNode **/
  6961. /**
  6962. * This type of node is a specialized version of `Object3DNode`
  6963. * with larger set of model related metrics. Unlike `Object3DNode`,
  6964. * `ModelNode` extracts the reference to the 3D object from the
  6965. * current node frame state.
  6966. *
  6967. * @augments module:Object3DNode~Object3DNode
  6968. */
  6969. class ModelNode extends Object3DNode {
  6970. static get type() {
  6971. return 'ModelNode';
  6972. }
  6973. /**
  6974. * Constructs a new object model node.
  6975. *
  6976. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  6977. */
  6978. constructor( scope ) {
  6979. super( scope );
  6980. }
  6981. /**
  6982. * Extracts the model reference from the frame state and then
  6983. * updates the uniform value depending on the scope.
  6984. *
  6985. * @param {NodeFrame} frame - The current node frame.
  6986. */
  6987. update( frame ) {
  6988. this.object3d = frame.object;
  6989. super.update( frame );
  6990. }
  6991. }
  6992. /**
  6993. * TSL object that represents the object's direction in world space.
  6994. *
  6995. * @type {ModelNode<vec3>}
  6996. */
  6997. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  6998. /**
  6999. * TSL object that represents the object's world matrix.
  7000. *
  7001. * @type {ModelNode<mat4>}
  7002. */
  7003. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7004. /**
  7005. * TSL object that represents the object's position in world space.
  7006. *
  7007. * @type {ModelNode<vec3>}
  7008. */
  7009. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7010. /**
  7011. * TSL object that represents the object's scale in world space.
  7012. *
  7013. * @type {ModelNode<vec3>}
  7014. */
  7015. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7016. /**
  7017. * TSL object that represents the object's position in view/camera space.
  7018. *
  7019. * @type {ModelNode<vec3>}
  7020. */
  7021. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7022. /**
  7023. * TSL object that represents the object's normal matrix.
  7024. *
  7025. * @type {UniformNode<mat3>}
  7026. */
  7027. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7028. /**
  7029. * TSL object that represents the object's inverse world matrix.
  7030. *
  7031. * @type {UniformNode<mat4>}
  7032. */
  7033. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7034. /**
  7035. * TSL object that represents the object's model view matrix.
  7036. *
  7037. * @type {Node<mat4>}
  7038. */
  7039. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7040. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7041. } ).once() )().toVar( 'modelViewMatrix' );
  7042. // GPU Precision
  7043. /**
  7044. * TSL object that represents the object's model view in `mediump` precision.
  7045. *
  7046. * @type {Node<mat4>}
  7047. */
  7048. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7049. // CPU Precision
  7050. /**
  7051. * TSL object that represents the object's model view in `highp` precision
  7052. * which is achieved by computing the matrix in JS and not in the shader.
  7053. *
  7054. * @type {Node<mat4>}
  7055. */
  7056. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7057. builder.context.isHighPrecisionModelViewMatrix = true;
  7058. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7059. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7060. } );
  7061. } ).once() )().toVar( 'highpModelViewMatrix' );
  7062. /**
  7063. * TSL object that represents the object's model normal view in `highp` precision
  7064. * which is achieved by computing the matrix in JS and not in the shader.
  7065. *
  7066. * @type {Node<mat3>}
  7067. */
  7068. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7069. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7070. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7071. if ( isHighPrecisionModelViewMatrix !== true ) {
  7072. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7073. }
  7074. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7075. } );
  7076. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7077. /** @module Position **/
  7078. /**
  7079. * TSL object that represents the position attribute of the current rendered object.
  7080. *
  7081. * @type {AttributeNode<vec3>}
  7082. */
  7083. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7084. /**
  7085. * TSL object that represents the vertex position in local space of the current rendered object.
  7086. *
  7087. * @type {AttributeNode<vec3>}
  7088. */
  7089. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  7090. /**
  7091. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7092. * Used in context of {@link module:VelocityNode~VelocityNode} for rendering motion vectors.
  7093. *
  7094. * @type {AttributeNode<vec3>}
  7095. */
  7096. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  7097. /**
  7098. * TSL object that represents the vertex position in world space of the current rendered object.
  7099. *
  7100. * @type {VaryingNode<vec3>}
  7101. */
  7102. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7103. /**
  7104. * TSL object that represents the position world direction of the current rendered object.
  7105. *
  7106. * @type {Node<vec3>}
  7107. */
  7108. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  7109. /**
  7110. * TSL object that represents the vertex position in view space of the current rendered object.
  7111. *
  7112. * @type {VaryingNode<vec3>}
  7113. */
  7114. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7115. return builder.context.setupPositionView();
  7116. }, 'vec3' ).once() )().varying( 'v_positionView' ).context( { needsPositionReassign: true } );
  7117. /**
  7118. * TSL object that represents the position view direction of the current rendered object.
  7119. *
  7120. * @type {VaryingNode<vec3>}
  7121. */
  7122. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  7123. /** @module FrontFacingNode **/
  7124. /**
  7125. * This node can be used to evaluate whether a primitive is front or back facing.
  7126. *
  7127. * @augments Node
  7128. */
  7129. class FrontFacingNode extends Node {
  7130. static get type() {
  7131. return 'FrontFacingNode';
  7132. }
  7133. /**
  7134. * Constructs a new front facing node.
  7135. */
  7136. constructor() {
  7137. super( 'bool' );
  7138. /**
  7139. * This flag can be used for type testing.
  7140. *
  7141. * @type {Boolean}
  7142. * @readonly
  7143. * @default true
  7144. */
  7145. this.isFrontFacingNode = true;
  7146. }
  7147. generate( builder ) {
  7148. const { renderer, material } = builder;
  7149. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  7150. if ( material.side === BackSide ) {
  7151. return 'false';
  7152. }
  7153. }
  7154. return builder.getFrontFacing();
  7155. }
  7156. }
  7157. /**
  7158. * TSL object that represents whether a primitive is front or back facing
  7159. *
  7160. * @type {FrontFacingNode<bool>}
  7161. */
  7162. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  7163. /**
  7164. * TSL object that represents the front facing status as a number instead of a bool.
  7165. * `1` means front facing, `-1` means back facing.
  7166. *
  7167. * @type {Node<float>}
  7168. */
  7169. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  7170. /** @module Normal **/
  7171. /**
  7172. * TSL object that represents the normal attribute of the current rendered object.
  7173. *
  7174. * @type {Node<vec3>}
  7175. */
  7176. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  7177. /**
  7178. * TSL object that represents the vertex normal in local space of the current rendered object.
  7179. *
  7180. * @type {Node<vec3>}
  7181. */
  7182. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  7183. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  7184. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  7185. return vec3( 0, 1, 0 );
  7186. }
  7187. return normalGeometry;
  7188. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  7189. /**
  7190. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  7191. *
  7192. * @type {Node<vec3>}
  7193. */
  7194. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  7195. /**
  7196. * TSL object that represents the vertex normal in view space of the current rendered object.
  7197. *
  7198. * @type {Node<vec3>}
  7199. */
  7200. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7201. let node;
  7202. if ( builder.material.flatShading === true ) {
  7203. node = normalFlat;
  7204. } else {
  7205. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  7206. }
  7207. return node;
  7208. }, 'vec3' ).once() )().toVar( 'normalView' );
  7209. /**
  7210. * TSL object that represents the vertex normal in world space of the current rendered object.
  7211. *
  7212. * @type {Node<vec3>}
  7213. */
  7214. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  7215. /**
  7216. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  7217. *
  7218. * @type {Node<vec3>}
  7219. */
  7220. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7221. return builder.context.setupNormal();
  7222. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  7223. /**
  7224. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  7225. *
  7226. * @type {Node<vec3>}
  7227. */
  7228. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  7229. /**
  7230. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  7231. *
  7232. * @type {Node<vec3>}
  7233. */
  7234. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7235. return builder.context.setupClearcoatNormal();
  7236. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  7237. /**
  7238. * Transforms the normal with the given matrix.
  7239. *
  7240. * @function
  7241. * @param {Node<vec3>} normal - The normal.
  7242. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  7243. * @return {Node<vec3>} The transformed normal.
  7244. */
  7245. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  7246. const m = mat3( matrix );
  7247. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  7248. return m.mul( transformedNormal ).xyz;
  7249. } );
  7250. /**
  7251. * Transforms the given normal from local to view space.
  7252. *
  7253. * @function
  7254. * @param {Node<vec3>} normal - The normal.
  7255. * @param {NodeBuilder} builder - The current node builder.
  7256. * @return {Node<vec3>} The transformed normal.
  7257. */
  7258. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  7259. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  7260. if ( modelNormalViewMatrix !== null ) {
  7261. return modelNormalViewMatrix.transformDirection( normal );
  7262. }
  7263. //
  7264. const transformedNormal = modelNormalMatrix.mul( normal );
  7265. return cameraViewMatrix.transformDirection( transformedNormal );
  7266. } );
  7267. /** @module MaterialProperties **/
  7268. /**
  7269. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  7270. *
  7271. * @type {UniformNode<float>}
  7272. */
  7273. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  7274. /** @module ReflectVector **/
  7275. /**
  7276. * The reflect vector in view space.
  7277. *
  7278. * @type {Node<vec3>}
  7279. */
  7280. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  7281. /**
  7282. * The refract vector in view space.
  7283. *
  7284. * @type {Node<vec3>}
  7285. */
  7286. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  7287. /**
  7288. * Used for sampling cube maps when using cube reflection mapping.
  7289. *
  7290. * @type {Node<vec3>}
  7291. */
  7292. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7293. /**
  7294. * Used for sampling cube maps when using cube refraction mapping.
  7295. *
  7296. * @type {Node<vec3>}
  7297. */
  7298. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7299. /** @module CubeTextureNode **/
  7300. /**
  7301. * This type of uniform node represents a cube texture.
  7302. *
  7303. * @augments module:TextureNode~TextureNode
  7304. */
  7305. class CubeTextureNode extends TextureNode {
  7306. static get type() {
  7307. return 'CubeTextureNode';
  7308. }
  7309. /**
  7310. * Constructs a new cube texture node.
  7311. *
  7312. * @param {CubeTexture} value - The cube texture.
  7313. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7314. * @param {Node<int>?} [levelNode=null] - The level node.
  7315. * @param {Node<float>?} [biasNode=null] - The bias node.
  7316. */
  7317. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7318. super( value, uvNode, levelNode, biasNode );
  7319. /**
  7320. * This flag can be used for type testing.
  7321. *
  7322. * @type {Boolean}
  7323. * @readonly
  7324. * @default true
  7325. */
  7326. this.isCubeTextureNode = true;
  7327. }
  7328. /**
  7329. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  7330. *
  7331. * @param {NodeBuilder} builder - The current node builder.
  7332. * @return {String} The input type.
  7333. */
  7334. getInputType( /*builder*/ ) {
  7335. return 'cubeTexture';
  7336. }
  7337. /**
  7338. * Returns a default uvs based on the mapping type of the cube texture.
  7339. *
  7340. * @return {Node<vec3>} The default uv attribute.
  7341. */
  7342. getDefaultUV() {
  7343. const texture = this.value;
  7344. if ( texture.mapping === CubeReflectionMapping ) {
  7345. return reflectVector;
  7346. } else if ( texture.mapping === CubeRefractionMapping ) {
  7347. return refractVector;
  7348. } else {
  7349. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  7350. return vec3( 0, 0, 0 );
  7351. }
  7352. }
  7353. /**
  7354. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  7355. * for cube textures. The uv transformation matrix is not applied to cube textures.
  7356. *
  7357. * @param {Boolean} value - The update toggle.
  7358. */
  7359. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  7360. /**
  7361. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  7362. * to modify the uv node for correct sampling.
  7363. *
  7364. * @param {NodeBuilder} builder - The current node builder.
  7365. * @param {Node} uvNode - The uv node to setup.
  7366. * @return {Node} The updated uv node.
  7367. */
  7368. setupUV( builder, uvNode ) {
  7369. const texture = this.value;
  7370. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  7371. return vec3( uvNode.x.negate(), uvNode.yz );
  7372. } else {
  7373. return uvNode;
  7374. }
  7375. }
  7376. /**
  7377. * Generates the uv code snippet.
  7378. *
  7379. * @param {NodeBuilder} builder - The current node builder.
  7380. * @param {Node} cubeUV - The uv node to generate code for.
  7381. * @return {String} The generated code snippet.
  7382. */
  7383. generateUV( builder, cubeUV ) {
  7384. return cubeUV.build( builder, 'vec3' );
  7385. }
  7386. }
  7387. /**
  7388. * TSL function for creating a cube texture node.
  7389. *
  7390. * @function
  7391. * @param {CubeTexture} value - The cube texture.
  7392. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7393. * @param {Node<int>?} [levelNode=null] - The level node.
  7394. * @param {Node<float>?} [biasNode=null] - The bias node.
  7395. * @returns {CubeTextureNode}
  7396. */
  7397. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  7398. /** @module BufferNode **/
  7399. /**
  7400. * A special type of uniform node which represents array-like data
  7401. * as uniform buffers. The access usually happens via `element()`
  7402. * which returns an instance of {@link ArrayElementNode}. For example:
  7403. *
  7404. * ```js
  7405. * const bufferNode = buffer( array, 'mat4', count );
  7406. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7407. * ```
  7408. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7409. * since it handles more input types and automatically cares about buffer paddings.
  7410. *
  7411. * @augments module:UniformNode~UniformNode
  7412. */
  7413. class BufferNode extends UniformNode {
  7414. static get type() {
  7415. return 'BufferNode';
  7416. }
  7417. /**
  7418. * Constructs a new buffer node.
  7419. *
  7420. * @param {Array<Number>} value - Array-like buffer data.
  7421. * @param {String} bufferType - The data type of the buffer.
  7422. * @param {Number} [bufferCount=0] - The count of buffer elements.
  7423. */
  7424. constructor( value, bufferType, bufferCount = 0 ) {
  7425. super( value, bufferType );
  7426. /**
  7427. * This flag can be used for type testing.
  7428. *
  7429. * @type {Boolean}
  7430. * @readonly
  7431. * @default true
  7432. */
  7433. this.isBufferNode = true;
  7434. /**
  7435. * The data type of the buffer.
  7436. *
  7437. * @type {String}
  7438. */
  7439. this.bufferType = bufferType;
  7440. /**
  7441. * The uniform node that holds the value of the reference node.
  7442. *
  7443. * @type {Number}
  7444. * @default 0
  7445. */
  7446. this.bufferCount = bufferCount;
  7447. }
  7448. /**
  7449. * The data type of the buffer elements.
  7450. *
  7451. * @param {NodeBuilder} builder - The current node builder.
  7452. * @return {String} The element type.
  7453. */
  7454. getElementType( builder ) {
  7455. return this.getNodeType( builder );
  7456. }
  7457. /**
  7458. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7459. *
  7460. * @param {NodeBuilder} builder - The current node builder.
  7461. * @return {String} The input type.
  7462. */
  7463. getInputType( /*builder*/ ) {
  7464. return 'buffer';
  7465. }
  7466. }
  7467. /**
  7468. * TSL function for creating a buffer node.
  7469. *
  7470. * @function
  7471. * @param {Array} value - Array-like buffer data.
  7472. * @param {String} type - The data type of a buffer element.
  7473. * @param {Number} count - The count of buffer elements.
  7474. * @returns {BufferNode}
  7475. */
  7476. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7477. /** @module UniformArrayNode **/
  7478. /**
  7479. * Represents the element access on uniform array nodes.
  7480. *
  7481. * @augments ArrayElementNode
  7482. */
  7483. class UniformArrayElementNode extends ArrayElementNode {
  7484. static get type() {
  7485. return 'UniformArrayElementNode';
  7486. }
  7487. /**
  7488. * Constructs a new buffer node.
  7489. *
  7490. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7491. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7492. */
  7493. constructor( uniformArrayNode, indexNode ) {
  7494. super( uniformArrayNode, indexNode );
  7495. /**
  7496. * This flag can be used for type testing.
  7497. *
  7498. * @type {Boolean}
  7499. * @readonly
  7500. * @default true
  7501. */
  7502. this.isArrayBufferElementNode = true;
  7503. }
  7504. generate( builder ) {
  7505. const snippet = super.generate( builder );
  7506. const type = this.getNodeType();
  7507. const paddedType = this.node.getPaddedType();
  7508. return builder.format( snippet, paddedType, type );
  7509. }
  7510. }
  7511. /**
  7512. * Similar to {@link module:BufferNode~BufferNode} this module represents array-like data as
  7513. * uniform buffers. Unlike {@link module:BufferNode~BufferNode}, it can handle more common
  7514. * data types in the array (e.g `three.js` primitives) and automatically
  7515. * manage buffer padding. It should be the first choice when working with
  7516. * uniforms buffers.
  7517. * ```js
  7518. * const tintColors = uniformArray( [
  7519. * new Color( 1, 0, 0 ),
  7520. * new Color( 0, 1, 0 ),
  7521. * new Color( 0, 0, 1 )
  7522. * ], 'color' );
  7523. *
  7524. * const redColor = tintColors.element( 0 );
  7525. *
  7526. * @augments module:BufferNode~BufferNode
  7527. */
  7528. class UniformArrayNode extends BufferNode {
  7529. static get type() {
  7530. return 'UniformArrayNode';
  7531. }
  7532. /**
  7533. * Constructs a new uniform array node.
  7534. *
  7535. * @param {Array<Any>} value - Array holding the buffer data.
  7536. * @param {String?} [elementType=null] - The data type of a buffer element.
  7537. */
  7538. constructor( value, elementType = null ) {
  7539. super( null );
  7540. /**
  7541. * Array holding the buffer data. Unlike {@link module:BufferNode~BufferNode}, the array can
  7542. * hold number primitives as well as three.js objects like vectors, matrices
  7543. * or colors.
  7544. *
  7545. * @type {Array<Any>}
  7546. */
  7547. this.array = value;
  7548. /**
  7549. * The data type of an array element.
  7550. *
  7551. * @type {String}
  7552. */
  7553. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7554. /**
  7555. * The padded type. Uniform buffers must conform to a certain buffer layout
  7556. * so a separate type is computed to ensure correct buffer size.
  7557. *
  7558. * @type {String}
  7559. */
  7560. this.paddedType = this.getPaddedType();
  7561. /**
  7562. * Overwritten since uniform array nodes are updated per render.
  7563. *
  7564. * @type {String}
  7565. * @default 'render'
  7566. */
  7567. this.updateType = NodeUpdateType.RENDER;
  7568. /**
  7569. * This flag can be used for type testing.
  7570. *
  7571. * @type {Boolean}
  7572. * @readonly
  7573. * @default true
  7574. */
  7575. this.isArrayBufferNode = true;
  7576. }
  7577. /**
  7578. * This method is overwritten since the node type is inferred from the
  7579. * {@link module:UniformArrayNode~UniformArrayNode#paddedType}.
  7580. *
  7581. * @param {NodeBuilder} builder - The current node builder.
  7582. * @return {String} The node type.
  7583. */
  7584. getNodeType( /*builder*/ ) {
  7585. return this.paddedType;
  7586. }
  7587. /**
  7588. * The data type of the array elements.
  7589. *
  7590. * @param {NodeBuilder} builder - The current node builder.
  7591. * @return {String} The element type.
  7592. */
  7593. getElementType() {
  7594. return this.elementType;
  7595. }
  7596. /**
  7597. * Returns the padded type based on the element type.
  7598. *
  7599. * @return {String} The padded type.
  7600. */
  7601. getPaddedType() {
  7602. const elementType = this.elementType;
  7603. let paddedType = 'vec4';
  7604. if ( elementType === 'mat2' ) {
  7605. paddedType = 'mat2';
  7606. } else if ( /mat/.test( elementType ) === true ) {
  7607. paddedType = 'mat4';
  7608. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7609. paddedType = 'ivec4';
  7610. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7611. paddedType = 'uvec4';
  7612. }
  7613. return paddedType;
  7614. }
  7615. /**
  7616. * The update makes sure to correctly transfer the data from the (complex) objects
  7617. * in the array to the internal, correctly padded value buffer.
  7618. *
  7619. * @param {NodeFrame} frame - A reference to the current node frame.
  7620. */
  7621. update( /*frame*/ ) {
  7622. const { array, value } = this;
  7623. const elementType = this.elementType;
  7624. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7625. for ( let i = 0; i < array.length; i ++ ) {
  7626. const index = i * 4;
  7627. value[ index ] = array[ i ];
  7628. }
  7629. } else if ( elementType === 'color' ) {
  7630. for ( let i = 0; i < array.length; i ++ ) {
  7631. const index = i * 4;
  7632. const vector = array[ i ];
  7633. value[ index ] = vector.r;
  7634. value[ index + 1 ] = vector.g;
  7635. value[ index + 2 ] = vector.b || 0;
  7636. //value[ index + 3 ] = vector.a || 0;
  7637. }
  7638. } else if ( elementType === 'mat2' ) {
  7639. for ( let i = 0; i < array.length; i ++ ) {
  7640. const index = i * 4;
  7641. const matrix = array[ i ];
  7642. value[ index ] = matrix.elements[ 0 ];
  7643. value[ index + 1 ] = matrix.elements[ 1 ];
  7644. value[ index + 2 ] = matrix.elements[ 2 ];
  7645. value[ index + 3 ] = matrix.elements[ 3 ];
  7646. }
  7647. } else if ( elementType === 'mat3' ) {
  7648. for ( let i = 0; i < array.length; i ++ ) {
  7649. const index = i * 16;
  7650. const matrix = array[ i ];
  7651. value[ index ] = matrix.elements[ 0 ];
  7652. value[ index + 1 ] = matrix.elements[ 1 ];
  7653. value[ index + 2 ] = matrix.elements[ 2 ];
  7654. value[ index + 4 ] = matrix.elements[ 3 ];
  7655. value[ index + 5 ] = matrix.elements[ 4 ];
  7656. value[ index + 6 ] = matrix.elements[ 5 ];
  7657. value[ index + 8 ] = matrix.elements[ 6 ];
  7658. value[ index + 9 ] = matrix.elements[ 7 ];
  7659. value[ index + 10 ] = matrix.elements[ 8 ];
  7660. value[ index + 15 ] = 1;
  7661. }
  7662. } else if ( elementType === 'mat4' ) {
  7663. for ( let i = 0; i < array.length; i ++ ) {
  7664. const index = i * 16;
  7665. const matrix = array[ i ];
  7666. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7667. value[ index + i ] = matrix.elements[ i ];
  7668. }
  7669. }
  7670. } else {
  7671. for ( let i = 0; i < array.length; i ++ ) {
  7672. const index = i * 4;
  7673. const vector = array[ i ];
  7674. value[ index ] = vector.x;
  7675. value[ index + 1 ] = vector.y;
  7676. value[ index + 2 ] = vector.z || 0;
  7677. value[ index + 3 ] = vector.w || 0;
  7678. }
  7679. }
  7680. }
  7681. /**
  7682. * Implement the value buffer creation based on the array data.
  7683. *
  7684. * @param {NodeBuilder} builder - A reference to the current node builder.
  7685. * @return {null}
  7686. */
  7687. setup( builder ) {
  7688. const length = this.array.length;
  7689. const elementType = this.elementType;
  7690. let arrayType = Float32Array;
  7691. const paddedType = this.paddedType;
  7692. const paddedElementLength = builder.getTypeLength( paddedType );
  7693. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7694. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7695. this.value = new arrayType( length * paddedElementLength );
  7696. this.bufferCount = length;
  7697. this.bufferType = paddedType;
  7698. return super.setup( builder );
  7699. }
  7700. /**
  7701. * Overwrites the default `element()` method to provide element access
  7702. * based on {@link module:UniformArrayNode~UniformArrayNode}.
  7703. *
  7704. * @param {IndexNode} indexNode - The index node.
  7705. * @return {UniformArrayElementNode}
  7706. */
  7707. element( indexNode ) {
  7708. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7709. }
  7710. }
  7711. /**
  7712. * TSL function for creating an uniform array node.
  7713. *
  7714. * @function
  7715. * @param {Array<Any>} values - Array-like data.
  7716. * @param {String} nodeType - The data type of the array elements.
  7717. * @returns {UniformArrayNode}
  7718. */
  7719. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7720. //
  7721. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7722. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7723. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7724. };
  7725. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  7726. /** @module ReferenceNode **/
  7727. /**
  7728. * This class is only relevant if the referenced property is array-like.
  7729. * In this case, `ReferenceElementNode` allows to refer to a specific
  7730. * element inside the data structure via an index.
  7731. *
  7732. * @augments ArrayElementNode
  7733. */
  7734. class ReferenceElementNode extends ArrayElementNode {
  7735. static get type() {
  7736. return 'ReferenceElementNode';
  7737. }
  7738. /**
  7739. * Constructs a new reference element node.
  7740. *
  7741. * @param {Node?} referenceNode - The reference node.
  7742. * @param {Node} indexNode - The index node that defines the element access.
  7743. */
  7744. constructor( referenceNode, indexNode ) {
  7745. super( referenceNode, indexNode );
  7746. /**
  7747. * Similar to {@link module:ReferenceNode~ReferenceNode#reference}, an additional
  7748. * property references to the current node.
  7749. *
  7750. * @type {Node?}
  7751. * @default null
  7752. */
  7753. this.referenceNode = referenceNode;
  7754. /**
  7755. * This flag can be used for type testing.
  7756. *
  7757. * @type {Boolean}
  7758. * @readonly
  7759. * @default true
  7760. */
  7761. this.isReferenceElementNode = true;
  7762. }
  7763. /**
  7764. * This method is overwritten since the node type is inferred from
  7765. * the uniform type of the reference node.
  7766. *
  7767. * @param {NodeBuilder} builder - The current node builder.
  7768. * @return {String} The node type.
  7769. */
  7770. getNodeType() {
  7771. return this.referenceNode.uniformType;
  7772. }
  7773. generate( builder ) {
  7774. const snippet = super.generate( builder );
  7775. const arrayType = this.referenceNode.getNodeType();
  7776. const elementType = this.getNodeType();
  7777. return builder.format( snippet, arrayType, elementType );
  7778. }
  7779. }
  7780. /**
  7781. * This type of node establishes a reference to a property of another object.
  7782. * In this way, the value of the node is automatically linked to the value of
  7783. * referenced object. Reference nodes internally represent the linked value
  7784. * as a uniform.
  7785. *
  7786. * @augments Node
  7787. */
  7788. class ReferenceNode extends Node {
  7789. static get type() {
  7790. return 'ReferenceNode';
  7791. }
  7792. /**
  7793. * Constructs a new reference node.
  7794. *
  7795. * @param {String} property - The name of the property the node refers to.
  7796. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  7797. * @param {Object?} [object=null] - The object the property belongs to.
  7798. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  7799. */
  7800. constructor( property, uniformType, object = null, count = null ) {
  7801. super();
  7802. /**
  7803. * The name of the property the node refers to.
  7804. *
  7805. * @type {String}
  7806. */
  7807. this.property = property;
  7808. /**
  7809. * The uniform type that should be used to represent the property value.
  7810. *
  7811. * @type {String}
  7812. */
  7813. this.uniformType = uniformType;
  7814. /**
  7815. * The object the property belongs to.
  7816. *
  7817. * @type {Object?}
  7818. * @default null
  7819. */
  7820. this.object = object;
  7821. /**
  7822. * When the linked property is an array, this parameter defines its length.
  7823. *
  7824. * @type {Number?}
  7825. * @default null
  7826. */
  7827. this.count = count;
  7828. /**
  7829. * The property name might have dots so nested properties can be referred.
  7830. * The hierarchy of the names is stored inside this array.
  7831. *
  7832. * @type {Array<String>}
  7833. */
  7834. this.properties = property.split( '.' );
  7835. /**
  7836. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  7837. * since the final reference might be updated from calling code.
  7838. *
  7839. * @type {Object?}
  7840. * @default null
  7841. */
  7842. this.reference = object;
  7843. /**
  7844. * The uniform node that holds the value of the reference node.
  7845. *
  7846. * @type {UniformNode}
  7847. * @default null
  7848. */
  7849. this.node = null;
  7850. /**
  7851. * The uniform group of the internal uniform.
  7852. *
  7853. * @type {UniformGroupNode}
  7854. * @default null
  7855. */
  7856. this.group = null;
  7857. /**
  7858. * An optional label of the internal uniform node.
  7859. *
  7860. * @type {String?}
  7861. * @default null
  7862. */
  7863. this.name = null;
  7864. /**
  7865. * Overwritten since reference nodes are updated per object.
  7866. *
  7867. * @type {String}
  7868. * @default 'object'
  7869. */
  7870. this.updateType = NodeUpdateType.OBJECT;
  7871. }
  7872. /**
  7873. * When the referred property is array-like, this method can be used
  7874. * to access elements via an index node.
  7875. *
  7876. * @param {IndexNode} indexNode - indexNode.
  7877. * @return {ReferenceElementNode} A reference to an element.
  7878. */
  7879. element( indexNode ) {
  7880. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  7881. }
  7882. /**
  7883. * Sets the uniform group for this reference node.
  7884. *
  7885. * @param {UniformGroupNode} group - The uniform group to set.
  7886. * @return {ReferenceNode} A reference to this node.
  7887. */
  7888. setGroup( group ) {
  7889. this.group = group;
  7890. return this;
  7891. }
  7892. /**
  7893. * Sets the label for the internal uniform.
  7894. *
  7895. * @param {String} name - The label to set.
  7896. * @return {ReferenceNode} A reference to this node.
  7897. */
  7898. label( name ) {
  7899. this.name = name;
  7900. return this;
  7901. }
  7902. /**
  7903. * Sets the node type which automatically defines the internal
  7904. * uniform type.
  7905. *
  7906. * @param {String} uniformType - The type to set.
  7907. */
  7908. setNodeType( uniformType ) {
  7909. let node = null;
  7910. if ( this.count !== null ) {
  7911. node = buffer( null, uniformType, this.count );
  7912. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  7913. node = uniformArray( null, uniformType );
  7914. } else if ( uniformType === 'texture' ) {
  7915. node = texture( null );
  7916. } else if ( uniformType === 'cubeTexture' ) {
  7917. node = cubeTexture( null );
  7918. } else {
  7919. node = uniform( null, uniformType );
  7920. }
  7921. if ( this.group !== null ) {
  7922. node.setGroup( this.group );
  7923. }
  7924. if ( this.name !== null ) node.label( this.name );
  7925. this.node = node.getSelf();
  7926. }
  7927. /**
  7928. * This method is overwritten since the node type is inferred from
  7929. * the type of the reference node.
  7930. *
  7931. * @param {NodeBuilder} builder - The current node builder.
  7932. * @return {String} The node type.
  7933. */
  7934. getNodeType( builder ) {
  7935. if ( this.node === null ) {
  7936. this.updateReference( builder );
  7937. this.updateValue();
  7938. }
  7939. return this.node.getNodeType( builder );
  7940. }
  7941. /**
  7942. * Returns the property value from the given referred object.
  7943. *
  7944. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  7945. * @return {Any} The value.
  7946. */
  7947. getValueFromReference( object = this.reference ) {
  7948. const { properties } = this;
  7949. let value = object[ properties[ 0 ] ];
  7950. for ( let i = 1; i < properties.length; i ++ ) {
  7951. value = value[ properties[ i ] ];
  7952. }
  7953. return value;
  7954. }
  7955. /**
  7956. * Allows to update the reference based on the given state. The state is only
  7957. * evaluated {@link module:ReferenceNode~ReferenceNode#object} is not set.
  7958. *
  7959. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  7960. * @return {Object} The updated reference.
  7961. */
  7962. updateReference( state ) {
  7963. this.reference = this.object !== null ? this.object : state.object;
  7964. return this.reference;
  7965. }
  7966. /**
  7967. * The output of the reference node is the internal uniform node.
  7968. *
  7969. * @param {NodeBuilder} builder - The current node builder.
  7970. * @return {UniformNode} The output node.
  7971. */
  7972. setup( /* builder */ ) {
  7973. this.updateValue();
  7974. return this.node;
  7975. }
  7976. /**
  7977. * Overwritten to to update the internal uniform value.
  7978. *
  7979. * @param {NodeFrame} frame - A reference to the current node frame.
  7980. */
  7981. update( /*frame*/ ) {
  7982. this.updateValue();
  7983. }
  7984. /**
  7985. * Retrieves the value from the referred object property and uses it
  7986. * to updated the internal uniform.
  7987. */
  7988. updateValue() {
  7989. if ( this.node === null ) this.setNodeType( this.uniformType );
  7990. const value = this.getValueFromReference();
  7991. if ( Array.isArray( value ) ) {
  7992. this.node.array = value;
  7993. } else {
  7994. this.node.value = value;
  7995. }
  7996. }
  7997. }
  7998. /**
  7999. * TSL function for creating a reference node.
  8000. *
  8001. * @function
  8002. * @param {String} name - The name of the property the node refers to.
  8003. * @param {String} type - The uniform type that should be used to represent the property value.
  8004. * @param {Object} object - The object the property belongs to.
  8005. * @returns {ReferenceNode}
  8006. */
  8007. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8008. /**
  8009. * TSL function for creating a reference node. Use this function if you want need a reference
  8010. * to an array-like property that should be represented as a uniform buffer.
  8011. *
  8012. * @function
  8013. * @param {String} name - The name of the property the node refers to.
  8014. * @param {String} type - The uniform type that should be used to represent the property value.
  8015. * @param {Number} count - The number of value inside the array-like object.
  8016. * @param {Object} object - An array-like object the property belongs to.
  8017. * @returns {ReferenceNode}
  8018. */
  8019. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8020. /** @module MaterialReferenceNode **/
  8021. /**
  8022. * This node is a special type of reference node which is intended
  8023. * for linking material properties with node values.
  8024. * ```js
  8025. * const opacityNode = materialReference( 'opacity', 'float', material );
  8026. * ```
  8027. * When changing `material.opacity`, the node value of `opacityNode` will
  8028. * automatically be updated.
  8029. *
  8030. * @augments module:ReferenceNode~ReferenceNode
  8031. */
  8032. class MaterialReferenceNode extends ReferenceNode {
  8033. static get type() {
  8034. return 'MaterialReferenceNode';
  8035. }
  8036. /**
  8037. * Constructs a new material reference node.
  8038. *
  8039. * @param {String} property - The name of the property the node refers to.
  8040. * @param {String} inputType - The uniform type that should be used to represent the property value.
  8041. * @param {Material?} [material=null] - The material the property belongs to. When no material is set,
  8042. * the node refers to the material of the current rendered object.
  8043. */
  8044. constructor( property, inputType, material = null ) {
  8045. super( property, inputType, material );
  8046. /**
  8047. * The material the property belongs to. When no material is set,
  8048. * the node refers to the material of the current rendered object.
  8049. *
  8050. * @type {Material?}
  8051. * @default null
  8052. */
  8053. this.material = material;
  8054. /**
  8055. * This flag can be used for type testing.
  8056. *
  8057. * @type {Boolean}
  8058. * @readonly
  8059. * @default true
  8060. */
  8061. this.isMaterialReferenceNode = true;
  8062. }
  8063. /**
  8064. * Updates the reference based on the given state. The state is only evaluated
  8065. * {@link module:MaterialReferenceNode~MaterialReferenceNode#material} is not set.
  8066. *
  8067. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8068. * @return {Object} The updated reference.
  8069. */
  8070. updateReference( state ) {
  8071. this.reference = this.material !== null ? this.material : state.material;
  8072. return this.reference;
  8073. }
  8074. }
  8075. /**
  8076. * TSL function for creating a material reference node.
  8077. *
  8078. * @function
  8079. * @param {String} name - The name of the property the node refers to.
  8080. * @param {String} type - The uniform type that should be used to represent the property value.
  8081. * @param {Material?} [material=null] - The material the property belongs to.
  8082. * When no material is set, the node refers to the material of the current rendered object.
  8083. * @returns {MaterialReferenceNode}
  8084. */
  8085. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8086. /** @module Tangent **/
  8087. /**
  8088. * TSL object that represents the tangent attribute of the current rendered object.
  8089. *
  8090. * @type {Node<vec4>}
  8091. */
  8092. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8093. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8094. builder.geometry.computeTangents();
  8095. }
  8096. return attribute( 'tangent', 'vec4' );
  8097. } )();
  8098. /**
  8099. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8100. *
  8101. * @type {Node<vec3>}
  8102. */
  8103. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8104. /**
  8105. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8106. *
  8107. * @type {Node<vec3>}
  8108. */
  8109. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8110. /**
  8111. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8112. *
  8113. * @type {Node<vec3>}
  8114. */
  8115. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8116. /**
  8117. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8118. *
  8119. * @type {Node<vec3>}
  8120. */
  8121. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8122. /**
  8123. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8124. *
  8125. * @type {Node<vec3>}
  8126. */
  8127. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8128. /** @module Bitangent **/
  8129. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8130. /**
  8131. * TSL object that represents the bitangent attribute of the current rendered object.
  8132. *
  8133. * @type {Node<vec3>}
  8134. */
  8135. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8136. /**
  8137. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8138. *
  8139. * @type {Node<vec3>}
  8140. */
  8141. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8142. /**
  8143. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8144. *
  8145. * @type {Node<vec4>}
  8146. */
  8147. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8148. /**
  8149. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8150. *
  8151. * @type {Node<vec4>}
  8152. */
  8153. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8154. /**
  8155. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8156. *
  8157. * @type {Node<vec4>}
  8158. */
  8159. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8160. /**
  8161. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8162. *
  8163. * @type {Node<vec4>}
  8164. */
  8165. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8166. /** @module AccessorsUtils **/
  8167. /**
  8168. * TSL object that represents the TBN matrix in view space.
  8169. *
  8170. * @type {Node<mat3>}
  8171. */
  8172. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8173. /**
  8174. * TSL object that represents the parallax direction.
  8175. *
  8176. * @type {Node<mat3>}
  8177. */
  8178. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8179. /**
  8180. * TSL function for computing parallax uv coordinates.
  8181. *
  8182. * @function
  8183. * @param {Node<vec2>} uv - A uv node.
  8184. * @param {Node<vec2>} scale - A scale node.
  8185. * @returns {Node<vec2>} Parallax uv coordinates.
  8186. */
  8187. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8188. /**
  8189. * TSL function for computing bent normals.
  8190. *
  8191. * @function
  8192. * @returns {Node<vec3>} Bent normals.
  8193. */
  8194. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8195. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8196. let bentNormal = anisotropyB.cross( positionViewDirection );
  8197. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8198. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8199. return bentNormal;
  8200. } )();
  8201. /** @module NormalMapNode **/
  8202. // Normal Mapping Without Precomputed Tangents
  8203. // http://www.thetenthplanet.de/archives/1180
  8204. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8205. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8206. const q0 = eye_pos.dFdx();
  8207. const q1 = eye_pos.dFdy();
  8208. const st0 = uv.dFdx();
  8209. const st1 = uv.dFdy();
  8210. const N = surf_norm; // normalized
  8211. const q1perp = q1.cross( N );
  8212. const q0perp = N.cross( q0 );
  8213. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8214. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8215. const det = T.dot( T ).max( B.dot( B ) );
  8216. const scale = faceDirection.mul( det.inverseSqrt() );
  8217. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8218. } );
  8219. /**
  8220. * This class can be used for applying normals maps to materials.
  8221. *
  8222. * ```js
  8223. * material.normalNode = normalMap( texture( normalTex ) );
  8224. * ```
  8225. *
  8226. * @augments TempNode
  8227. */
  8228. class NormalMapNode extends TempNode {
  8229. static get type() {
  8230. return 'NormalMapNode';
  8231. }
  8232. /**
  8233. * Constructs a new normal map node.
  8234. *
  8235. * @param {Node} node - Represents the normal map data.
  8236. * @param {Node?} [scaleNode=null] - Controls the intensity of the effect.
  8237. */
  8238. constructor( node, scaleNode = null ) {
  8239. super( 'vec3' );
  8240. /**
  8241. * Represents the normal map data.
  8242. *
  8243. * @type {Node}
  8244. */
  8245. this.node = node;
  8246. /**
  8247. * Controls the intensity of the effect.
  8248. *
  8249. * @type {Node?}
  8250. * @default null
  8251. */
  8252. this.scaleNode = scaleNode;
  8253. /**
  8254. * The normal map type.
  8255. *
  8256. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8257. * @default TangentSpaceNormalMap
  8258. */
  8259. this.normalMapType = TangentSpaceNormalMap;
  8260. }
  8261. setup( builder ) {
  8262. const { normalMapType, scaleNode } = this;
  8263. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8264. if ( scaleNode !== null ) {
  8265. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8266. }
  8267. let outputNode = null;
  8268. if ( normalMapType === ObjectSpaceNormalMap ) {
  8269. outputNode = transformNormalToView( normalMap );
  8270. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8271. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8272. if ( tangent === true ) {
  8273. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8274. } else {
  8275. outputNode = perturbNormal2Arb( {
  8276. eye_pos: positionView,
  8277. surf_norm: normalView,
  8278. mapN: normalMap,
  8279. uv: uv()
  8280. } );
  8281. }
  8282. }
  8283. return outputNode;
  8284. }
  8285. }
  8286. /**
  8287. * TSL function for creating a normal map node.
  8288. *
  8289. * @function
  8290. * @param {Node} node - Represents the normal map data.
  8291. * @param {Node?} [scaleNode=null] - Controls the intensity of the effect.
  8292. * @returns {NormalMapNode}
  8293. */
  8294. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8295. /** @module BumpMapNode **/
  8296. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8297. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8298. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8299. // It's used to preserve the same TextureNode instance
  8300. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8301. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8302. return vec2(
  8303. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8304. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8305. ).mul( bumpScale );
  8306. } );
  8307. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8308. const perturbNormalArb = Fn( ( inputs ) => {
  8309. const { surf_pos, surf_norm, dHdxy } = inputs;
  8310. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8311. const vSigmaX = surf_pos.dFdx().normalize();
  8312. const vSigmaY = surf_pos.dFdy().normalize();
  8313. const vN = surf_norm; // normalized
  8314. const R1 = vSigmaY.cross( vN );
  8315. const R2 = vN.cross( vSigmaX );
  8316. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8317. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8318. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8319. } );
  8320. /**
  8321. * This class can be used for applying bump maps to materials.
  8322. *
  8323. * ```js
  8324. * material.normalNode = bumpMap( texture( bumpTex ) );
  8325. * ```
  8326. *
  8327. * @augments TempNode
  8328. */
  8329. class BumpMapNode extends TempNode {
  8330. static get type() {
  8331. return 'BumpMapNode';
  8332. }
  8333. /**
  8334. * Constructs a new bump map node.
  8335. *
  8336. * @param {Node} textureNode - Represents the bump map data.
  8337. * @param {Node?} [scaleNode=null] - Controls the intensity of the bump effect.
  8338. */
  8339. constructor( textureNode, scaleNode = null ) {
  8340. super( 'vec3' );
  8341. /**
  8342. * Represents the bump map data.
  8343. *
  8344. * @type {Node}
  8345. */
  8346. this.textureNode = textureNode;
  8347. /**
  8348. * Controls the intensity of the bump effect.
  8349. *
  8350. * @type {Node?}
  8351. * @default null
  8352. */
  8353. this.scaleNode = scaleNode;
  8354. }
  8355. setup() {
  8356. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8357. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8358. return perturbNormalArb( {
  8359. surf_pos: positionView,
  8360. surf_norm: normalView,
  8361. dHdxy
  8362. } );
  8363. }
  8364. }
  8365. /**
  8366. * TSL function for creating a bump map node.
  8367. *
  8368. * @function
  8369. * @param {Node} textureNode - Represents the bump map data.
  8370. * @param {Node?} [scaleNode=null] - Controls the intensity of the bump effect.
  8371. * @returns {BumpMapNode}
  8372. */
  8373. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8374. /** @module MaterialNode **/
  8375. const _propertyCache = new Map();
  8376. /**
  8377. * This class should simplify the node access to material properties.
  8378. * It internal uses reference nodes to make sure changes to material
  8379. * properties are automatically reflected to predefined TSL objects
  8380. * like e.g. `materialColor`.
  8381. *
  8382. * @augments Node
  8383. */
  8384. class MaterialNode extends Node {
  8385. static get type() {
  8386. return 'MaterialNode';
  8387. }
  8388. /**
  8389. * Constructs a new material node.
  8390. *
  8391. * @param {String} scope - The scope defines what kind of material property is referred by the node.
  8392. */
  8393. constructor( scope ) {
  8394. super();
  8395. /**
  8396. * The scope defines what material property is referred by the node.
  8397. *
  8398. * @type {String}
  8399. */
  8400. this.scope = scope;
  8401. }
  8402. /**
  8403. * Returns a cached reference node for the given property and type.
  8404. *
  8405. * @param {String} property - The name of the material property.
  8406. * @param {String} type - The uniform type of the property.
  8407. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8408. */
  8409. getCache( property, type ) {
  8410. let node = _propertyCache.get( property );
  8411. if ( node === undefined ) {
  8412. node = materialReference( property, type );
  8413. _propertyCache.set( property, node );
  8414. }
  8415. return node;
  8416. }
  8417. /**
  8418. * Returns a float-typed material reference node for the given property name.
  8419. *
  8420. * @param {String} property - The name of the material property.
  8421. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8422. */
  8423. getFloat( property ) {
  8424. return this.getCache( property, 'float' );
  8425. }
  8426. /**
  8427. * Returns a color-typed material reference node for the given property name.
  8428. *
  8429. * @param {String} property - The name of the material property.
  8430. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8431. */
  8432. getColor( property ) {
  8433. return this.getCache( property, 'color' );
  8434. }
  8435. /**
  8436. * Returns a texture-typed material reference node for the given property name.
  8437. *
  8438. * @param {String} property - The name of the material property.
  8439. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8440. */
  8441. getTexture( property ) {
  8442. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8443. }
  8444. /**
  8445. * The node setup is done depending on the selected scope. Multiple material properties
  8446. * might be grouped into a single node composition if they logically belong together.
  8447. *
  8448. * @param {NodeBuilder} builder - The current node builder.
  8449. * @return {Node} The node representing the selected scope.
  8450. */
  8451. setup( builder ) {
  8452. const material = builder.context.material;
  8453. const scope = this.scope;
  8454. let node = null;
  8455. if ( scope === MaterialNode.COLOR ) {
  8456. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8457. if ( material.map && material.map.isTexture === true ) {
  8458. node = colorNode.mul( this.getTexture( 'map' ) );
  8459. } else {
  8460. node = colorNode;
  8461. }
  8462. } else if ( scope === MaterialNode.OPACITY ) {
  8463. const opacityNode = this.getFloat( scope );
  8464. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  8465. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  8466. } else {
  8467. node = opacityNode;
  8468. }
  8469. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  8470. if ( material.specularMap && material.specularMap.isTexture === true ) {
  8471. node = this.getTexture( 'specular' ).r;
  8472. } else {
  8473. node = float( 1 );
  8474. }
  8475. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  8476. const specularIntensityNode = this.getFloat( scope );
  8477. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  8478. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  8479. } else {
  8480. node = specularIntensityNode;
  8481. }
  8482. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  8483. const specularColorNode = this.getColor( scope );
  8484. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  8485. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  8486. } else {
  8487. node = specularColorNode;
  8488. }
  8489. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  8490. const roughnessNode = this.getFloat( scope );
  8491. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  8492. node = roughnessNode.mul( this.getTexture( scope ).g );
  8493. } else {
  8494. node = roughnessNode;
  8495. }
  8496. } else if ( scope === MaterialNode.METALNESS ) {
  8497. const metalnessNode = this.getFloat( scope );
  8498. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  8499. node = metalnessNode.mul( this.getTexture( scope ).b );
  8500. } else {
  8501. node = metalnessNode;
  8502. }
  8503. } else if ( scope === MaterialNode.EMISSIVE ) {
  8504. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  8505. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  8506. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  8507. node = emissiveNode.mul( this.getTexture( scope ) );
  8508. } else {
  8509. node = emissiveNode;
  8510. }
  8511. } else if ( scope === MaterialNode.NORMAL ) {
  8512. if ( material.normalMap ) {
  8513. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  8514. node.normalMapType = material.normalMapType;
  8515. } else if ( material.bumpMap ) {
  8516. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  8517. } else {
  8518. node = normalView;
  8519. }
  8520. } else if ( scope === MaterialNode.CLEARCOAT ) {
  8521. const clearcoatNode = this.getFloat( scope );
  8522. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  8523. node = clearcoatNode.mul( this.getTexture( scope ).r );
  8524. } else {
  8525. node = clearcoatNode;
  8526. }
  8527. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  8528. const clearcoatRoughnessNode = this.getFloat( scope );
  8529. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  8530. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  8531. } else {
  8532. node = clearcoatRoughnessNode;
  8533. }
  8534. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  8535. if ( material.clearcoatNormalMap ) {
  8536. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  8537. } else {
  8538. node = normalView;
  8539. }
  8540. } else if ( scope === MaterialNode.SHEEN ) {
  8541. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  8542. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  8543. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  8544. } else {
  8545. node = sheenNode;
  8546. }
  8547. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  8548. const sheenRoughnessNode = this.getFloat( scope );
  8549. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  8550. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  8551. } else {
  8552. node = sheenRoughnessNode;
  8553. }
  8554. node = node.clamp( 0.07, 1.0 );
  8555. } else if ( scope === MaterialNode.ANISOTROPY ) {
  8556. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  8557. const anisotropyPolar = this.getTexture( scope );
  8558. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  8559. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  8560. } else {
  8561. node = materialAnisotropyVector;
  8562. }
  8563. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  8564. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  8565. if ( material.iridescenceThicknessMap ) {
  8566. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  8567. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  8568. } else {
  8569. node = iridescenceThicknessMaximum;
  8570. }
  8571. } else if ( scope === MaterialNode.TRANSMISSION ) {
  8572. const transmissionNode = this.getFloat( scope );
  8573. if ( material.transmissionMap ) {
  8574. node = transmissionNode.mul( this.getTexture( scope ).r );
  8575. } else {
  8576. node = transmissionNode;
  8577. }
  8578. } else if ( scope === MaterialNode.THICKNESS ) {
  8579. const thicknessNode = this.getFloat( scope );
  8580. if ( material.thicknessMap ) {
  8581. node = thicknessNode.mul( this.getTexture( scope ).g );
  8582. } else {
  8583. node = thicknessNode;
  8584. }
  8585. } else if ( scope === MaterialNode.IOR ) {
  8586. node = this.getFloat( scope );
  8587. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  8588. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  8589. } else if ( scope === MaterialNode.AO ) {
  8590. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  8591. } else {
  8592. const outputType = this.getNodeType( builder );
  8593. node = this.getCache( scope, outputType );
  8594. }
  8595. return node;
  8596. }
  8597. }
  8598. MaterialNode.ALPHA_TEST = 'alphaTest';
  8599. MaterialNode.COLOR = 'color';
  8600. MaterialNode.OPACITY = 'opacity';
  8601. MaterialNode.SHININESS = 'shininess';
  8602. MaterialNode.SPECULAR = 'specular';
  8603. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  8604. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  8605. MaterialNode.SPECULAR_COLOR = 'specularColor';
  8606. MaterialNode.REFLECTIVITY = 'reflectivity';
  8607. MaterialNode.ROUGHNESS = 'roughness';
  8608. MaterialNode.METALNESS = 'metalness';
  8609. MaterialNode.NORMAL = 'normal';
  8610. MaterialNode.CLEARCOAT = 'clearcoat';
  8611. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  8612. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  8613. MaterialNode.EMISSIVE = 'emissive';
  8614. MaterialNode.ROTATION = 'rotation';
  8615. MaterialNode.SHEEN = 'sheen';
  8616. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  8617. MaterialNode.ANISOTROPY = 'anisotropy';
  8618. MaterialNode.IRIDESCENCE = 'iridescence';
  8619. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  8620. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  8621. MaterialNode.IOR = 'ior';
  8622. MaterialNode.TRANSMISSION = 'transmission';
  8623. MaterialNode.THICKNESS = 'thickness';
  8624. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  8625. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  8626. MaterialNode.LINE_SCALE = 'scale';
  8627. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  8628. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  8629. MaterialNode.LINE_WIDTH = 'linewidth';
  8630. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  8631. MaterialNode.POINT_WIDTH = 'pointWidth';
  8632. MaterialNode.DISPERSION = 'dispersion';
  8633. MaterialNode.LIGHT_MAP = 'light';
  8634. MaterialNode.AO = 'ao';
  8635. /**
  8636. * TSL object that represents alpha test of the current material.
  8637. *
  8638. * @type {Node<float>}
  8639. */
  8640. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  8641. /**
  8642. * TSL object that represents the diffuse color of the current material.
  8643. * The value is composed via `color` * `map`.
  8644. *
  8645. * @type {Node<vec3>}
  8646. */
  8647. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  8648. /**
  8649. * TSL object that represents the shininess of the current material.
  8650. *
  8651. * @type {Node<float>}
  8652. */
  8653. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  8654. /**
  8655. * TSL object that represents the emissive color of the current material.
  8656. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  8657. *
  8658. * @type {Node<vec3>}
  8659. */
  8660. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  8661. /**
  8662. * TSL object that represents the opacity of the current material.
  8663. * The value is composed via `opacity` * `alphaMap`.
  8664. *
  8665. * @type {Node<float>}
  8666. */
  8667. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  8668. /**
  8669. * TSL object that represents the specular of the current material.
  8670. *
  8671. * @type {Node<vec3>}
  8672. */
  8673. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  8674. /**
  8675. * TSL object that represents the specular intensity of the current material.
  8676. * The value is composed via `specularIntensity` * `specularMap.a`.
  8677. *
  8678. * @type {Node<float>}
  8679. */
  8680. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  8681. /**
  8682. * TSL object that represents the specular color of the current material.
  8683. * The value is composed via `specularColor` * `specularMap.rgb`.
  8684. *
  8685. * @type {Node<vec3>}
  8686. */
  8687. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  8688. /**
  8689. * TSL object that represents the specular strength of the current material.
  8690. * The value is composed via `specularMap.r`.
  8691. *
  8692. * @type {Node<float>}
  8693. */
  8694. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  8695. /**
  8696. * TSL object that represents the reflectivity of the current material.
  8697. *
  8698. * @type {Node<float>}
  8699. */
  8700. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  8701. /**
  8702. * TSL object that represents the roughness of the current material.
  8703. * The value is composed via `roughness` * `roughnessMap.g`
  8704. *
  8705. * @type {Node<float>}
  8706. */
  8707. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  8708. /**
  8709. * TSL object that represents the metalness of the current material.
  8710. * The value is composed via `metalness` * `metalnessMap.b`
  8711. *
  8712. * @type {Node<float>}
  8713. */
  8714. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  8715. /**
  8716. * TSL object that represents the normal of the current material.
  8717. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  8718. *
  8719. * @type {Node<vec3>}
  8720. */
  8721. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  8722. /**
  8723. * TSL object that represents the clearcoat of the current material.
  8724. * The value is composed via `clearcoat` * `clearcoatMap.r`
  8725. *
  8726. * @type {Node<float>}
  8727. */
  8728. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  8729. /**
  8730. * TSL object that represents the clearcoat roughness of the current material.
  8731. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`
  8732. *
  8733. * @type {Node<float>}
  8734. */
  8735. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  8736. /**
  8737. * TSL object that represents the clearcoat normal of the current material.
  8738. * The value will be either `clearcoatNormalMap` or `normalView`.
  8739. *
  8740. * @type {Node<vec3>}
  8741. */
  8742. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  8743. /**
  8744. * TSL object that represents the rotation of the current sprite material.
  8745. *
  8746. * @type {Node<float>}
  8747. */
  8748. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  8749. /**
  8750. * TSL object that represents the sheen color of the current material.
  8751. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  8752. *
  8753. * @type {Node<vec3>}
  8754. */
  8755. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  8756. /**
  8757. * TSL object that represents the sheen roughness of the current material.
  8758. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a` .
  8759. *
  8760. * @type {Node<float>}
  8761. */
  8762. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  8763. /**
  8764. * TSL object that represents the anisotropy of the current material.
  8765. *
  8766. * @type {Node<vec2>}
  8767. */
  8768. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  8769. /**
  8770. * TSL object that represents the iridescence of the current material.
  8771. *
  8772. * @type {Node<float>}
  8773. */
  8774. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  8775. /**
  8776. * TSL object that represents the iridescence IOR of the current material.
  8777. *
  8778. * @type {Node<float>}
  8779. */
  8780. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  8781. /**
  8782. * TSL object that represents the iridescence thickness of the current material.
  8783. *
  8784. * @type {Node<float>}
  8785. */
  8786. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  8787. /**
  8788. * TSL object that represents the transmission of the current material.
  8789. * The value is composed via `transmission` * `transmissionMap.r`.
  8790. *
  8791. * @type {Node<float>}
  8792. */
  8793. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  8794. /**
  8795. * TSL object that represents the thickness of the current material.
  8796. * The value is composed via `thickness` * `thicknessMap.g`.
  8797. *
  8798. * @type {Node<float>}
  8799. */
  8800. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  8801. /**
  8802. * TSL object that represents the IOR of the current material.
  8803. *
  8804. * @type {Node<float>}
  8805. */
  8806. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  8807. /**
  8808. * TSL object that represents the attenuation distance of the current material.
  8809. *
  8810. * @type {Node<float>}
  8811. */
  8812. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  8813. /**
  8814. * TSL object that represents the attenuation color of the current material.
  8815. *
  8816. * @type {Node<vec3>}
  8817. */
  8818. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  8819. /**
  8820. * TSL object that represents the scale of the current dashed line material.
  8821. *
  8822. * @type {Node<float>}
  8823. */
  8824. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  8825. /**
  8826. * TSL object that represents the dash size of the current dashed line material.
  8827. *
  8828. * @type {Node<float>}
  8829. */
  8830. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  8831. /**
  8832. * TSL object that represents the gap size of the current dashed line material.
  8833. *
  8834. * @type {Node<float>}
  8835. */
  8836. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  8837. /**
  8838. * TSL object that represents the line width of the current line material.
  8839. *
  8840. * @type {Node<float>}
  8841. */
  8842. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  8843. /**
  8844. * TSL object that represents the dash offset of the current line material.
  8845. *
  8846. * @type {Node<float>}
  8847. */
  8848. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  8849. /**
  8850. * TSL object that represents the point width of the current points material.
  8851. *
  8852. * @type {Node<float>}
  8853. */
  8854. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  8855. /**
  8856. * TSL object that represents the dispersion of the current material.
  8857. *
  8858. * @type {Node<float>}
  8859. */
  8860. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  8861. /**
  8862. * TSL object that represents the light map of the current material.
  8863. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  8864. *
  8865. * @type {Node<vec3>}
  8866. */
  8867. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  8868. /**
  8869. * TSL object that represents the ambient occlusion map of the current material.
  8870. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  8871. *
  8872. * @type {Node<float>}
  8873. */
  8874. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  8875. /**
  8876. * TSL object that represents the anisotropy vector of the current material.
  8877. *
  8878. * @type {Node<vec2>}
  8879. */
  8880. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  8881. return frame.material;
  8882. } ).onRenderUpdate( function ( { material } ) {
  8883. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  8884. } );
  8885. /** @module ModelViewProjectionNode **/
  8886. /**
  8887. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  8888. *
  8889. * @type {VaryingNode<vec4>}
  8890. */
  8891. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  8892. return builder.context.setupModelViewProjection();
  8893. }, 'vec4' ).once() )().varying( 'v_modelViewProjection' );
  8894. /** @module IndexNode **/
  8895. /**
  8896. * This class represents shader indices of different types. The following predefined node
  8897. * objects cover frequent use cases:
  8898. *
  8899. * - `vertexIndex`: The index of a vertex within a mesh.
  8900. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  8901. * - `drawIndex`: The index of a draw call.
  8902. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  8903. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  8904. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  8905. *
  8906. * @augments Node
  8907. */
  8908. class IndexNode extends Node {
  8909. static get type() {
  8910. return 'IndexNode';
  8911. }
  8912. /**
  8913. * Constructs a new index node.
  8914. *
  8915. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  8916. */
  8917. constructor( scope ) {
  8918. super( 'uint' );
  8919. /**
  8920. * The scope of the index node.
  8921. *
  8922. * @type {String}
  8923. */
  8924. this.scope = scope;
  8925. /**
  8926. * This flag can be used for type testing.
  8927. *
  8928. * @type {Boolean}
  8929. * @readonly
  8930. * @default true
  8931. */
  8932. this.isIndexNode = true;
  8933. }
  8934. generate( builder ) {
  8935. const nodeType = this.getNodeType( builder );
  8936. const scope = this.scope;
  8937. let propertyName;
  8938. if ( scope === IndexNode.VERTEX ) {
  8939. propertyName = builder.getVertexIndex();
  8940. } else if ( scope === IndexNode.INSTANCE ) {
  8941. propertyName = builder.getInstanceIndex();
  8942. } else if ( scope === IndexNode.DRAW ) {
  8943. propertyName = builder.getDrawIndex();
  8944. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  8945. propertyName = builder.getInvocationLocalIndex();
  8946. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  8947. propertyName = builder.getInvocationSubgroupIndex();
  8948. } else if ( scope === IndexNode.SUBGROUP ) {
  8949. propertyName = builder.getSubgroupIndex();
  8950. } else {
  8951. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  8952. }
  8953. let output;
  8954. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  8955. output = propertyName;
  8956. } else {
  8957. const nodeVarying = varying( this );
  8958. output = nodeVarying.build( builder, nodeType );
  8959. }
  8960. return output;
  8961. }
  8962. }
  8963. IndexNode.VERTEX = 'vertex';
  8964. IndexNode.INSTANCE = 'instance';
  8965. IndexNode.SUBGROUP = 'subgroup';
  8966. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  8967. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  8968. IndexNode.DRAW = 'draw';
  8969. /**
  8970. * TSL object that represents the index of a vertex within a mesh.
  8971. *
  8972. * @type {IndexNode}
  8973. */
  8974. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  8975. /**
  8976. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  8977. *
  8978. * @type {IndexNode}
  8979. */
  8980. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  8981. /**
  8982. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  8983. *
  8984. * @type {IndexNode}
  8985. */
  8986. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  8987. /**
  8988. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  8989. *
  8990. * @type {IndexNode}
  8991. */
  8992. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  8993. /**
  8994. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  8995. *
  8996. * @type {IndexNode}
  8997. */
  8998. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  8999. /**
  9000. * TSL object that represents the index of a draw call.
  9001. *
  9002. * @type {IndexNode}
  9003. */
  9004. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9005. /** @module InstanceNode **/
  9006. /**
  9007. * This node implements the vertex shader logic which is required
  9008. * when rendering 3D objects via instancing. The code makes sure
  9009. * vertex positions, normals and colors can be modified via instanced
  9010. * data.
  9011. *
  9012. * @augments Node
  9013. */
  9014. class InstanceNode extends Node {
  9015. static get type() {
  9016. return 'InstanceNode';
  9017. }
  9018. /**
  9019. * Constructs a new instance node.
  9020. *
  9021. * @param {Number} count - The number of instances.
  9022. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9023. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9024. */
  9025. constructor( count, instanceMatrix, instanceColor ) {
  9026. super( 'void' );
  9027. /**
  9028. * The number of instances.
  9029. *
  9030. * @type {Number}
  9031. */
  9032. this.count = count;
  9033. /**
  9034. * Instanced buffer attribute representing the transformation of instances.
  9035. *
  9036. * @type {InstancedBufferAttribute}
  9037. */
  9038. this.instanceMatrix = instanceMatrix;
  9039. /**
  9040. * Instanced buffer attribute representing the color of instances.
  9041. *
  9042. * @type {InstancedBufferAttribute}
  9043. */
  9044. this.instanceColor = instanceColor;
  9045. /**
  9046. * The node that represents the instance matrix data.
  9047. *
  9048. * @type {Node}
  9049. */
  9050. this.instanceMatrixNode = null;
  9051. /**
  9052. * The node that represents the instance color data.
  9053. *
  9054. * @type {Node}
  9055. */
  9056. this.instanceColorNode = null;
  9057. /**
  9058. * The update type is set to `frame` since an update
  9059. * of instanced buffer data must be checked per frame.
  9060. *
  9061. * @type {String}
  9062. * @default 'frame'
  9063. */
  9064. this.updateType = NodeUpdateType.FRAME;
  9065. /**
  9066. * A reference to a buffer that is used by `instanceMatrixNode`.
  9067. *
  9068. * @type {InstancedInterleavedBuffer}
  9069. */
  9070. this.buffer = null;
  9071. /**
  9072. * A reference to a buffer that is used by `instanceColorNode`.
  9073. *
  9074. * @type {InstancedInterleavedBuffer}
  9075. */
  9076. this.bufferColor = null;
  9077. }
  9078. /**
  9079. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9080. * to predefined node variables for accumulation. That follows the same patterns
  9081. * like with morph and skinning nodes.
  9082. *
  9083. * @param {NodeBuilder} builder - The current node builder.
  9084. */
  9085. setup( builder ) {
  9086. const { count, instanceMatrix, instanceColor } = this;
  9087. let { instanceMatrixNode, instanceColorNode } = this;
  9088. if ( instanceMatrixNode === null ) {
  9089. // Both WebGPU and WebGL backends have UBO max limited to 64kb. Matrix count number bigger than 1000 ( 16 * 4 * 1000 = 64kb ) will fallback to attribute.
  9090. if ( count <= 1000 ) {
  9091. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9092. } else {
  9093. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9094. this.buffer = buffer;
  9095. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9096. const instanceBuffers = [
  9097. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9098. bufferFn( buffer, 'vec4', 16, 0 ),
  9099. bufferFn( buffer, 'vec4', 16, 4 ),
  9100. bufferFn( buffer, 'vec4', 16, 8 ),
  9101. bufferFn( buffer, 'vec4', 16, 12 )
  9102. ];
  9103. instanceMatrixNode = mat4( ...instanceBuffers );
  9104. }
  9105. this.instanceMatrixNode = instanceMatrixNode;
  9106. }
  9107. if ( instanceColor && instanceColorNode === null ) {
  9108. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9109. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9110. this.bufferColor = buffer;
  9111. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9112. this.instanceColorNode = instanceColorNode;
  9113. }
  9114. // POSITION
  9115. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9116. positionLocal.assign( instancePosition );
  9117. // NORMAL
  9118. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9119. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9120. // ASSIGNS
  9121. normalLocal.assign( instanceNormal );
  9122. }
  9123. // COLOR
  9124. if ( this.instanceColorNode !== null ) {
  9125. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9126. }
  9127. }
  9128. /**
  9129. * Checks if the internal buffers required an update.
  9130. *
  9131. * @param {NodeFrame} frame - The current node frame.
  9132. */
  9133. update( /*frame*/ ) {
  9134. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9135. this.buffer.version = this.instanceMatrix.version;
  9136. }
  9137. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9138. this.bufferColor.version = this.instanceColor.version;
  9139. }
  9140. }
  9141. }
  9142. /**
  9143. * TSL function for creating an instance node.
  9144. *
  9145. * @function
  9146. * @param {Number} count - The number of instances.
  9147. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9148. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9149. * @returns {InstanceNode}
  9150. */
  9151. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9152. /** @module InstancedMeshNode **/
  9153. /**
  9154. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9155. * It allows an easier setup of the instance node.
  9156. *
  9157. * @augments module:InstanceNode~InstanceNode
  9158. */
  9159. class InstancedMeshNode extends InstanceNode {
  9160. static get type() {
  9161. return 'InstancedMeshNode';
  9162. }
  9163. /**
  9164. * Constructs a new instanced mesh node.
  9165. *
  9166. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9167. */
  9168. constructor( instancedMesh ) {
  9169. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9170. super( count, instanceMatrix, instanceColor );
  9171. /**
  9172. * A reference to the instanced mesh.
  9173. *
  9174. * @type {InstancedMesh}
  9175. */
  9176. this.instancedMesh = instancedMesh;
  9177. }
  9178. }
  9179. /**
  9180. * TSL function for creating an instanced mesh node.
  9181. *
  9182. * @function
  9183. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9184. * @returns {InstancedMeshNode}
  9185. */
  9186. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9187. /** @module BatchNode **/
  9188. /**
  9189. * This node implements the vertex shader logic which is required
  9190. * when rendering 3D objects via batching. `BatchNode` must be used
  9191. * with instances of {@link BatchedMesh}.
  9192. *
  9193. * @augments Node
  9194. */
  9195. class BatchNode extends Node {
  9196. static get type() {
  9197. return 'BatchNode';
  9198. }
  9199. /**
  9200. * Constructs a new batch node.
  9201. *
  9202. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9203. */
  9204. constructor( batchMesh ) {
  9205. super( 'void' );
  9206. /**
  9207. * A reference to batched mesh.
  9208. *
  9209. * @type {BatchedMesh}
  9210. */
  9211. this.batchMesh = batchMesh;
  9212. /**
  9213. * The batching index node.
  9214. *
  9215. * @type {IndexNode?}
  9216. * @default null
  9217. */
  9218. this.batchingIdNode = null;
  9219. }
  9220. /**
  9221. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9222. * to predefined node variables for accumulation. That follows the same patterns
  9223. * like with morph and skinning nodes.
  9224. *
  9225. * @param {NodeBuilder} builder - The current node builder.
  9226. */
  9227. setup( builder ) {
  9228. if ( this.batchingIdNode === null ) {
  9229. if ( builder.getDrawIndex() === null ) {
  9230. this.batchingIdNode = instanceIndex;
  9231. } else {
  9232. this.batchingIdNode = drawIndex;
  9233. }
  9234. }
  9235. const getIndirectIndex = Fn( ( [ id ] ) => {
  9236. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  9237. const x = int( id ).modInt( int( size ) );
  9238. const y = int( id ).div( int( size ) );
  9239. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9240. } ).setLayout( {
  9241. name: 'getIndirectIndex',
  9242. type: 'uint',
  9243. inputs: [
  9244. { name: 'id', type: 'int' }
  9245. ]
  9246. } );
  9247. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9248. const matricesTexture = this.batchMesh._matricesTexture;
  9249. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9250. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9251. const x = j.modInt( size );
  9252. const y = j.div( int( size ) );
  9253. const batchingMatrix = mat4(
  9254. textureLoad( matricesTexture, ivec2( x, y ) ),
  9255. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9256. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9257. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9258. );
  9259. const colorsTexture = this.batchMesh._colorsTexture;
  9260. if ( colorsTexture !== null ) {
  9261. const getBatchingColor = Fn( ( [ id ] ) => {
  9262. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9263. const j = id;
  9264. const x = j.modInt( size );
  9265. const y = j.div( size );
  9266. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9267. } ).setLayout( {
  9268. name: 'getBatchingColor',
  9269. type: 'vec3',
  9270. inputs: [
  9271. { name: 'id', type: 'int' }
  9272. ]
  9273. } );
  9274. const color = getBatchingColor( indirectId );
  9275. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9276. }
  9277. const bm = mat3( batchingMatrix );
  9278. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9279. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9280. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9281. normalLocal.assign( batchingNormal );
  9282. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9283. tangentLocal.mulAssign( bm );
  9284. }
  9285. }
  9286. }
  9287. /**
  9288. * TSL function for creating a batch node.
  9289. *
  9290. * @function
  9291. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9292. * @returns {BatchNode}
  9293. */
  9294. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9295. /** @module SkinningNode **/
  9296. const _frameId = new WeakMap();
  9297. /**
  9298. * This node implements the vertex transformation shader logic which is required
  9299. * for skinning/skeletal animation.
  9300. *
  9301. * @augments Node
  9302. */
  9303. class SkinningNode extends Node {
  9304. static get type() {
  9305. return 'SkinningNode';
  9306. }
  9307. /**
  9308. * Constructs a new skinning node.
  9309. *
  9310. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9311. * @param {Boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9312. */
  9313. constructor( skinnedMesh, useReference = false ) {
  9314. super( 'void' );
  9315. /**
  9316. * The skinned mesh.
  9317. *
  9318. * @type {SkinnedMesh}
  9319. */
  9320. this.skinnedMesh = skinnedMesh;
  9321. /**
  9322. * Whether to use reference nodes for internal skinned mesh related data or not.
  9323. * TODO: Explain the purpose of the property.
  9324. *
  9325. * @type {Boolean}
  9326. */
  9327. this.useReference = useReference;
  9328. /**
  9329. * The update type overwritten since skinning nodes are updated per object.
  9330. *
  9331. * @type {String}
  9332. */
  9333. this.updateType = NodeUpdateType.OBJECT;
  9334. //
  9335. /**
  9336. * The skin index attribute.
  9337. *
  9338. * @type {AttributeNode}
  9339. */
  9340. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9341. /**
  9342. * The skin weight attribute.
  9343. *
  9344. * @type {AttributeNode}
  9345. */
  9346. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9347. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9348. if ( useReference ) {
  9349. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9350. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9351. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9352. } else {
  9353. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9354. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9355. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9356. }
  9357. /**
  9358. * The bind matrix node.
  9359. *
  9360. * @type {Node<mat4>}
  9361. */
  9362. this.bindMatrixNode = bindMatrixNode;
  9363. /**
  9364. * The bind matrix inverse node.
  9365. *
  9366. * @type {Node<mat4>}
  9367. */
  9368. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9369. /**
  9370. * The bind matrices as a uniform buffer node.
  9371. *
  9372. * @type {Node}
  9373. */
  9374. this.boneMatricesNode = boneMatricesNode;
  9375. /**
  9376. * The previous bind matrices as a uniform buffer node.
  9377. * Required for computing motion vectors.
  9378. *
  9379. * @type {Node?}
  9380. * @default null
  9381. */
  9382. this.previousBoneMatricesNode = null;
  9383. }
  9384. /**
  9385. * Transforms the given vertex position via skinning.
  9386. *
  9387. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9388. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9389. * @return {Node<vec3>} The transformed vertex position.
  9390. */
  9391. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9392. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9393. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9394. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9395. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9396. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9397. // POSITION
  9398. const skinVertex = bindMatrixNode.mul( position );
  9399. const skinned = add(
  9400. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9401. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9402. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9403. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9404. );
  9405. return bindMatrixInverseNode.mul( skinned ).xyz;
  9406. }
  9407. /**
  9408. * Transforms the given vertex normal via skinning.
  9409. *
  9410. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9411. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9412. * @return {Node<vec3>} The transformed vertex normal.
  9413. */
  9414. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9415. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9416. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9417. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9418. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9419. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9420. // NORMAL
  9421. let skinMatrix = add(
  9422. skinWeightNode.x.mul( boneMatX ),
  9423. skinWeightNode.y.mul( boneMatY ),
  9424. skinWeightNode.z.mul( boneMatZ ),
  9425. skinWeightNode.w.mul( boneMatW )
  9426. );
  9427. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  9428. return skinMatrix.transformDirection( normal ).xyz;
  9429. }
  9430. /**
  9431. * Transforms the given vertex normal via skinning.
  9432. *
  9433. * @param {NodeBuilder} builder - The current node builder.
  9434. * @return {Node<vec3>} The skinned position from the previous frame.
  9435. */
  9436. getPreviousSkinnedPosition( builder ) {
  9437. const skinnedMesh = builder.object;
  9438. if ( this.previousBoneMatricesNode === null ) {
  9439. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  9440. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9441. }
  9442. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  9443. }
  9444. /**
  9445. * Returns `true` if bone matrices from the previous frame are required.
  9446. *
  9447. * @param {NodeBuilder} builder - The current node builder.
  9448. * @return {Boolean} Whether bone matrices from the previous frame are required or not.
  9449. */
  9450. needsPreviousBoneMatrices( builder ) {
  9451. const mrt = builder.renderer.getMRT();
  9452. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  9453. }
  9454. /**
  9455. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  9456. *
  9457. * @param {NodeBuilder} builder - The current node builder.
  9458. */
  9459. setup( builder ) {
  9460. if ( this.needsPreviousBoneMatrices( builder ) ) {
  9461. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  9462. }
  9463. const skinPosition = this.getSkinnedPosition();
  9464. positionLocal.assign( skinPosition );
  9465. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9466. const skinNormal = this.getSkinnedNormal();
  9467. normalLocal.assign( skinNormal );
  9468. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9469. tangentLocal.assign( skinNormal );
  9470. }
  9471. }
  9472. }
  9473. /**
  9474. * Generates the code snippet of the skinning node.
  9475. *
  9476. * @param {NodeBuilder} builder - The current node builder.
  9477. * @param {String} output - The current output.
  9478. * @return {String} The generated code snippet.
  9479. */
  9480. generate( builder, output ) {
  9481. if ( output !== 'void' ) {
  9482. return positionLocal.build( builder, output );
  9483. }
  9484. }
  9485. /**
  9486. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  9487. *
  9488. * @param {NodeFrame} frame - The current node frame.
  9489. */
  9490. update( frame ) {
  9491. const object = this.useReference ? frame.object : this.skinnedMesh;
  9492. const skeleton = object.skeleton;
  9493. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  9494. _frameId.set( skeleton, frame.frameId );
  9495. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  9496. skeleton.update();
  9497. }
  9498. }
  9499. /**
  9500. * TSL function for creating a skinning node.
  9501. *
  9502. * @function
  9503. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9504. * @returns {SkinningNode}
  9505. */
  9506. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  9507. /**
  9508. * TSL function for creating a skinning node with reference usage.
  9509. *
  9510. * @function
  9511. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9512. * @returns {SkinningNode}
  9513. */
  9514. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  9515. /** @module LoopNode **/
  9516. /**
  9517. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  9518. * ```js
  9519. * Loop( count, ( { i } ) => {
  9520. *
  9521. * } );
  9522. * ```
  9523. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  9524. * ```js
  9525. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  9526. *
  9527. * } );
  9528. *```
  9529. * Nested loops can be defined in a compacted form:
  9530. * ```js
  9531. * Loop( 10, 5, ( { i, j } ) => {
  9532. *
  9533. * } );
  9534. * ```
  9535. * Loops that should run backwards can be defined like so:
  9536. * ```js
  9537. * Loop( { start: 10 }, () => {} );
  9538. * ```
  9539. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  9540. * @augments Node
  9541. */
  9542. class LoopNode extends Node {
  9543. static get type() {
  9544. return 'LoopNode';
  9545. }
  9546. /**
  9547. * Constructs a new loop node.
  9548. *
  9549. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  9550. */
  9551. constructor( params = [] ) {
  9552. super();
  9553. this.params = params;
  9554. }
  9555. /**
  9556. * Returns a loop variable name based on an index. The pattern is
  9557. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  9558. *
  9559. * @param {Number} index - The index.
  9560. * @return {String} The loop variable name.
  9561. */
  9562. getVarName( index ) {
  9563. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  9564. }
  9565. /**
  9566. * Returns properties about this node.
  9567. *
  9568. * @param {NodeBuilder} builder - The current node builder.
  9569. * @return {Object} The node properties.
  9570. */
  9571. getProperties( builder ) {
  9572. const properties = builder.getNodeProperties( this );
  9573. if ( properties.stackNode !== undefined ) return properties;
  9574. //
  9575. const inputs = {};
  9576. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9577. const param = this.params[ i ];
  9578. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  9579. const type = ( param.isNode !== true && param.type ) || 'int';
  9580. inputs[ name ] = expression( name, type );
  9581. }
  9582. const stack = builder.addStack(); // TODO: cache() it
  9583. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  9584. properties.stackNode = stack;
  9585. builder.removeStack();
  9586. return properties;
  9587. }
  9588. /**
  9589. * This method is overwritten since the node type is inferred based on the loop configuration.
  9590. *
  9591. * @param {NodeBuilder} builder - The current node builder.
  9592. * @return {String} The node type.
  9593. */
  9594. getNodeType( builder ) {
  9595. const { returnsNode } = this.getProperties( builder );
  9596. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  9597. }
  9598. setup( builder ) {
  9599. // setup properties
  9600. this.getProperties( builder );
  9601. }
  9602. generate( builder ) {
  9603. const properties = this.getProperties( builder );
  9604. const params = this.params;
  9605. const stackNode = properties.stackNode;
  9606. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  9607. const param = params[ i ];
  9608. let start = null, end = null, name = null, type = null, condition = null, update = null;
  9609. if ( param.isNode ) {
  9610. type = 'int';
  9611. name = this.getVarName( i );
  9612. start = '0';
  9613. end = param.build( builder, type );
  9614. condition = '<';
  9615. } else {
  9616. type = param.type || 'int';
  9617. name = param.name || this.getVarName( i );
  9618. start = param.start;
  9619. end = param.end;
  9620. condition = param.condition;
  9621. update = param.update;
  9622. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  9623. else if ( start && start.isNode ) start = start.build( builder, type );
  9624. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  9625. else if ( end && end.isNode ) end = end.build( builder, type );
  9626. if ( start !== undefined && end === undefined ) {
  9627. start = start + ' - 1';
  9628. end = '0';
  9629. condition = '>=';
  9630. } else if ( end !== undefined && start === undefined ) {
  9631. start = '0';
  9632. condition = '<';
  9633. }
  9634. if ( condition === undefined ) {
  9635. if ( Number( start ) > Number( end ) ) {
  9636. condition = '>=';
  9637. } else {
  9638. condition = '<';
  9639. }
  9640. }
  9641. }
  9642. const internalParam = { start, end, condition };
  9643. //
  9644. const startSnippet = internalParam.start;
  9645. const endSnippet = internalParam.end;
  9646. let declarationSnippet = '';
  9647. let conditionalSnippet = '';
  9648. let updateSnippet = '';
  9649. if ( ! update ) {
  9650. if ( type === 'int' || type === 'uint' ) {
  9651. if ( condition.includes( '<' ) ) update = '++';
  9652. else update = '--';
  9653. } else {
  9654. if ( condition.includes( '<' ) ) update = '+= 1.';
  9655. else update = '-= 1.';
  9656. }
  9657. }
  9658. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  9659. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  9660. updateSnippet += name + ' ' + update;
  9661. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  9662. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  9663. }
  9664. const stackSnippet = stackNode.build( builder, 'void' );
  9665. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  9666. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  9667. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9668. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  9669. }
  9670. builder.addFlowTab();
  9671. return returnsSnippet;
  9672. }
  9673. }
  9674. /**
  9675. * TSL function for creating a loop node.
  9676. *
  9677. * @function
  9678. * @param {...Any} params - A list of parameters.
  9679. * @returns {LoopNode}
  9680. */
  9681. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  9682. /**
  9683. * TSL function for creating a `Continue()` expression.
  9684. *
  9685. * @function
  9686. * @returns {ExpressionNode}
  9687. */
  9688. const Continue = () => expression( 'continue' ).append();
  9689. /**
  9690. * TSL function for creating a `Break()` expression.
  9691. *
  9692. * @function
  9693. * @returns {ExpressionNode}
  9694. */
  9695. const Break = () => expression( 'break' ).append();
  9696. //
  9697. const loop = ( ...params ) => { // @deprecated, r168
  9698. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  9699. return Loop( ...params );
  9700. };
  9701. /** @module MorphNode **/
  9702. const _morphTextures = /*@__PURE__*/ new WeakMap();
  9703. const _morphVec4 = /*@__PURE__*/ new Vector4();
  9704. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  9705. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  9706. const y = texelIndex.div( width );
  9707. const x = texelIndex.sub( y.mul( width ) );
  9708. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  9709. return bufferAttrib.mul( influence );
  9710. } );
  9711. function getEntry( geometry ) {
  9712. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9713. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  9714. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  9715. // instead of using attributes, the WebGL 2 code path encodes morph targets
  9716. // into an array of data textures. Each layer represents a single morph target.
  9717. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9718. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9719. let entry = _morphTextures.get( geometry );
  9720. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  9721. if ( entry !== undefined ) entry.texture.dispose();
  9722. const morphTargets = geometry.morphAttributes.position || [];
  9723. const morphNormals = geometry.morphAttributes.normal || [];
  9724. const morphColors = geometry.morphAttributes.color || [];
  9725. let vertexDataCount = 0;
  9726. if ( hasMorphPosition === true ) vertexDataCount = 1;
  9727. if ( hasMorphNormals === true ) vertexDataCount = 2;
  9728. if ( hasMorphColors === true ) vertexDataCount = 3;
  9729. let width = geometry.attributes.position.count * vertexDataCount;
  9730. let height = 1;
  9731. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  9732. if ( width > maxTextureSize ) {
  9733. height = Math.ceil( width / maxTextureSize );
  9734. width = maxTextureSize;
  9735. }
  9736. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  9737. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  9738. bufferTexture.type = FloatType;
  9739. bufferTexture.needsUpdate = true;
  9740. // fill buffer
  9741. const vertexDataStride = vertexDataCount * 4;
  9742. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  9743. const morphTarget = morphTargets[ i ];
  9744. const morphNormal = morphNormals[ i ];
  9745. const morphColor = morphColors[ i ];
  9746. const offset = width * height * 4 * i;
  9747. for ( let j = 0; j < morphTarget.count; j ++ ) {
  9748. const stride = j * vertexDataStride;
  9749. if ( hasMorphPosition === true ) {
  9750. _morphVec4.fromBufferAttribute( morphTarget, j );
  9751. buffer[ offset + stride + 0 ] = _morphVec4.x;
  9752. buffer[ offset + stride + 1 ] = _morphVec4.y;
  9753. buffer[ offset + stride + 2 ] = _morphVec4.z;
  9754. buffer[ offset + stride + 3 ] = 0;
  9755. }
  9756. if ( hasMorphNormals === true ) {
  9757. _morphVec4.fromBufferAttribute( morphNormal, j );
  9758. buffer[ offset + stride + 4 ] = _morphVec4.x;
  9759. buffer[ offset + stride + 5 ] = _morphVec4.y;
  9760. buffer[ offset + stride + 6 ] = _morphVec4.z;
  9761. buffer[ offset + stride + 7 ] = 0;
  9762. }
  9763. if ( hasMorphColors === true ) {
  9764. _morphVec4.fromBufferAttribute( morphColor, j );
  9765. buffer[ offset + stride + 8 ] = _morphVec4.x;
  9766. buffer[ offset + stride + 9 ] = _morphVec4.y;
  9767. buffer[ offset + stride + 10 ] = _morphVec4.z;
  9768. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  9769. }
  9770. }
  9771. }
  9772. entry = {
  9773. count: morphTargetsCount,
  9774. texture: bufferTexture,
  9775. stride: vertexDataCount,
  9776. size: new Vector2( width, height )
  9777. };
  9778. _morphTextures.set( geometry, entry );
  9779. function disposeTexture() {
  9780. bufferTexture.dispose();
  9781. _morphTextures.delete( geometry );
  9782. geometry.removeEventListener( 'dispose', disposeTexture );
  9783. }
  9784. geometry.addEventListener( 'dispose', disposeTexture );
  9785. }
  9786. return entry;
  9787. }
  9788. /**
  9789. * This node implements the vertex transformation shader logic which is required
  9790. * for morph target animation.
  9791. *
  9792. * @augments Node
  9793. */
  9794. class MorphNode extends Node {
  9795. static get type() {
  9796. return 'MorphNode';
  9797. }
  9798. /**
  9799. * Constructs a new morph node.
  9800. *
  9801. * @param {Mesh} mesh - The mesh holding the morph targets.
  9802. */
  9803. constructor( mesh ) {
  9804. super( 'void' );
  9805. /**
  9806. * The mesh holding the morph targets.
  9807. *
  9808. * @type {Mesh}
  9809. */
  9810. this.mesh = mesh;
  9811. /**
  9812. * A uniform node which represents the morph base influence value.
  9813. *
  9814. * @type {UniformNode<float>}
  9815. */
  9816. this.morphBaseInfluence = uniform( 1 );
  9817. /**
  9818. * The update type overwritten since morph nodes are updated per object.
  9819. *
  9820. * @type {String}
  9821. */
  9822. this.updateType = NodeUpdateType.OBJECT;
  9823. }
  9824. /**
  9825. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  9826. *
  9827. * @param {NodeBuilder} builder - The current node builder.
  9828. */
  9829. setup( builder ) {
  9830. const { geometry } = builder;
  9831. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9832. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  9833. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9834. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9835. // nodes
  9836. const { texture: bufferMap, stride, size } = getEntry( geometry );
  9837. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  9838. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  9839. const width = int( size.width );
  9840. Loop( morphTargetsCount, ( { i } ) => {
  9841. const influence = float( 0 ).toVar();
  9842. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  9843. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  9844. } else {
  9845. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  9846. }
  9847. if ( hasMorphPosition === true ) {
  9848. positionLocal.addAssign( getMorph( {
  9849. bufferMap,
  9850. influence,
  9851. stride,
  9852. width,
  9853. depth: i,
  9854. offset: int( 0 )
  9855. } ) );
  9856. }
  9857. if ( hasMorphNormals === true ) {
  9858. normalLocal.addAssign( getMorph( {
  9859. bufferMap,
  9860. influence,
  9861. stride,
  9862. width,
  9863. depth: i,
  9864. offset: int( 1 )
  9865. } ) );
  9866. }
  9867. } );
  9868. }
  9869. /**
  9870. * Updates the state of the morphed mesh by updating the base influence.
  9871. *
  9872. * @param {NodeFrame} frame - The current node frame.
  9873. */
  9874. update( /*frame*/ ) {
  9875. const morphBaseInfluence = this.morphBaseInfluence;
  9876. if ( this.mesh.geometry.morphTargetsRelative ) {
  9877. morphBaseInfluence.value = 1;
  9878. } else {
  9879. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  9880. }
  9881. }
  9882. }
  9883. /**
  9884. * TSL function for creating a morph node.
  9885. *
  9886. * @function
  9887. * @param {Mesh} mesh - The mesh holding the morph targets.
  9888. * @returns {MorphNode}
  9889. */
  9890. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  9891. /**
  9892. * Base class for lighting nodes.
  9893. *
  9894. * @augments Node
  9895. */
  9896. class LightingNode extends Node {
  9897. static get type() {
  9898. return 'LightingNode';
  9899. }
  9900. /**
  9901. * Constructs a new lighting node.
  9902. */
  9903. constructor() {
  9904. super( 'vec3' );
  9905. /**
  9906. * This flag can be used for type testing.
  9907. *
  9908. * @type {Boolean}
  9909. * @readonly
  9910. * @default true
  9911. */
  9912. this.isLightingNode = true;
  9913. }
  9914. }
  9915. /**
  9916. * A generic class that can be used by nodes which contribute
  9917. * ambient occlusion to the scene. E.g. an ambient occlusion map
  9918. * node can be used as input for this module. Used in {@link NodeMaterial}.
  9919. *
  9920. * @augments LightingNode
  9921. */
  9922. class AONode extends LightingNode {
  9923. static get type() {
  9924. return 'AONode';
  9925. }
  9926. /**
  9927. * Constructs a new AO node.
  9928. *
  9929. * @param {Node<float>?} [aoNode=null] - The ambient occlusion node.
  9930. */
  9931. constructor( aoNode = null ) {
  9932. super();
  9933. /**
  9934. * The ambient occlusion node.
  9935. *
  9936. * @type {Node<float>?}
  9937. * @default null
  9938. */
  9939. this.aoNode = aoNode;
  9940. }
  9941. setup( builder ) {
  9942. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  9943. }
  9944. }
  9945. /**
  9946. * `LightingContextNode` represents an extension of the {@link module:ContextNode~ContextNode} module
  9947. * by adding lighting specific context data. It represents the runtime context of
  9948. * {@link LightsNode}.
  9949. *
  9950. * @augments ContextNode
  9951. */
  9952. class LightingContextNode extends ContextNode {
  9953. static get type() {
  9954. return 'LightingContextNode';
  9955. }
  9956. /**
  9957. * Constructs a new lighting context node.
  9958. *
  9959. * @param {LightsNode} node - The lights node.
  9960. * @param {LightingModel?} [lightingModel=null] - The current lighting model.
  9961. * @param {Node<vec3>?} [backdropNode=null] - A backdrop node.
  9962. * @param {Node<float>?} [backdropAlphaNode=null] - A backdrop alpha node.
  9963. */
  9964. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  9965. super( node );
  9966. /**
  9967. * The current lighting model.
  9968. *
  9969. * @type {LightingModel?}
  9970. * @default null
  9971. */
  9972. this.lightingModel = lightingModel;
  9973. /**
  9974. * A backdrop node.
  9975. *
  9976. * @type {Node<vec3>?}
  9977. * @default null
  9978. */
  9979. this.backdropNode = backdropNode;
  9980. /**
  9981. * A backdrop alpha node.
  9982. *
  9983. * @type {Node<float>?}
  9984. * @default null
  9985. */
  9986. this.backdropAlphaNode = backdropAlphaNode;
  9987. this._value = null;
  9988. }
  9989. /**
  9990. * Returns a lighting context object.
  9991. *
  9992. * @return {{
  9993. * radiance: Node<vec3>,
  9994. * irradiance: Node<vec3>,
  9995. * iblIrradiance: Node<vec3>,
  9996. * ambientOcclusion: Node<float>,
  9997. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  9998. * backdrop: Node<vec3>,
  9999. * backdropAlpha: Node<float>
  10000. * }} The lighting context object.
  10001. */
  10002. getContext() {
  10003. const { backdropNode, backdropAlphaNode } = this;
  10004. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10005. directSpecular = vec3().toVar( 'directSpecular' ),
  10006. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10007. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10008. const reflectedLight = {
  10009. directDiffuse,
  10010. directSpecular,
  10011. indirectDiffuse,
  10012. indirectSpecular
  10013. };
  10014. const context = {
  10015. radiance: vec3().toVar( 'radiance' ),
  10016. irradiance: vec3().toVar( 'irradiance' ),
  10017. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10018. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10019. reflectedLight,
  10020. backdrop: backdropNode,
  10021. backdropAlpha: backdropAlphaNode
  10022. };
  10023. return context;
  10024. }
  10025. setup( builder ) {
  10026. this.value = this._value || ( this._value = this.getContext() );
  10027. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10028. return super.setup( builder );
  10029. }
  10030. }
  10031. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10032. /**
  10033. * A generic class that can be used by nodes which contribute
  10034. * irradiance to the scene. E.g. a light map node can be used
  10035. * as input for this module. Used in {@link NodeMaterial}.
  10036. *
  10037. * @augments LightingNode
  10038. */
  10039. class IrradianceNode extends LightingNode {
  10040. static get type() {
  10041. return 'IrradianceNode';
  10042. }
  10043. /**
  10044. * Constructs a new irradiance node.
  10045. *
  10046. * @param {Node<vec3>} node - A node contributing irradiance.
  10047. */
  10048. constructor( node ) {
  10049. super();
  10050. /**
  10051. * A node contributing irradiance.
  10052. *
  10053. * @type {Node<vec3>}
  10054. */
  10055. this.node = node;
  10056. }
  10057. setup( builder ) {
  10058. builder.context.irradiance.addAssign( this.node );
  10059. }
  10060. }
  10061. /** @module ScreenNode **/
  10062. let screenSizeVec, viewportVec;
  10063. /**
  10064. * This node provides a collection of screen related metrics.
  10065. * Depending on {@link module:ScreenNode~ScreenNode#scope}, the nodes can represent
  10066. * resolution or viewport data as well as fragment or uv coordinates.
  10067. *
  10068. * @augments Node
  10069. */
  10070. class ScreenNode extends Node {
  10071. static get type() {
  10072. return 'ScreenNode';
  10073. }
  10074. /**
  10075. * Constructs a new screen node.
  10076. *
  10077. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10078. */
  10079. constructor( scope ) {
  10080. super();
  10081. /**
  10082. * The node represents different metric depending on which scope is selected.
  10083. *
  10084. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10085. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10086. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10087. * - `ScreenNode.UV`: Normalized coordinates.
  10088. *
  10089. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10090. */
  10091. this.scope = scope;
  10092. /**
  10093. * This flag can be used for type testing.
  10094. *
  10095. * @type {Boolean}
  10096. * @readonly
  10097. * @default true
  10098. */
  10099. this.isViewportNode = true;
  10100. }
  10101. /**
  10102. * This method is overwritten since the node type depends on the selected scope.
  10103. *
  10104. * @return {('vec2'|'vec4')} The node type.
  10105. */
  10106. getNodeType() {
  10107. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10108. else return 'vec2';
  10109. }
  10110. /**
  10111. * This method is overwritten since the node's update type depends on the selected scope.
  10112. *
  10113. * @return {NodeUpdateType} The update type.
  10114. */
  10115. getUpdateType() {
  10116. let updateType = NodeUpdateType.NONE;
  10117. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10118. updateType = NodeUpdateType.RENDER;
  10119. }
  10120. this.updateType = updateType;
  10121. return updateType;
  10122. }
  10123. /**
  10124. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10125. * from the current renderer.
  10126. *
  10127. * @param {NodeFrame} frame - A reference to the current node frame.
  10128. */
  10129. update( { renderer } ) {
  10130. const renderTarget = renderer.getRenderTarget();
  10131. if ( this.scope === ScreenNode.VIEWPORT ) {
  10132. if ( renderTarget !== null ) {
  10133. viewportVec.copy( renderTarget.viewport );
  10134. } else {
  10135. renderer.getViewport( viewportVec );
  10136. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10137. }
  10138. } else {
  10139. if ( renderTarget !== null ) {
  10140. screenSizeVec.width = renderTarget.width;
  10141. screenSizeVec.height = renderTarget.height;
  10142. } else {
  10143. renderer.getDrawingBufferSize( screenSizeVec );
  10144. }
  10145. }
  10146. }
  10147. setup( /*builder*/ ) {
  10148. const scope = this.scope;
  10149. let output = null;
  10150. if ( scope === ScreenNode.SIZE ) {
  10151. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10152. } else if ( scope === ScreenNode.VIEWPORT ) {
  10153. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10154. } else {
  10155. output = vec2( screenCoordinate.div( screenSize ) );
  10156. }
  10157. return output;
  10158. }
  10159. generate( builder ) {
  10160. if ( this.scope === ScreenNode.COORDINATE ) {
  10161. let coord = builder.getFragCoord();
  10162. if ( builder.isFlipY() ) {
  10163. // follow webgpu standards
  10164. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10165. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10166. }
  10167. return coord;
  10168. }
  10169. return super.generate( builder );
  10170. }
  10171. }
  10172. ScreenNode.COORDINATE = 'coordinate';
  10173. ScreenNode.VIEWPORT = 'viewport';
  10174. ScreenNode.SIZE = 'size';
  10175. ScreenNode.UV = 'uv';
  10176. // Screen
  10177. /**
  10178. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10179. *
  10180. * @type {ScreenNode<vec2>}
  10181. */
  10182. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10183. /**
  10184. * TSL object that represents the screen resolution in physical pixel units.
  10185. *
  10186. * @type {ScreenNode<vec2>}
  10187. */
  10188. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10189. /**
  10190. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10191. *
  10192. * @type {ScreenNode<vec2>}
  10193. */
  10194. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10195. // Viewport
  10196. /**
  10197. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10198. *
  10199. * @type {ScreenNode<vec4>}
  10200. */
  10201. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10202. /**
  10203. * TSL object that represents the viewport resolution in physical pixel units.
  10204. *
  10205. * @type {ScreenNode<vec2>}
  10206. */
  10207. const viewportSize = viewport.zw;
  10208. /**
  10209. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10210. *
  10211. * @type {ScreenNode<vec2>}
  10212. */
  10213. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10214. /**
  10215. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10216. *
  10217. * @type {ScreenNode<vec2>}
  10218. */
  10219. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10220. // Deprecated
  10221. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10222. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10223. return screenSize;
  10224. }, 'vec2' ).once() )();
  10225. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10226. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10227. return screenUV;
  10228. }, 'vec2' ).once() )();
  10229. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10230. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10231. return screenUV.flipY();
  10232. }, 'vec2' ).once() )();
  10233. /** @module ViewportTextureNode **/
  10234. const _size$4 = /*@__PURE__*/ new Vector2();
  10235. /**
  10236. * A special type of texture node which represents the data of the current viewport
  10237. * as a texture. The module extracts data from the current bound framebuffer with
  10238. * a copy operation so no extra render pass is required to produce the texture data
  10239. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10240. * variety of effects like refractive or transmissive materials.
  10241. *
  10242. * @augments module:TextureNode~TextureNode
  10243. */
  10244. class ViewportTextureNode extends TextureNode {
  10245. static get type() {
  10246. return 'ViewportTextureNode';
  10247. }
  10248. /**
  10249. * Constructs a new viewport texture node.
  10250. *
  10251. * @param {Node} [uvNode=screenUV] - The uv node.
  10252. * @param {Node?} [levelNode=null] - The level node.
  10253. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10254. */
  10255. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10256. if ( framebufferTexture === null ) {
  10257. framebufferTexture = new FramebufferTexture();
  10258. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10259. }
  10260. super( framebufferTexture, uvNode, levelNode );
  10261. /**
  10262. * Whether to generate mipmaps or not.
  10263. *
  10264. * @type {Boolean}
  10265. * @default false
  10266. */
  10267. this.generateMipmaps = false;
  10268. /**
  10269. * This flag can be used for type testing.
  10270. *
  10271. * @type {Boolean}
  10272. * @readonly
  10273. * @default true
  10274. */
  10275. this.isOutputTextureNode = true;
  10276. /**
  10277. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10278. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10279. *
  10280. * @type {String}
  10281. * @default 'frame'
  10282. */
  10283. this.updateBeforeType = NodeUpdateType.FRAME;
  10284. }
  10285. updateBefore( frame ) {
  10286. const renderer = frame.renderer;
  10287. renderer.getDrawingBufferSize( _size$4 );
  10288. //
  10289. const framebufferTexture = this.value;
  10290. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10291. framebufferTexture.image.width = _size$4.width;
  10292. framebufferTexture.image.height = _size$4.height;
  10293. framebufferTexture.needsUpdate = true;
  10294. }
  10295. //
  10296. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10297. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10298. renderer.copyFramebufferToTexture( framebufferTexture );
  10299. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10300. }
  10301. clone() {
  10302. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10303. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10304. return viewportTextureNode;
  10305. }
  10306. }
  10307. /**
  10308. * TSL function for creating a viewport texture node.
  10309. *
  10310. * @function
  10311. * @param {Node} [uvNode=screenUV] - The uv node.
  10312. * @param {Node?} [levelNode=null] - The level node.
  10313. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10314. * @returns {ViewportTextureNode}
  10315. */
  10316. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10317. /**
  10318. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10319. *
  10320. * @function
  10321. * @param {Node} [uvNode=screenUV] - The uv node.
  10322. * @param {Node?} [levelNode=null] - The level node.
  10323. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10324. * @returns {ViewportTextureNode}
  10325. */
  10326. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10327. /** @module ViewportDepthTextureNode **/
  10328. let sharedDepthbuffer = null;
  10329. /**
  10330. * Represents the depth of the current viewport as a texture. This module
  10331. * can be used in combination with viewport texture to achieve effects
  10332. * that require depth evaluation.
  10333. *
  10334. * @augments module:ViewportTextureNode~ViewportTextureNode
  10335. */
  10336. class ViewportDepthTextureNode extends ViewportTextureNode {
  10337. static get type() {
  10338. return 'ViewportDepthTextureNode';
  10339. }
  10340. /**
  10341. * Constructs a new viewport depth texture node.
  10342. *
  10343. * @param {Node} [uvNode=screenUV] - The uv node.
  10344. * @param {Node?} [levelNode=null] - The level node.
  10345. */
  10346. constructor( uvNode = screenUV, levelNode = null ) {
  10347. if ( sharedDepthbuffer === null ) {
  10348. sharedDepthbuffer = new DepthTexture();
  10349. }
  10350. super( uvNode, levelNode, sharedDepthbuffer );
  10351. }
  10352. }
  10353. /**
  10354. * TSL function for a viewport depth texture node.
  10355. *
  10356. * @function
  10357. * @param {Node} [uvNode=screenUV] - The uv node.
  10358. * @param {Node?} [levelNode=null] - The level node.
  10359. * @returns {ViewportDepthTextureNode}
  10360. */
  10361. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10362. /** @module ViewportDepthNode **/
  10363. /**
  10364. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10365. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10366. * fragment or for depth evaluation purposes.
  10367. *
  10368. * @augments Node
  10369. */
  10370. class ViewportDepthNode extends Node {
  10371. static get type() {
  10372. return 'ViewportDepthNode';
  10373. }
  10374. /**
  10375. * Constructs a new viewport depth node.
  10376. *
  10377. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10378. * @param {Node?} [valueNode=null] - The value node.
  10379. */
  10380. constructor( scope, valueNode = null ) {
  10381. super( 'float' );
  10382. /**
  10383. * The node behaves differently depending on which scope is selected.
  10384. *
  10385. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10386. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10387. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10388. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  10389. *
  10390. * @type {('depth'|'depthBase'|'linearDepth')}
  10391. */
  10392. this.scope = scope;
  10393. /**
  10394. * Can be used to define a custom depth value.
  10395. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  10396. *
  10397. * @type {Node?}
  10398. * @default null
  10399. */
  10400. this.valueNode = valueNode;
  10401. /**
  10402. * This flag can be used for type testing.
  10403. *
  10404. * @type {Boolean}
  10405. * @readonly
  10406. * @default true
  10407. */
  10408. this.isViewportDepthNode = true;
  10409. }
  10410. generate( builder ) {
  10411. const { scope } = this;
  10412. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10413. return builder.getFragDepth();
  10414. }
  10415. return super.generate( builder );
  10416. }
  10417. setup( { camera } ) {
  10418. const { scope } = this;
  10419. const value = this.valueNode;
  10420. let node = null;
  10421. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10422. if ( value !== null ) {
  10423. node = depthBase().assign( value );
  10424. }
  10425. } else if ( scope === ViewportDepthNode.DEPTH ) {
  10426. if ( camera.isPerspectiveCamera ) {
  10427. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  10428. } else {
  10429. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10430. }
  10431. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  10432. if ( value !== null ) {
  10433. if ( camera.isPerspectiveCamera ) {
  10434. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  10435. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  10436. } else {
  10437. node = value;
  10438. }
  10439. } else {
  10440. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10441. }
  10442. }
  10443. return node;
  10444. }
  10445. }
  10446. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  10447. ViewportDepthNode.DEPTH = 'depth';
  10448. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  10449. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  10450. /**
  10451. * TSL function for converting a viewZ value to an orthographic depth value.
  10452. *
  10453. * @function
  10454. * @param {Node<float>} viewZ - The viewZ node.
  10455. * @param {Node<float>} near - The camera's near value.
  10456. * @param {Node<float>} far - The camera's far value.
  10457. * @returns {Node<float>}
  10458. */
  10459. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  10460. /**
  10461. * TSL function for converting an orthographic depth value to a viewZ value.
  10462. *
  10463. * @function
  10464. * @param {Node<float>} depth - The orthographic depth.
  10465. * @param {Node<float>} near - The camera's near value.
  10466. * @param {Node<float>} far - The camera's far value.
  10467. * @returns {Node<float>}
  10468. */
  10469. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  10470. /**
  10471. * TSL function for converting a viewZ value to a perspective depth value.
  10472. *
  10473. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  10474. *
  10475. * @function
  10476. * @param {Node<float>} viewZ - The viewZ node.
  10477. * @param {Node<float>} near - The camera's near value.
  10478. * @param {Node<float>} far - The camera's far value.
  10479. * @returns {Node<float>}
  10480. */
  10481. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  10482. /**
  10483. * TSL function for converting a perspective depth value to a viewZ value.
  10484. *
  10485. * @function
  10486. * @param {Node<float>} depth - The perspective depth.
  10487. * @param {Node<float>} near - The camera's near value.
  10488. * @param {Node<float>} far - The camera's far value.
  10489. * @returns {Node<float>}
  10490. */
  10491. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  10492. /**
  10493. * TSL function for converting a viewZ value to a logarithmic depth value.
  10494. *
  10495. * @function
  10496. * @param {Node<float>} viewZ - The viewZ node.
  10497. * @param {Node<float>} near - The camera's near value.
  10498. * @param {Node<float>} far - The camera's far value.
  10499. * @returns {Node<float>}
  10500. */
  10501. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  10502. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  10503. // The final logarithmic depth formula used here is adapted from one described in an
  10504. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  10505. // which was an improvement upon an earlier formula one described in an
  10506. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  10507. // Ulrich's formula is the following:
  10508. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  10509. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  10510. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  10511. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  10512. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  10513. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  10514. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  10515. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  10516. // be used, and ultimately Ulrich's "near plane" version was chosen.
  10517. // Outerra eventually made another improvement to their original "C-constant" variant,
  10518. // but it still does not incorporate the camera near plane (for this version,
  10519. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  10520. // Here we make 4 changes to Ulrich's formula:
  10521. // 1. Clamp the camera near plane so we don't divide by 0.
  10522. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  10523. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  10524. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  10525. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  10526. // so we do the same here, hence the 'viewZ.negate()' call.
  10527. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  10528. near = near.max( 1e-6 ).toVar();
  10529. const numerator = log2( viewZ.negate().div( near ) );
  10530. const denominator = log2( far.div( near ) );
  10531. return numerator.div( denominator );
  10532. };
  10533. /**
  10534. * TSL function for converting a logarithmic depth value to a viewZ value.
  10535. *
  10536. * @function
  10537. * @param {Node<float>} depth - The logarithmic depth.
  10538. * @param {Node<float>} near - The camera's near value.
  10539. * @param {Node<float>} far - The camera's far value.
  10540. * @returns {Node<float>}
  10541. */
  10542. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  10543. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  10544. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  10545. // a negative viewZ).
  10546. const exponent = depth.mul( log( far.div( near ) ) );
  10547. return float( Math.E ).pow( exponent ).mul( near ).negate();
  10548. };
  10549. /**
  10550. * TSL function for defining a value for the current fragment's depth.
  10551. *
  10552. * @function
  10553. * @param {Node<float>} value - The depth value to set.
  10554. * @returns {ViewportDepthNode<float>}
  10555. */
  10556. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  10557. /**
  10558. * TSL object that represents the depth value for the current fragment.
  10559. *
  10560. * @type {ViewportDepthNode}
  10561. */
  10562. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  10563. /**
  10564. * TSL function for converting a perspective depth value to linear depth.
  10565. *
  10566. * @function
  10567. * @param {Node<float>} value - The perspective depth.
  10568. * @returns {ViewportDepthNode<float>}
  10569. */
  10570. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  10571. /**
  10572. * TSL object that represents the linear (orthographic) depth value of the current fragment
  10573. *
  10574. * @type {ViewportDepthNode}
  10575. */
  10576. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  10577. depth.assign = ( value ) => depthBase( value );
  10578. /** @module BuiltinNode **/
  10579. /**
  10580. * The node allows to set values for built-in shader variables. That is
  10581. * required for features like hardware-accelerated vertex clipping.
  10582. *
  10583. * @augments Node
  10584. */
  10585. class BuiltinNode extends Node {
  10586. /**
  10587. * Constructs a new builtin node.
  10588. *
  10589. * @param {String} name - The name of the built-in shader variable.
  10590. */
  10591. constructor( name ) {
  10592. super( 'float' );
  10593. /**
  10594. * The name of the built-in shader variable.
  10595. *
  10596. * @type {String}
  10597. */
  10598. this.name = name;
  10599. /**
  10600. * This flag can be used for type testing.
  10601. *
  10602. * @type {Boolean}
  10603. * @readonly
  10604. * @default true
  10605. */
  10606. this.isBuiltinNode = true;
  10607. }
  10608. /**
  10609. * Generates the code snippet of the builtin node.
  10610. *
  10611. * @param {NodeBuilder} builder - The current node builder.
  10612. * @return {String} The generated code snippet.
  10613. */
  10614. generate( /* builder */ ) {
  10615. return this.name;
  10616. }
  10617. }
  10618. /**
  10619. * TSL function for creating a builtin node.
  10620. *
  10621. * @function
  10622. * @param {String} name - The name of the built-in shader variable.
  10623. * @returns {BuiltinNode}
  10624. */
  10625. const builtin = nodeProxy( BuiltinNode );
  10626. /** @module ClippingNode **/
  10627. /**
  10628. * ```
  10629. * This node is used in {@link NodeMaterial} to setup the clipping
  10630. * which can happen hardware-accelerated (if supported) and optionally
  10631. * use alpha-to-coverage for anti-aliasing clipped edges.
  10632. * ```
  10633. * @augments Node
  10634. */
  10635. class ClippingNode extends Node {
  10636. static get type() {
  10637. return 'ClippingNode';
  10638. }
  10639. /**
  10640. * Constructs a new clipping node.
  10641. *
  10642. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  10643. * the selected scope influences the behavior of the node and what type of code is generated.
  10644. */
  10645. constructor( scope = ClippingNode.DEFAULT ) {
  10646. super();
  10647. /**
  10648. * The node's scope. Similar to other nodes, the selected scope influences
  10649. * the behavior of the node and what type of code is generated.
  10650. *
  10651. * @type {('default'|'hardware'|'alphaToCoverage')}
  10652. */
  10653. this.scope = scope;
  10654. }
  10655. /**
  10656. * Setups the node depending on the selected scope.
  10657. *
  10658. * @param {NodeBuilder} builder - The current node builder.
  10659. * @return {Node} The result node.
  10660. */
  10661. setup( builder ) {
  10662. super.setup( builder );
  10663. const clippingContext = builder.clippingContext;
  10664. const { intersectionPlanes, unionPlanes } = clippingContext;
  10665. this.hardwareClipping = builder.material.hardwareClipping;
  10666. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  10667. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  10668. } else if ( this.scope === ClippingNode.HARDWARE ) {
  10669. return this.setupHardwareClipping( unionPlanes, builder );
  10670. } else {
  10671. return this.setupDefault( intersectionPlanes, unionPlanes );
  10672. }
  10673. }
  10674. /**
  10675. * Setups alpha to coverage.
  10676. *
  10677. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10678. * @param {Array<Vector4>} unionPlanes - The union planes.
  10679. * @return {Node} The result node.
  10680. */
  10681. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  10682. return Fn( () => {
  10683. const distanceToPlane = float().toVar( 'distanceToPlane' );
  10684. const distanceGradient = float().toVar( 'distanceToGradient' );
  10685. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  10686. const numUnionPlanes = unionPlanes.length;
  10687. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10688. const clippingPlanes = uniformArray( unionPlanes );
  10689. Loop( numUnionPlanes, ( { i } ) => {
  10690. const plane = clippingPlanes.element( i );
  10691. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10692. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10693. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  10694. } );
  10695. }
  10696. const numIntersectionPlanes = intersectionPlanes.length;
  10697. if ( numIntersectionPlanes > 0 ) {
  10698. const clippingPlanes = uniformArray( intersectionPlanes );
  10699. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  10700. Loop( numIntersectionPlanes, ( { i } ) => {
  10701. const plane = clippingPlanes.element( i );
  10702. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10703. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10704. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  10705. } );
  10706. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  10707. }
  10708. diffuseColor.a.mulAssign( clipOpacity );
  10709. diffuseColor.a.equal( 0.0 ).discard();
  10710. } )();
  10711. }
  10712. /**
  10713. * Setups the default clipping.
  10714. *
  10715. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10716. * @param {Array<Vector4>} unionPlanes - The union planes.
  10717. * @return {Node} The result node.
  10718. */
  10719. setupDefault( intersectionPlanes, unionPlanes ) {
  10720. return Fn( () => {
  10721. const numUnionPlanes = unionPlanes.length;
  10722. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10723. const clippingPlanes = uniformArray( unionPlanes );
  10724. Loop( numUnionPlanes, ( { i } ) => {
  10725. const plane = clippingPlanes.element( i );
  10726. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  10727. } );
  10728. }
  10729. const numIntersectionPlanes = intersectionPlanes.length;
  10730. if ( numIntersectionPlanes > 0 ) {
  10731. const clippingPlanes = uniformArray( intersectionPlanes );
  10732. const clipped = bool( true ).toVar( 'clipped' );
  10733. Loop( numIntersectionPlanes, ( { i } ) => {
  10734. const plane = clippingPlanes.element( i );
  10735. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  10736. } );
  10737. clipped.discard();
  10738. }
  10739. } )();
  10740. }
  10741. /**
  10742. * Setups hardware clipping.
  10743. *
  10744. * @param {Array<Vector4>} unionPlanes - The union planes.
  10745. * @param {NodeBuilder} builder - The current node builder.
  10746. * @return {Node} The result node.
  10747. */
  10748. setupHardwareClipping( unionPlanes, builder ) {
  10749. const numUnionPlanes = unionPlanes.length;
  10750. builder.enableHardwareClipping( numUnionPlanes );
  10751. return Fn( () => {
  10752. const clippingPlanes = uniformArray( unionPlanes );
  10753. const hw_clip_distances = builtin( builder.getClipDistance() );
  10754. Loop( numUnionPlanes, ( { i } ) => {
  10755. const plane = clippingPlanes.element( i );
  10756. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  10757. hw_clip_distances.element( i ).assign( distance );
  10758. } );
  10759. } )();
  10760. }
  10761. }
  10762. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  10763. ClippingNode.DEFAULT = 'default';
  10764. ClippingNode.HARDWARE = 'hardware';
  10765. /**
  10766. * TSL function for setting up the default clipping logic.
  10767. *
  10768. * @function
  10769. * @returns {ClippingNode}
  10770. */
  10771. const clipping = () => nodeObject( new ClippingNode() );
  10772. /**
  10773. * TSL function for setting up alpha to coverage.
  10774. *
  10775. * @function
  10776. * @returns {ClippingNode}
  10777. */
  10778. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  10779. /**
  10780. * TSL function for setting up hardware-based clipping.
  10781. *
  10782. * @function
  10783. * @returns {ClippingNode}
  10784. */
  10785. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  10786. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  10787. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  10788. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10789. return fract( mul( 1.0e4, sin( mul( 17.0, value.x ).add( mul( 0.1, value.y ) ) ) ).mul( add( 0.1, abs( sin( mul( 13.0, value.y ).add( value.x ) ) ) ) ) );
  10790. } );
  10791. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10792. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  10793. } );
  10794. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  10795. // Find the discretized derivatives of our coordinates
  10796. const maxDeriv = max$1(
  10797. length( dFdx( position.xyz ) ),
  10798. length( dFdy( position.xyz ) )
  10799. );
  10800. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  10801. // Find two nearest log-discretized noise scales
  10802. const pixScales = vec2(
  10803. exp2( floor( log2( pixScale ) ) ),
  10804. exp2( ceil( log2( pixScale ) ) )
  10805. );
  10806. // Compute alpha thresholds at our two noise scales
  10807. const alpha = vec2(
  10808. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  10809. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  10810. );
  10811. // Factor to interpolate lerp with
  10812. const lerpFactor = fract( log2( pixScale ) );
  10813. // Interpolate alpha threshold from noise at two scales
  10814. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  10815. // Pass into CDF to compute uniformly distrib threshold
  10816. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  10817. const cases = vec3(
  10818. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  10819. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  10820. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  10821. // Find our final, uniformly distributed alpha threshold (ατ)
  10822. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  10823. // Avoids ατ == 0. Could also do ατ =1-ατ
  10824. return clamp( threshold, 1.0e-6, 1.0 );
  10825. } ).setLayout( {
  10826. name: 'getAlphaHashThreshold',
  10827. type: 'float',
  10828. inputs: [
  10829. { name: 'position', type: 'vec3' }
  10830. ]
  10831. } );
  10832. /**
  10833. * Base class for all node materials.
  10834. *
  10835. * @augments Material
  10836. */
  10837. class NodeMaterial extends Material {
  10838. static get type() {
  10839. return 'NodeMaterial';
  10840. }
  10841. /**
  10842. * Represents the type of the node material.
  10843. *
  10844. * @type {String}
  10845. */
  10846. get type() {
  10847. return this.constructor.type;
  10848. }
  10849. set type( _value ) { /* */ }
  10850. /**
  10851. * Constructs a new node material.
  10852. */
  10853. constructor() {
  10854. super();
  10855. /**
  10856. * This flag can be used for type testing.
  10857. *
  10858. * @type {Boolean}
  10859. * @readonly
  10860. * @default true
  10861. */
  10862. this.isNodeMaterial = true;
  10863. /**
  10864. * Whether this material is affected by fog or not.
  10865. *
  10866. * @type {Boolean}
  10867. * @default true
  10868. */
  10869. this.fog = true;
  10870. /**
  10871. * Whether this material is affected by lights or not.
  10872. *
  10873. * @type {Boolean}
  10874. * @default false
  10875. */
  10876. this.lights = false;
  10877. /**
  10878. * Whether this material uses hardware clipping or not.
  10879. * This property is managed by the engine and should not be
  10880. * modified by apps.
  10881. *
  10882. * @type {Boolean}
  10883. * @default false
  10884. */
  10885. this.hardwareClipping = false;
  10886. /**
  10887. * Node materials which set their `lights` property to `true`
  10888. * are affected by all lights of the scene. Sometimes selective
  10889. * lighting is wanted which means only _some_ lights in the scene
  10890. * affect a material. This can be achieved by creating an instance
  10891. * of {@link module:LightsNode~LightsNode} with a list of selective
  10892. * lights and assign the node to this property.
  10893. *
  10894. * ```js
  10895. * const customLightsNode = lights( [ light1, light2 ] );
  10896. * material.lightsNode = customLightsNode;
  10897. * ```
  10898. *
  10899. * @type {LightsNode?}
  10900. * @default null
  10901. */
  10902. this.lightsNode = null;
  10903. /**
  10904. * The environment of node materials can be defined by an environment
  10905. * map assigned to the `envMap` property or by `Scene.environment`
  10906. * if the node material is a PBR material. This node property allows to overwrite
  10907. * the default behavior and define the environment with a custom node.
  10908. *
  10909. * ```js
  10910. * material.envNode = pmremTexture( renderTarget.texture );
  10911. * ```
  10912. *
  10913. * @type {Node<vec3>?}
  10914. * @default null
  10915. */
  10916. this.envNode = null;
  10917. /**
  10918. * The lighting of node materials might be influenced by ambient occlusion.
  10919. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  10920. * and the respective `aoMapIntensity`. This node property allows to overwrite
  10921. * the default and define the ambient occlusion with a custom node instead.
  10922. *
  10923. * If you don't want to overwrite the diffuse color but modify the existing
  10924. * values instead, use {@link module:MaterialNode.materialAO}.
  10925. *
  10926. * @type {Node<float>?}
  10927. * @default null
  10928. */
  10929. this.aoNode = null;
  10930. /**
  10931. * The diffuse color of node materials is by default inferred from the
  10932. * `color` and `map` properties. This node property allows to overwrite the default
  10933. * and define the diffuse color with a node instead.
  10934. *
  10935. * ```js
  10936. * material.colorNode = color( 0xff0000 ); // define red color
  10937. * ```
  10938. *
  10939. * If you don't want to overwrite the diffuse color but modify the existing
  10940. * values instead, use {@link module:MaterialNode.materialColor}.
  10941. *
  10942. * ```js
  10943. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  10944. * ```
  10945. *
  10946. * @type {Node<vec3>?}
  10947. * @default null
  10948. */
  10949. this.colorNode = null;
  10950. /**
  10951. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  10952. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  10953. * and define the normals with a node instead.
  10954. *
  10955. * If you don't want to overwrite the normals but modify the existing values instead,
  10956. * use {@link module:MaterialNode.materialNormal}.
  10957. *
  10958. * @type {Node<vec3>?}
  10959. * @default null
  10960. */
  10961. this.normalNode = null;
  10962. /**
  10963. * The opacity of node materials is by default inferred from the `opacity`
  10964. * and `alphaMap` properties. This node property allows to overwrite the default
  10965. * and define the opacity with a node instead.
  10966. *
  10967. * If you don't want to overwrite the normals but modify the existing
  10968. * value instead, use {@link module:MaterialNode.materialOpacity}.
  10969. *
  10970. * @type {Node<float>?}
  10971. * @default null
  10972. */
  10973. this.opacityNode = null;
  10974. /**
  10975. * This node can be used to to implement a variety of filter-like effects. The idea is
  10976. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  10977. * to create an arbitrary effect and then assign the node composition to this property.
  10978. * Everything behind the object using this material will now be affected by a filter.
  10979. *
  10980. * ```js
  10981. * const material = new NodeMaterial()
  10982. * material.transparent = true;
  10983. *
  10984. * // everything behind the object will be monochromatic
  10985. * material.backdropNode = viewportSharedTexture().rgb.saturation( 0 );
  10986. * ```
  10987. *
  10988. * Backdrop computations are part of the lighting so only lit materials can use this property.
  10989. *
  10990. * @type {Node<vec3>?}
  10991. * @default null
  10992. */
  10993. this.backdropNode = null;
  10994. /**
  10995. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  10996. *
  10997. * @type {Node<float>?}
  10998. * @default null
  10999. */
  11000. this.backdropAlphaNode = null;
  11001. /**
  11002. * The alpha test of node materials is by default inferred from the `alphaTest`
  11003. * property. This node property allows to overwrite the default and define the
  11004. * alpha test with a node instead.
  11005. *
  11006. * If you don't want to overwrite the alpha test but modify the existing
  11007. * value instead, use {@link module:MaterialNode.materialAlphaTest}.
  11008. *
  11009. * @type {Node<float>?}
  11010. * @default null
  11011. */
  11012. this.alphaTestNode = null;
  11013. /**
  11014. * The local vertex positions are computed based on multiple factors like the
  11015. * attribute data, morphing or skinning. This node property allows to overwrite
  11016. * the default and define local vertex positions with nodes instead.
  11017. *
  11018. * If you don't want to overwrite the vertex positions but modify the existing
  11019. * values instead, use {@link module:Position.positionLocal}.
  11020. *
  11021. *```js
  11022. * material.positionNode = positionLocal.add( displace );
  11023. * ```
  11024. *
  11025. * @type {Node<vec3>?}
  11026. * @default null
  11027. */
  11028. this.positionNode = null;
  11029. /**
  11030. * This node property is intended for logic which modifies geometry data once or per animation step.
  11031. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11032. * `geometryNode` is intended as a dedicated API so there is an intended spot where goemetry modiciations
  11033. * can be implemented.
  11034. *
  11035. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11036. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11037. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11038. * eventually assigned to `geometryNode`.
  11039. *
  11040. * @type {Function}
  11041. * @default null
  11042. */
  11043. this.geometryNode = null;
  11044. /**
  11045. * Allows to overwrite depth values in the fragment shader.
  11046. *
  11047. * @type {Node<float>?}
  11048. * @default null
  11049. */
  11050. this.depthNode = null;
  11051. /**
  11052. * Allows to overwrite the position used for shadow map rendering which
  11053. * is by default {@link module:Position.positionWorld}, the vertex position
  11054. * in world space.
  11055. *
  11056. * @type {Node<float>?}
  11057. * @default null
  11058. */
  11059. this.shadowPositionNode = null;
  11060. /**
  11061. * This node can be used to influence how an object using this node material
  11062. * receive shadows.
  11063. *
  11064. * ```js
  11065. * const totalShadows = float( 1 ).toVar();
  11066. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11067. * totalShadows.mulAssign( shadow );
  11068. * //return float( 1 ); // bypass received shadows
  11069. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11070. * } );
  11071. *
  11072. * @type {Node<vec4>?}
  11073. * @default null
  11074. */
  11075. this.receivedShadowNode = null;
  11076. /**
  11077. * This node can be used to influence how an object using this node material
  11078. * casts shadows. To apply a color to shadows, you can simply do:
  11079. *
  11080. * ```js
  11081. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11082. * ```
  11083. *
  11084. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11085. * is also common to use the property with `Fn` function so checks are performed
  11086. * per fragment.
  11087. *
  11088. * ```js
  11089. * materialCustomShadow.castShadowNode = Fn( () => {
  11090. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11091. * return materialColor;
  11092. * } )();
  11093. * ```
  11094. *
  11095. * @type {Node<vec4>?}
  11096. * @default null
  11097. */
  11098. this.castShadowNode = null;
  11099. /**
  11100. * This node can be used to define the final output of the material.
  11101. *
  11102. * TODO: Explain the differences to `fragmentNode`.
  11103. *
  11104. * @type {Node<vec4>?}
  11105. * @default null
  11106. */
  11107. this.outputNode = null;
  11108. /**
  11109. * MRT configuration is done on renderer or pass level. This node allows to
  11110. * overwrite what values are written into MRT targets on material level. This
  11111. * can be useful for implementing selective FX features that should only affect
  11112. * specific objects.
  11113. *
  11114. * @type {MRTNode?}
  11115. * @default null
  11116. */
  11117. this.mrtNode = null;
  11118. /**
  11119. * This node property can be used if you need complete freedom in implementing
  11120. * the fragment shader. Assigning a node will replace the built-in material
  11121. * logic used in the fragment stage.
  11122. *
  11123. * @type {Node<vec4>?}
  11124. * @default null
  11125. */
  11126. this.fragmentNode = null;
  11127. /**
  11128. * This node property can be used if you need complete freedom in implementing
  11129. * the vertex shader. Assigning a node will replace the built-in material logic
  11130. * used in the vertex stage.
  11131. *
  11132. * @type {Node<vec4>?}
  11133. * @default null
  11134. */
  11135. this.vertexNode = null;
  11136. }
  11137. /**
  11138. * Allows to define a custom cache key that influence the material key computation
  11139. * for render objects.
  11140. *
  11141. * @return {String} The custom cache key.
  11142. */
  11143. customProgramCacheKey() {
  11144. return this.type + getCacheKey$1( this );
  11145. }
  11146. /**
  11147. * Builds this material with the given node builder.
  11148. *
  11149. * @param {NodeBuilder} builder - The current node builder.
  11150. */
  11151. build( builder ) {
  11152. this.setup( builder );
  11153. }
  11154. /**
  11155. * Setups a node material observer with the given builder.
  11156. *
  11157. * @param {NodeBuilder} builder - The current node builder.
  11158. * @return {NodeMaterialObserver} The node material observer.
  11159. */
  11160. setupObserver( builder ) {
  11161. return new NodeMaterialObserver( builder );
  11162. }
  11163. /**
  11164. * Setups the vertex and fragment stage of this node material.
  11165. *
  11166. * @param {NodeBuilder} builder - The current node builder.
  11167. */
  11168. setup( builder ) {
  11169. builder.context.setupNormal = () => this.setupNormal( builder );
  11170. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11171. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11172. const renderer = builder.renderer;
  11173. const renderTarget = renderer.getRenderTarget();
  11174. // < VERTEX STAGE >
  11175. builder.addStack();
  11176. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11177. builder.stack.outputNode = vertexNode;
  11178. this.setupHardwareClipping( builder );
  11179. if ( this.geometryNode !== null ) {
  11180. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11181. }
  11182. builder.addFlow( 'vertex', builder.removeStack() );
  11183. // < FRAGMENT STAGE >
  11184. builder.addStack();
  11185. let resultNode;
  11186. const clippingNode = this.setupClipping( builder );
  11187. if ( this.depthWrite === true || this.depthTest === true ) {
  11188. // only write depth if depth buffer is configured
  11189. if ( renderTarget !== null ) {
  11190. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11191. } else {
  11192. if ( renderer.depth === true ) this.setupDepth( builder );
  11193. }
  11194. }
  11195. if ( this.fragmentNode === null ) {
  11196. this.setupDiffuseColor( builder );
  11197. this.setupVariants( builder );
  11198. const outgoingLightNode = this.setupLighting( builder );
  11199. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11200. // force unsigned floats - useful for RenderTargets
  11201. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11202. resultNode = this.setupOutput( builder, basicOutput );
  11203. // OUTPUT NODE
  11204. output.assign( resultNode );
  11205. //
  11206. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11207. // MRT
  11208. if ( renderTarget !== null ) {
  11209. const mrt = renderer.getMRT();
  11210. const materialMRT = this.mrtNode;
  11211. if ( mrt !== null ) {
  11212. resultNode = mrt;
  11213. if ( materialMRT !== null ) {
  11214. resultNode = mrt.merge( materialMRT );
  11215. }
  11216. } else if ( materialMRT !== null ) {
  11217. resultNode = materialMRT;
  11218. }
  11219. }
  11220. } else {
  11221. let fragmentNode = this.fragmentNode;
  11222. if ( fragmentNode.isOutputStructNode !== true ) {
  11223. fragmentNode = vec4( fragmentNode );
  11224. }
  11225. resultNode = this.setupOutput( builder, fragmentNode );
  11226. }
  11227. builder.stack.outputNode = resultNode;
  11228. builder.addFlow( 'fragment', builder.removeStack() );
  11229. // < MONITOR >
  11230. builder.monitor = this.setupObserver( builder );
  11231. }
  11232. /**
  11233. * Setups the clipping node.
  11234. *
  11235. * @param {NodeBuilder} builder - The current node builder.
  11236. * @return {ClippingNode} The clipping node.
  11237. */
  11238. setupClipping( builder ) {
  11239. if ( builder.clippingContext === null ) return null;
  11240. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11241. let result = null;
  11242. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11243. const samples = builder.renderer.samples;
  11244. if ( this.alphaToCoverage && samples > 1 ) {
  11245. // to be added to flow when the color/alpha value has been determined
  11246. result = clippingAlpha();
  11247. } else {
  11248. builder.stack.add( clipping() );
  11249. }
  11250. }
  11251. return result;
  11252. }
  11253. /**
  11254. * Setups the hardware clipping if available on the current device.
  11255. *
  11256. * @param {NodeBuilder} builder - The current node builder.
  11257. */
  11258. setupHardwareClipping( builder ) {
  11259. this.hardwareClipping = false;
  11260. if ( builder.clippingContext === null ) return;
  11261. const candidateCount = builder.clippingContext.unionPlanes.length;
  11262. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11263. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11264. builder.stack.add( hardwareClipping() );
  11265. this.hardwareClipping = true;
  11266. }
  11267. return;
  11268. }
  11269. /**
  11270. * Setups the depth of this material.
  11271. *
  11272. * @param {NodeBuilder} builder - The current node builder.
  11273. */
  11274. setupDepth( builder ) {
  11275. const { renderer, camera } = builder;
  11276. // Depth
  11277. let depthNode = this.depthNode;
  11278. if ( depthNode === null ) {
  11279. const mrt = renderer.getMRT();
  11280. if ( mrt && mrt.has( 'depth' ) ) {
  11281. depthNode = mrt.get( 'depth' );
  11282. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11283. if ( camera.isPerspectiveCamera ) {
  11284. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11285. } else {
  11286. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11287. }
  11288. }
  11289. }
  11290. if ( depthNode !== null ) {
  11291. depth.assign( depthNode ).append();
  11292. }
  11293. }
  11294. /**
  11295. * Setups the position node in view space. This method exists
  11296. * so derived node materials can modifiy the implementation e.g. sprite materials.
  11297. *
  11298. * @param {NodeBuilder} builder - The current node builder.
  11299. * @return {Node<vec3>} The position in view space.
  11300. */
  11301. setupPositionView( /*builder*/ ) {
  11302. return modelViewMatrix.mul( positionLocal ).xyz;
  11303. }
  11304. /**
  11305. * Setups the position in clip space.
  11306. *
  11307. * @param {NodeBuilder} builder - The current node builder.
  11308. * @return {Node<vec4>} The position in view space.
  11309. */
  11310. setupModelViewProjection( /*builder*/ ) {
  11311. return cameraProjectionMatrix.mul( positionView );
  11312. }
  11313. /**
  11314. * Setups the logic for the vertex stage.
  11315. *
  11316. * @param {NodeBuilder} builder - The current node builder.
  11317. * @return {Node<vec4>} The position in clip space.
  11318. */
  11319. setupVertex( builder ) {
  11320. builder.addStack();
  11321. this.setupPosition( builder );
  11322. builder.context.vertex = builder.removeStack();
  11323. return modelViewProjection;
  11324. }
  11325. /**
  11326. * Setups the computation of the position in local space.
  11327. *
  11328. * @param {NodeBuilder} builder - The current node builder.
  11329. * @return {Node<vec3>} The position in local space.
  11330. */
  11331. setupPosition( builder ) {
  11332. const { object, geometry } = builder;
  11333. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11334. morphReference( object ).append();
  11335. }
  11336. if ( object.isSkinnedMesh === true ) {
  11337. skinningReference( object ).append();
  11338. }
  11339. if ( this.displacementMap ) {
  11340. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11341. const displacementScale = materialReference( 'displacementScale', 'float' );
  11342. const displacementBias = materialReference( 'displacementBias', 'float' );
  11343. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11344. }
  11345. if ( object.isBatchedMesh ) {
  11346. batch( object ).append();
  11347. }
  11348. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11349. instancedMesh( object ).append();
  11350. }
  11351. if ( this.positionNode !== null ) {
  11352. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11353. }
  11354. return positionLocal;
  11355. }
  11356. /**
  11357. * Setups the computation of the material's diffuse color.
  11358. *
  11359. * @param {NodeBuilder} builder - The current node builder.
  11360. * @param {BufferGeometry} geometry - The geometry.
  11361. */
  11362. setupDiffuseColor( { object, geometry } ) {
  11363. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11364. // VERTEX COLORS
  11365. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11366. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11367. }
  11368. // Instanced colors
  11369. if ( object.instanceColor ) {
  11370. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11371. colorNode = instanceColor.mul( colorNode );
  11372. }
  11373. if ( object.isBatchedMesh && object._colorsTexture ) {
  11374. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11375. colorNode = batchColor.mul( colorNode );
  11376. }
  11377. // COLOR
  11378. diffuseColor.assign( colorNode );
  11379. // OPACITY
  11380. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  11381. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  11382. // ALPHA TEST
  11383. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  11384. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  11385. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  11386. }
  11387. // ALPHA HASH
  11388. if ( this.alphaHash === true ) {
  11389. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  11390. }
  11391. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  11392. diffuseColor.a.assign( 1.0 );
  11393. }
  11394. }
  11395. /**
  11396. * Abstract interface method that can be implemented by derived materials
  11397. * to setup material-specific node variables.
  11398. *
  11399. * @abstract
  11400. * @param {NodeBuilder} builder - The current node builder.
  11401. */
  11402. setupVariants( /*builder*/ ) {
  11403. // Interface function.
  11404. }
  11405. /**
  11406. * Setups the outgoing light node variable
  11407. *
  11408. * @return {Node<vec3>} The outgoing light node.
  11409. */
  11410. setupOutgoingLight() {
  11411. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  11412. }
  11413. /**
  11414. * Setups the normal node from the material.
  11415. *
  11416. * @return {Node<vec3>} The normal node.
  11417. */
  11418. setupNormal() {
  11419. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  11420. }
  11421. /**
  11422. * Setups the environment node from the material.
  11423. *
  11424. * @param {NodeBuilder} builder - The current node builder.
  11425. * @return {Node<vec4>} The environment node.
  11426. */
  11427. setupEnvironment( /*builder*/ ) {
  11428. let node = null;
  11429. if ( this.envNode ) {
  11430. node = this.envNode;
  11431. } else if ( this.envMap ) {
  11432. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  11433. }
  11434. return node;
  11435. }
  11436. /**
  11437. * Setups the light map node from the material.
  11438. *
  11439. * @param {NodeBuilder} builder - The current node builder.
  11440. * @return {Node<vec3>} The light map node.
  11441. */
  11442. setupLightMap( builder ) {
  11443. let node = null;
  11444. if ( builder.material.lightMap ) {
  11445. node = new IrradianceNode( materialLightMap );
  11446. }
  11447. return node;
  11448. }
  11449. /**
  11450. * Setups the lights node based on the scene, environment and material.
  11451. *
  11452. * @param {NodeBuilder} builder - The current node builder.
  11453. * @return {LightsNode} The lights node.
  11454. */
  11455. setupLights( builder ) {
  11456. const materialLightsNode = [];
  11457. //
  11458. const envNode = this.setupEnvironment( builder );
  11459. if ( envNode && envNode.isLightingNode ) {
  11460. materialLightsNode.push( envNode );
  11461. }
  11462. const lightMapNode = this.setupLightMap( builder );
  11463. if ( lightMapNode && lightMapNode.isLightingNode ) {
  11464. materialLightsNode.push( lightMapNode );
  11465. }
  11466. if ( this.aoNode !== null || builder.material.aoMap ) {
  11467. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  11468. materialLightsNode.push( new AONode( aoNode ) );
  11469. }
  11470. let lightsN = this.lightsNode || builder.lightsNode;
  11471. if ( materialLightsNode.length > 0 ) {
  11472. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  11473. }
  11474. return lightsN;
  11475. }
  11476. /**
  11477. * This method should be implemented by most derived materials
  11478. * since it defines the material's lighting model.
  11479. *
  11480. * @abstract
  11481. * @param {NodeBuilder} builder - The current node builder.
  11482. * @return {LightingModel} The lighting model.
  11483. */
  11484. setupLightingModel( /*builder*/ ) {
  11485. // Interface function.
  11486. }
  11487. /**
  11488. * Setups the outgoing light node.
  11489. *
  11490. * @param {NodeBuilder} builder - The current node builder.
  11491. * @return {Node<vec3>} The outgoing light node.
  11492. */
  11493. setupLighting( builder ) {
  11494. const { material } = builder;
  11495. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  11496. // OUTGOING LIGHT
  11497. const lights = this.lights === true || this.lightsNode !== null;
  11498. const lightsNode = lights ? this.setupLights( builder ) : null;
  11499. let outgoingLightNode = this.setupOutgoingLight( builder );
  11500. if ( lightsNode && lightsNode.getScope().hasLights ) {
  11501. const lightingModel = this.setupLightingModel( builder );
  11502. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  11503. } else if ( backdropNode !== null ) {
  11504. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  11505. }
  11506. // EMISSIVE
  11507. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  11508. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  11509. outgoingLightNode = outgoingLightNode.add( emissive );
  11510. }
  11511. return outgoingLightNode;
  11512. }
  11513. /**
  11514. * Setups the output node.
  11515. *
  11516. * @param {NodeBuilder} builder - The current node builder.
  11517. * @param {Node<vec4>} outputNode - The existing output node.
  11518. * @return {Node<vec4>} The output node.
  11519. */
  11520. setupOutput( builder, outputNode ) {
  11521. // FOG
  11522. if ( this.fog === true ) {
  11523. const fogNode = builder.fogNode;
  11524. if ( fogNode ) {
  11525. output.assign( outputNode );
  11526. outputNode = vec4( fogNode );
  11527. }
  11528. }
  11529. return outputNode;
  11530. }
  11531. /**
  11532. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  11533. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  11534. * defining all material properties of the classic type in the node type.
  11535. *
  11536. * @param {Material} material - The material to copy properties with their values to this node material.
  11537. */
  11538. setDefaultValues( material ) {
  11539. // This approach is to reuse the native refreshUniforms*
  11540. // and turn available the use of features like transmission and environment in core
  11541. for ( const property in material ) {
  11542. const value = material[ property ];
  11543. if ( this[ property ] === undefined ) {
  11544. this[ property ] = value;
  11545. if ( value && value.clone ) this[ property ] = value.clone();
  11546. }
  11547. }
  11548. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  11549. for ( const key in descriptors ) {
  11550. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  11551. descriptors[ key ].get !== undefined ) {
  11552. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  11553. }
  11554. }
  11555. }
  11556. /**
  11557. * Serializes this material to JSON.
  11558. *
  11559. * @param {(Object|String)?} meta - The meta information for serialization.
  11560. * @return {Object} The serialized node.
  11561. */
  11562. toJSON( meta ) {
  11563. const isRoot = ( meta === undefined || typeof meta === 'string' );
  11564. if ( isRoot ) {
  11565. meta = {
  11566. textures: {},
  11567. images: {},
  11568. nodes: {}
  11569. };
  11570. }
  11571. const data = Material.prototype.toJSON.call( this, meta );
  11572. const nodeChildren = getNodeChildren( this );
  11573. data.inputNodes = {};
  11574. for ( const { property, childNode } of nodeChildren ) {
  11575. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  11576. }
  11577. // TODO: Copied from Object3D.toJSON
  11578. function extractFromCache( cache ) {
  11579. const values = [];
  11580. for ( const key in cache ) {
  11581. const data = cache[ key ];
  11582. delete data.metadata;
  11583. values.push( data );
  11584. }
  11585. return values;
  11586. }
  11587. if ( isRoot ) {
  11588. const textures = extractFromCache( meta.textures );
  11589. const images = extractFromCache( meta.images );
  11590. const nodes = extractFromCache( meta.nodes );
  11591. if ( textures.length > 0 ) data.textures = textures;
  11592. if ( images.length > 0 ) data.images = images;
  11593. if ( nodes.length > 0 ) data.nodes = nodes;
  11594. }
  11595. return data;
  11596. }
  11597. /**
  11598. * Copies the properties of the given node material to this instance.
  11599. *
  11600. * @param {NodeMaterial} source - The material to copy.
  11601. * @return {NodeMaterial} A reference to this node material.
  11602. */
  11603. copy( source ) {
  11604. this.lightsNode = source.lightsNode;
  11605. this.envNode = source.envNode;
  11606. this.colorNode = source.colorNode;
  11607. this.normalNode = source.normalNode;
  11608. this.opacityNode = source.opacityNode;
  11609. this.backdropNode = source.backdropNode;
  11610. this.backdropAlphaNode = source.backdropAlphaNode;
  11611. this.alphaTestNode = source.alphaTestNode;
  11612. this.positionNode = source.positionNode;
  11613. this.geometryNode = source.geometryNode;
  11614. this.depthNode = source.depthNode;
  11615. this.shadowPositionNode = source.shadowPositionNode;
  11616. this.receivedShadowNode = source.receivedShadowNode;
  11617. this.castShadowNode = source.castShadowNode;
  11618. this.outputNode = source.outputNode;
  11619. this.mrtNode = source.mrtNode;
  11620. this.fragmentNode = source.fragmentNode;
  11621. this.vertexNode = source.vertexNode;
  11622. return super.copy( source );
  11623. }
  11624. }
  11625. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  11626. /**
  11627. * Unlike WebGL, WebGPU can render point primitives only with a size
  11628. * of one pixel. This type node material can be used to mimic the WebGL
  11629. * points rendering by rendering small planes via instancing.
  11630. *
  11631. * This material should be used with {@link InstancedPointsGeometry}.
  11632. *
  11633. * @augments NodeMaterial
  11634. */
  11635. class InstancedPointsNodeMaterial extends NodeMaterial {
  11636. static get type() {
  11637. return 'InstancedPointsNodeMaterial';
  11638. }
  11639. /**
  11640. * Constructs a new instanced points node material.
  11641. *
  11642. * @param {Object?} parameters - The configuration parameter.
  11643. */
  11644. constructor( parameters = {} ) {
  11645. super();
  11646. /**
  11647. * This flag can be used for type testing.
  11648. *
  11649. * @type {Boolean}
  11650. * @readonly
  11651. * @default true
  11652. */
  11653. this.isInstancedPointsNodeMaterial = true;
  11654. /**
  11655. * Whether vertex colors should be used or not. If set to `true`,
  11656. * each point instance can receive a custom color value.
  11657. *
  11658. * @type {Boolean}
  11659. * @default false
  11660. */
  11661. this.useColor = parameters.vertexColors;
  11662. /**
  11663. * The points width in pixels.
  11664. *
  11665. * @type {Number}
  11666. * @default 1
  11667. */
  11668. this.pointWidth = 1;
  11669. /**
  11670. * This node can be used to define the colors for each instance.
  11671. *
  11672. * @type {Node<vec3>?}
  11673. * @default null
  11674. */
  11675. this.pointColorNode = null;
  11676. /**
  11677. * This node can be used to define the width for each point instance.
  11678. *
  11679. * @type {Node<float>?}
  11680. * @default null
  11681. */
  11682. this.pointWidthNode = null;
  11683. this._useAlphaToCoverage = true;
  11684. this.setDefaultValues( _defaultValues$e );
  11685. this.setValues( parameters );
  11686. }
  11687. /**
  11688. * Setups the vertex and fragment stage of this node material.
  11689. *
  11690. * @param {NodeBuilder} builder - The current node builder.
  11691. */
  11692. setup( builder ) {
  11693. const { renderer } = builder;
  11694. const useAlphaToCoverage = this._useAlphaToCoverage;
  11695. const useColor = this.useColor;
  11696. this.vertexNode = Fn( () => {
  11697. const instancePosition = attribute( 'instancePosition' ).xyz;
  11698. // camera space
  11699. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  11700. const aspect = viewport.z.div( viewport.w );
  11701. // clip space
  11702. const clipPos = cameraProjectionMatrix.mul( mvPos );
  11703. // offset in ndc space
  11704. const offset = positionGeometry.xy.toVar();
  11705. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  11706. offset.assign( offset.div( viewport.z ) );
  11707. offset.y.assign( offset.y.mul( aspect ) );
  11708. // back to clip space
  11709. offset.assign( offset.mul( clipPos.w ) );
  11710. //clipPos.xy += offset;
  11711. clipPos.addAssign( vec4( offset, 0, 0 ) );
  11712. return clipPos;
  11713. } )();
  11714. this.fragmentNode = Fn( () => {
  11715. const alpha = float( 1 ).toVar();
  11716. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  11717. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  11718. const dlen = float( len2.fwidth() ).toVar();
  11719. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  11720. } else {
  11721. len2.greaterThan( 1.0 ).discard();
  11722. }
  11723. let pointColorNode;
  11724. if ( this.pointColorNode ) {
  11725. pointColorNode = this.pointColorNode;
  11726. } else {
  11727. if ( useColor ) {
  11728. const instanceColor = attribute( 'instanceColor' );
  11729. pointColorNode = instanceColor.mul( materialColor );
  11730. } else {
  11731. pointColorNode = materialColor;
  11732. }
  11733. }
  11734. alpha.mulAssign( materialOpacity );
  11735. return vec4( pointColorNode, alpha );
  11736. } )();
  11737. super.setup( builder );
  11738. }
  11739. /**
  11740. * Whether alpha to coverage should be used or not.
  11741. *
  11742. * @type {Boolean}
  11743. * @default true
  11744. */
  11745. get alphaToCoverage() {
  11746. return this._useAlphaToCoverage;
  11747. }
  11748. set alphaToCoverage( value ) {
  11749. if ( this._useAlphaToCoverage !== value ) {
  11750. this._useAlphaToCoverage = value;
  11751. this.needsUpdate = true;
  11752. }
  11753. }
  11754. }
  11755. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  11756. /**
  11757. * Node material version of `LineBasicMaterial`.
  11758. *
  11759. * @augments NodeMaterial
  11760. */
  11761. class LineBasicNodeMaterial extends NodeMaterial {
  11762. static get type() {
  11763. return 'LineBasicNodeMaterial';
  11764. }
  11765. /**
  11766. * Constructs a new line basic node material.
  11767. *
  11768. * @param {Object?} parameters - The configuration parameter.
  11769. */
  11770. constructor( parameters ) {
  11771. super();
  11772. /**
  11773. * This flag can be used for type testing.
  11774. *
  11775. * @type {Boolean}
  11776. * @readonly
  11777. * @default true
  11778. */
  11779. this.isLineBasicNodeMaterial = true;
  11780. this.setDefaultValues( _defaultValues$d );
  11781. this.setValues( parameters );
  11782. }
  11783. }
  11784. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  11785. /**
  11786. * Node material version of `LineDashedMaterial`.
  11787. *
  11788. * @augments NodeMaterial
  11789. */
  11790. class LineDashedNodeMaterial extends NodeMaterial {
  11791. static get type() {
  11792. return 'LineDashedNodeMaterial';
  11793. }
  11794. /**
  11795. * Constructs a new line dashed node material.
  11796. *
  11797. * @param {Object?} parameters - The configuration parameter.
  11798. */
  11799. constructor( parameters ) {
  11800. super();
  11801. /**
  11802. * This flag can be used for type testing.
  11803. *
  11804. * @type {Boolean}
  11805. * @readonly
  11806. * @default true
  11807. */
  11808. this.isLineDashedNodeMaterial = true;
  11809. this.setDefaultValues( _defaultValues$c );
  11810. /**
  11811. * The dash offset.
  11812. *
  11813. * @type {Number}
  11814. * @default 0
  11815. */
  11816. this.dashOffset = 0;
  11817. /**
  11818. * The offset of dash materials is by default inferred from the `dashOffset`
  11819. * property. This node property allows to overwrite the default
  11820. * and define the offset with a node instead.
  11821. *
  11822. * If you don't want to overwrite the offset but modify the existing
  11823. * value instead, use {@link module:MaterialNode.materialLineDashOffset}.
  11824. *
  11825. * @type {Node<float>?}
  11826. * @default null
  11827. */
  11828. this.offsetNode = null;
  11829. /**
  11830. * The scale of dash materials is by default inferred from the `scale`
  11831. * property. This node property allows to overwrite the default
  11832. * and define the scale with a node instead.
  11833. *
  11834. * If you don't want to overwrite the scale but modify the existing
  11835. * value instead, use {@link module:MaterialNode.materialLineScale}.
  11836. *
  11837. * @type {Node<float>?}
  11838. * @default null
  11839. */
  11840. this.dashScaleNode = null;
  11841. /**
  11842. * The dash size of dash materials is by default inferred from the `dashSize`
  11843. * property. This node property allows to overwrite the default
  11844. * and define the dash size with a node instead.
  11845. *
  11846. * If you don't want to overwrite the dash size but modify the existing
  11847. * value instead, use {@link module:MaterialNode.materialLineDashSize}.
  11848. *
  11849. * @type {Node<float>?}
  11850. * @default null
  11851. */
  11852. this.dashSizeNode = null;
  11853. /**
  11854. * The gap size of dash materials is by default inferred from the `gapSize`
  11855. * property. This node property allows to overwrite the default
  11856. * and define the gap size with a node instead.
  11857. *
  11858. * If you don't want to overwrite the gap size but modify the existing
  11859. * value instead, use {@link module:MaterialNode.materialLineGapSize}.
  11860. *
  11861. * @type {Node<float>?}
  11862. * @default null
  11863. */
  11864. this.gapSizeNode = null;
  11865. this.setValues( parameters );
  11866. }
  11867. /**
  11868. * Setups the dash specific node variables.
  11869. *
  11870. * @param {NodeBuilder} builder - The current node builder.
  11871. */
  11872. setupVariants( /* builder */ ) {
  11873. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  11874. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  11875. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  11876. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  11877. dashSize.assign( dashSizeNode );
  11878. gapSize.assign( gapSizeNode );
  11879. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  11880. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  11881. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  11882. }
  11883. }
  11884. /** @module ViewportSharedTextureNode **/
  11885. let _sharedFramebuffer = null;
  11886. /**
  11887. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  11888. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  11889. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  11890. *
  11891. * @augments module:ViewportTextureNode~ViewportTextureNode
  11892. */
  11893. class ViewportSharedTextureNode extends ViewportTextureNode {
  11894. static get type() {
  11895. return 'ViewportSharedTextureNode';
  11896. }
  11897. /**
  11898. * Constructs a new viewport shared texture node.
  11899. *
  11900. * @param {Node} [uvNode=screenUV] - The uv node.
  11901. * @param {Node?} [levelNode=null] - The level node.
  11902. */
  11903. constructor( uvNode = screenUV, levelNode = null ) {
  11904. if ( _sharedFramebuffer === null ) {
  11905. _sharedFramebuffer = new FramebufferTexture();
  11906. }
  11907. super( uvNode, levelNode, _sharedFramebuffer );
  11908. }
  11909. updateReference() {
  11910. return this;
  11911. }
  11912. }
  11913. /**
  11914. * TSL function for creating a shared viewport texture node.
  11915. *
  11916. * @function
  11917. * @param {Node} [uvNode=screenUV] - The uv node.
  11918. * @param {Node?} [levelNode=null] - The level node.
  11919. * @returns {ViewportSharedTextureNode}
  11920. */
  11921. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  11922. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  11923. /**
  11924. * This node material can be used to render lines with a size larger than one
  11925. * by representing them as instanced meshes.
  11926. *
  11927. * @augments NodeMaterial
  11928. */
  11929. class Line2NodeMaterial extends NodeMaterial {
  11930. static get type() {
  11931. return 'Line2NodeMaterial';
  11932. }
  11933. /**
  11934. * Constructs a new node material for wide line rendering.
  11935. *
  11936. * @param {Object?} parameters - The configuration parameter.
  11937. */
  11938. constructor( parameters = {} ) {
  11939. super();
  11940. /**
  11941. * This flag can be used for type testing.
  11942. *
  11943. * @type {Boolean}
  11944. * @readonly
  11945. * @default true
  11946. */
  11947. this.isLine2NodeMaterial = true;
  11948. this.setDefaultValues( _defaultValues$b );
  11949. /**
  11950. * Whether vertex colors should be used or not.
  11951. *
  11952. * @type {Boolean}
  11953. * @default false
  11954. */
  11955. this.useColor = parameters.vertexColors;
  11956. /**
  11957. * The dash offset.
  11958. *
  11959. * @type {Number}
  11960. * @default 0
  11961. */
  11962. this.dashOffset = 0;
  11963. /**
  11964. * The line width.
  11965. *
  11966. * @type {Number}
  11967. * @default 0
  11968. */
  11969. this.lineWidth = 1;
  11970. /**
  11971. * Defines the lines color.
  11972. *
  11973. * @type {Node<vec3>?}
  11974. * @default null
  11975. */
  11976. this.lineColorNode = null;
  11977. /**
  11978. * Defines the offset.
  11979. *
  11980. * @type {Node<float>?}
  11981. * @default null
  11982. */
  11983. this.offsetNode = null;
  11984. /**
  11985. * Defines the dash scale.
  11986. *
  11987. * @type {Node<float>?}
  11988. * @default null
  11989. */
  11990. this.dashScaleNode = null;
  11991. /**
  11992. * Defines the dash size.
  11993. *
  11994. * @type {Node<float>?}
  11995. * @default null
  11996. */
  11997. this.dashSizeNode = null;
  11998. /**
  11999. * Defines the gap size.
  12000. *
  12001. * @type {Node<float>?}
  12002. * @default null
  12003. */
  12004. this.gapSizeNode = null;
  12005. /**
  12006. * Blending is set to `NoBlending` since transparency
  12007. * is not supported, yet.
  12008. *
  12009. * @type {Number}
  12010. * @default 0
  12011. */
  12012. this.blending = NoBlending;
  12013. this._useDash = parameters.dashed;
  12014. this._useAlphaToCoverage = true;
  12015. this._useWorldUnits = false;
  12016. this.setValues( parameters );
  12017. }
  12018. /**
  12019. * Setups the vertex and fragment stage of this node material.
  12020. *
  12021. * @param {NodeBuilder} builder - The current node builder.
  12022. */
  12023. setup( builder ) {
  12024. const { renderer } = builder;
  12025. const useAlphaToCoverage = this._useAlphaToCoverage;
  12026. const useColor = this.useColor;
  12027. const useDash = this._useDash;
  12028. const useWorldUnits = this._useWorldUnits;
  12029. const trimSegment = Fn( ( { start, end } ) => {
  12030. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12031. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12032. const nearEstimate = b.mul( - 0.5 ).div( a );
  12033. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12034. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12035. } ).setLayout( {
  12036. name: 'trimSegment',
  12037. type: 'vec4',
  12038. inputs: [
  12039. { name: 'start', type: 'vec4' },
  12040. { name: 'end', type: 'vec4' }
  12041. ]
  12042. } );
  12043. this.vertexNode = Fn( () => {
  12044. const instanceStart = attribute( 'instanceStart' );
  12045. const instanceEnd = attribute( 'instanceEnd' );
  12046. // camera space
  12047. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12048. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12049. if ( useDash ) {
  12050. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12051. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12052. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12053. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12054. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12055. lineDistance = lineDistance.add( offsetNode );
  12056. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12057. }
  12058. if ( useWorldUnits ) {
  12059. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12060. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12061. }
  12062. const aspect = viewport.z.div( viewport.w );
  12063. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12064. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12065. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12066. // perhaps there is a more elegant solution -- WestLangley
  12067. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  12068. If( perspective, () => {
  12069. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12070. end.assign( trimSegment( { start: start, end: end } ) );
  12071. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12072. start.assign( trimSegment( { start: end, end: start } ) );
  12073. } );
  12074. } );
  12075. // clip space
  12076. const clipStart = cameraProjectionMatrix.mul( start );
  12077. const clipEnd = cameraProjectionMatrix.mul( end );
  12078. // ndc space
  12079. const ndcStart = clipStart.xyz.div( clipStart.w );
  12080. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12081. // direction
  12082. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12083. // account for clip-space aspect ratio
  12084. dir.x.assign( dir.x.mul( aspect ) );
  12085. dir.assign( dir.normalize() );
  12086. const clip = vec4().toVar();
  12087. if ( useWorldUnits ) {
  12088. // get the offset direction as perpendicular to the view vector
  12089. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12090. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12091. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12092. const worldFwd = worldDir.cross( worldUp );
  12093. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12094. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12095. // height offset
  12096. const hw = materialLineWidth.mul( 0.5 );
  12097. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12098. // don't extend the line if we're rendering dashes because we
  12099. // won't be rendering the endcaps
  12100. if ( ! useDash ) {
  12101. // cap extension
  12102. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12103. // add width to the box
  12104. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12105. // endcaps
  12106. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12107. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12108. } );
  12109. }
  12110. // project the worldpos
  12111. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12112. // shift the depth of the projected points so the line
  12113. // segments overlap neatly
  12114. const clipPose = vec3().toVar();
  12115. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12116. clip.z.assign( clipPose.z.mul( clip.w ) );
  12117. } else {
  12118. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12119. // undo aspect ratio adjustment
  12120. dir.x.assign( dir.x.div( aspect ) );
  12121. offset.x.assign( offset.x.div( aspect ) );
  12122. // sign flip
  12123. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12124. // endcaps
  12125. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12126. offset.assign( offset.sub( dir ) );
  12127. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12128. offset.assign( offset.add( dir ) );
  12129. } );
  12130. // adjust for linewidth
  12131. offset.assign( offset.mul( materialLineWidth ) );
  12132. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12133. offset.assign( offset.div( viewport.w ) );
  12134. // select end
  12135. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12136. // back to clip space
  12137. offset.assign( offset.mul( clip.w ) );
  12138. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12139. }
  12140. return clip;
  12141. } )();
  12142. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12143. const p13 = p1.sub( p3 );
  12144. const p43 = p4.sub( p3 );
  12145. const p21 = p2.sub( p1 );
  12146. const d1343 = p13.dot( p43 );
  12147. const d4321 = p43.dot( p21 );
  12148. const d1321 = p13.dot( p21 );
  12149. const d4343 = p43.dot( p43 );
  12150. const d2121 = p21.dot( p21 );
  12151. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12152. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12153. const mua = numer.div( denom ).clamp();
  12154. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12155. return vec2( mua, mub );
  12156. } );
  12157. this.colorNode = Fn( () => {
  12158. const vUv = uv();
  12159. if ( useDash ) {
  12160. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12161. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12162. dashSize.assign( dashSizeNode );
  12163. gapSize.assign( gapSizeNode );
  12164. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12165. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12166. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12167. }
  12168. const alpha = float( 1 ).toVar( 'alpha' );
  12169. if ( useWorldUnits ) {
  12170. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12171. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12172. // Find the closest points on the view ray and the line segment
  12173. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12174. const lineDir = worldEnd.sub( worldStart );
  12175. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12176. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12177. const p2 = rayEnd.mul( params.y );
  12178. const delta = p1.sub( p2 );
  12179. const len = delta.length();
  12180. const norm = len.div( materialLineWidth );
  12181. if ( ! useDash ) {
  12182. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12183. const dnorm = norm.fwidth();
  12184. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12185. } else {
  12186. norm.greaterThan( 0.5 ).discard();
  12187. }
  12188. }
  12189. } else {
  12190. // round endcaps
  12191. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12192. const a = vUv.x;
  12193. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12194. const len2 = a.mul( a ).add( b.mul( b ) );
  12195. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12196. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12197. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12198. } );
  12199. } else {
  12200. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12201. const a = vUv.x;
  12202. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12203. const len2 = a.mul( a ).add( b.mul( b ) );
  12204. len2.greaterThan( 1.0 ).discard();
  12205. } );
  12206. }
  12207. }
  12208. let lineColorNode;
  12209. if ( this.lineColorNode ) {
  12210. lineColorNode = this.lineColorNode;
  12211. } else {
  12212. if ( useColor ) {
  12213. const instanceColorStart = attribute( 'instanceColorStart' );
  12214. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12215. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12216. lineColorNode = instanceColor.mul( materialColor );
  12217. } else {
  12218. lineColorNode = materialColor;
  12219. }
  12220. }
  12221. return vec4( lineColorNode, alpha );
  12222. } )();
  12223. if ( this.transparent ) {
  12224. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12225. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12226. }
  12227. super.setup( builder );
  12228. }
  12229. /**
  12230. * Whether the lines should sized in world units or not.
  12231. * When set to `false` the unit is pixel.
  12232. *
  12233. * @type {Boolean}
  12234. * @default false
  12235. */
  12236. get worldUnits() {
  12237. return this._useWorldUnits;
  12238. }
  12239. set worldUnits( value ) {
  12240. if ( this._useWorldUnits !== value ) {
  12241. this._useWorldUnits = value;
  12242. this.needsUpdate = true;
  12243. }
  12244. }
  12245. /**
  12246. * Whether the lines should be dashed or not.
  12247. *
  12248. * @type {Boolean}
  12249. * @default false
  12250. */
  12251. get dashed() {
  12252. return this._useDash;
  12253. }
  12254. set dashed( value ) {
  12255. if ( this._useDash !== value ) {
  12256. this._useDash = value;
  12257. this.needsUpdate = true;
  12258. }
  12259. }
  12260. /**
  12261. * Whether alpha to coverage should be used or not.
  12262. *
  12263. * @type {Boolean}
  12264. * @default true
  12265. */
  12266. get alphaToCoverage() {
  12267. return this._useAlphaToCoverage;
  12268. }
  12269. set alphaToCoverage( value ) {
  12270. if ( this._useAlphaToCoverage !== value ) {
  12271. this._useAlphaToCoverage = value;
  12272. this.needsUpdate = true;
  12273. }
  12274. }
  12275. }
  12276. /** @module Packing **/
  12277. /**
  12278. * Packs a direction vector into a color value.
  12279. *
  12280. * @method
  12281. * @param {Node<vec3>} node - The direction to pack.
  12282. * @return {Node<vec3>} The color.
  12283. */
  12284. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12285. /**
  12286. * Unpacks a color value into a direction vector.
  12287. *
  12288. * @method
  12289. * @param {Node<vec3>} node - The color to unpack.
  12290. * @return {Node<vec3>} The direction.
  12291. */
  12292. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12293. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12294. /**
  12295. * Node material version of `MeshNormalMaterial`.
  12296. *
  12297. * @augments NodeMaterial
  12298. */
  12299. class MeshNormalNodeMaterial extends NodeMaterial {
  12300. static get type() {
  12301. return 'MeshNormalNodeMaterial';
  12302. }
  12303. /**
  12304. * Constructs a new mesh normal node material.
  12305. *
  12306. * @param {Object?} parameters - The configuration parameter.
  12307. */
  12308. constructor( parameters ) {
  12309. super();
  12310. /**
  12311. * This flag can be used for type testing.
  12312. *
  12313. * @type {Boolean}
  12314. * @readonly
  12315. * @default true
  12316. */
  12317. this.isMeshNormalNodeMaterial = true;
  12318. this.setDefaultValues( _defaultValues$a );
  12319. this.setValues( parameters );
  12320. }
  12321. /**
  12322. * Overwrites the default implementation by computing the diffuse color
  12323. * based on the normal data.
  12324. */
  12325. setupDiffuseColor() {
  12326. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12327. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12328. }
  12329. }
  12330. /** @module EquirectUVNode **/
  12331. /**
  12332. * Can be used to compute texture coordinates for projecting an
  12333. * equirectangular texture onto a mesh for using it as the scene's
  12334. * background.
  12335. *
  12336. * ```js
  12337. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12338. * ```
  12339. *
  12340. * @augments TempNode
  12341. */
  12342. class EquirectUVNode extends TempNode {
  12343. static get type() {
  12344. return 'EquirectUVNode';
  12345. }
  12346. /**
  12347. * Constructs a new equirect uv node.
  12348. *
  12349. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12350. */
  12351. constructor( dirNode = positionWorldDirection ) {
  12352. super( 'vec2' );
  12353. /**
  12354. * A direction vector for sampling why is by default `positionWorldDirection`.
  12355. *
  12356. * @type {Node<vec3>}
  12357. */
  12358. this.dirNode = dirNode;
  12359. }
  12360. setup() {
  12361. const dir = this.dirNode;
  12362. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12363. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12364. return vec2( u, v );
  12365. }
  12366. }
  12367. /**
  12368. * TSL function for creating an equirect uv node.
  12369. *
  12370. * @function
  12371. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12372. * @returns {EquirectUVNode}
  12373. */
  12374. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12375. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12376. /**
  12377. * This class represents a cube render target. It is a special version
  12378. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12379. *
  12380. * @augments WebGLCubeRenderTarget
  12381. */
  12382. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12383. constructor( size = 1, options = {} ) {
  12384. super( size, options );
  12385. this.isCubeRenderTarget = true;
  12386. }
  12387. /**
  12388. * Converts the given equirectangular texture to a cube map.
  12389. *
  12390. * @param {Renderer} renderer - The renderer.
  12391. * @param {Texture} texture - The equirectangular texture.
  12392. * @return {CubeRenderTarget} A reference to this cube render target.
  12393. */
  12394. fromEquirectangularTexture( renderer, texture$1 ) {
  12395. const currentMinFilter = texture$1.minFilter;
  12396. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12397. texture$1.generateMipmaps = true;
  12398. this.texture.type = texture$1.type;
  12399. this.texture.colorSpace = texture$1.colorSpace;
  12400. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12401. this.texture.minFilter = texture$1.minFilter;
  12402. this.texture.magFilter = texture$1.magFilter;
  12403. const geometry = new BoxGeometry( 5, 5, 5 );
  12404. const uvNode = equirectUV( positionWorldDirection );
  12405. const material = new NodeMaterial();
  12406. material.colorNode = texture( texture$1, uvNode, 0 );
  12407. material.side = BackSide;
  12408. material.blending = NoBlending;
  12409. const mesh = new Mesh( geometry, material );
  12410. const scene = new Scene();
  12411. scene.add( mesh );
  12412. // Avoid blurred poles
  12413. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12414. const camera = new CubeCamera( 1, 10, this );
  12415. const currentMRT = renderer.getMRT();
  12416. renderer.setMRT( null );
  12417. camera.update( renderer, scene );
  12418. renderer.setMRT( currentMRT );
  12419. texture$1.minFilter = currentMinFilter;
  12420. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12421. mesh.geometry.dispose();
  12422. mesh.material.dispose();
  12423. return this;
  12424. }
  12425. }
  12426. /** @module CubeMapNode **/
  12427. const _cache$1 = new WeakMap();
  12428. /**
  12429. * This node can be used to automatically convert environment maps in the
  12430. * equirectangular format into the cube map format.
  12431. *
  12432. * @augments TempNode
  12433. */
  12434. class CubeMapNode extends TempNode {
  12435. static get type() {
  12436. return 'CubeMapNode';
  12437. }
  12438. /**
  12439. * Constructs a new cube map node.
  12440. *
  12441. * @param {Node} envNode - The node representing the environment map.
  12442. */
  12443. constructor( envNode ) {
  12444. super( 'vec3' );
  12445. /**
  12446. * The node representing the environment map.
  12447. *
  12448. * @type {Node}
  12449. */
  12450. this.envNode = envNode;
  12451. /**
  12452. * A reference to the internal cube texture.
  12453. *
  12454. * @private
  12455. * @type {CubeTexture}
  12456. * @default null
  12457. */
  12458. this._cubeTexture = null;
  12459. /**
  12460. * A reference to the internal cube texture node.
  12461. *
  12462. * @private
  12463. * @type {CubeTextureNode}
  12464. */
  12465. this._cubeTextureNode = cubeTexture();
  12466. const defaultTexture = new CubeTexture();
  12467. defaultTexture.isRenderTargetTexture = true;
  12468. /**
  12469. * A default cube texture that acts as a placeholder.
  12470. * It is used when the conversion from equirectangular to cube
  12471. * map has not finished yet for a given texture.
  12472. *
  12473. * @private
  12474. * @type {CubeTexture}
  12475. */
  12476. this._defaultTexture = defaultTexture;
  12477. /**
  12478. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12479. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12480. *
  12481. * @type {String}
  12482. * @default 'render'
  12483. */
  12484. this.updateBeforeType = NodeUpdateType.RENDER;
  12485. }
  12486. updateBefore( frame ) {
  12487. const { renderer, material } = frame;
  12488. const envNode = this.envNode;
  12489. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12490. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12491. if ( texture && texture.isTexture ) {
  12492. const mapping = texture.mapping;
  12493. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12494. // check for converted cubemap map
  12495. if ( _cache$1.has( texture ) ) {
  12496. const cubeMap = _cache$1.get( texture );
  12497. mapTextureMapping( cubeMap, texture.mapping );
  12498. this._cubeTexture = cubeMap;
  12499. } else {
  12500. // create cube map from equirectangular map
  12501. const image = texture.image;
  12502. if ( isEquirectangularMapReady$1( image ) ) {
  12503. const renderTarget = new CubeRenderTarget( image.height );
  12504. renderTarget.fromEquirectangularTexture( renderer, texture );
  12505. mapTextureMapping( renderTarget.texture, texture.mapping );
  12506. this._cubeTexture = renderTarget.texture;
  12507. _cache$1.set( texture, renderTarget.texture );
  12508. texture.addEventListener( 'dispose', onTextureDispose );
  12509. } else {
  12510. // default cube texture as fallback when equirectangular texture is not yet loaded
  12511. this._cubeTexture = this._defaultTexture;
  12512. }
  12513. }
  12514. //
  12515. this._cubeTextureNode.value = this._cubeTexture;
  12516. } else {
  12517. // envNode already refers to a cube map
  12518. this._cubeTextureNode = this.envNode;
  12519. }
  12520. }
  12521. }
  12522. }
  12523. setup( builder ) {
  12524. this.updateBefore( builder );
  12525. return this._cubeTextureNode;
  12526. }
  12527. }
  12528. /**
  12529. * Returns true if the given equirectangular image has been fully loaded
  12530. * and is ready for further processing.
  12531. *
  12532. * @private
  12533. * @param {Image} image - The equirectangular image to check.
  12534. * @return {Boolean} Whether the image is ready or not.
  12535. */
  12536. function isEquirectangularMapReady$1( image ) {
  12537. if ( image === null || image === undefined ) return false;
  12538. return image.height > 0;
  12539. }
  12540. /**
  12541. * This function is executed when `dispose()` is called on the equirectangular
  12542. * texture. In this case, the generated cube map with its render target
  12543. * is deleted as well.
  12544. *
  12545. * @private
  12546. * @param {Object} event - The event object.
  12547. */
  12548. function onTextureDispose( event ) {
  12549. const texture = event.target;
  12550. texture.removeEventListener( 'dispose', onTextureDispose );
  12551. const renderTarget = _cache$1.get( texture );
  12552. if ( renderTarget !== undefined ) {
  12553. _cache$1.delete( texture );
  12554. renderTarget.dispose();
  12555. }
  12556. }
  12557. /**
  12558. * This function makes sure the generated cube map uses the correct
  12559. * texture mapping that corresponds to the equirectangular original.
  12560. *
  12561. * @private
  12562. * @param {Texture} texture - The cube texture.
  12563. * @param {Number} mapping - The original texture mapping.
  12564. */
  12565. function mapTextureMapping( texture, mapping ) {
  12566. if ( mapping === EquirectangularReflectionMapping ) {
  12567. texture.mapping = CubeReflectionMapping;
  12568. } else if ( mapping === EquirectangularRefractionMapping ) {
  12569. texture.mapping = CubeRefractionMapping;
  12570. }
  12571. }
  12572. /**
  12573. * TSL function for creating a cube map node.
  12574. *
  12575. * @function
  12576. * @param {Node} envNode - The node representing the environment map.
  12577. * @returns {CubeMapNode}
  12578. */
  12579. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  12580. /**
  12581. * Represents a basic model for Image-based lighting (IBL). The environment
  12582. * is defined via environment maps in the equirectangular or cube map format.
  12583. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  12584. * or {@link MeshPhongNodeMaterial}.
  12585. *
  12586. * @augments LightingNode
  12587. */
  12588. class BasicEnvironmentNode extends LightingNode {
  12589. static get type() {
  12590. return 'BasicEnvironmentNode';
  12591. }
  12592. /**
  12593. * Constructs a new basic environment node.
  12594. *
  12595. * @param {Node} [envNode=null] - A node representing the environment.
  12596. */
  12597. constructor( envNode = null ) {
  12598. super();
  12599. /**
  12600. * A node representing the environment.
  12601. *
  12602. * @type {Node}
  12603. * @default null
  12604. */
  12605. this.envNode = envNode;
  12606. }
  12607. setup( builder ) {
  12608. // environment property is used in the finish() method of BasicLightingModel
  12609. builder.context.environment = cubeMapNode( this.envNode );
  12610. }
  12611. }
  12612. /**
  12613. * A specific version of {@link IrradianceNode} that is only relevant
  12614. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  12615. * requires a special scaling factor for the light map.
  12616. *
  12617. * @augments LightingNode
  12618. */
  12619. class BasicLightMapNode extends LightingNode {
  12620. static get type() {
  12621. return 'BasicLightMapNode';
  12622. }
  12623. /**
  12624. * Constructs a new basic light map node.
  12625. *
  12626. * @param {Node<vec3>?} [lightMapNode=null] - The light map node.
  12627. */
  12628. constructor( lightMapNode = null ) {
  12629. super();
  12630. /**
  12631. * The light map node.
  12632. *
  12633. * @type {Node<vec3>?}
  12634. */
  12635. this.lightMapNode = lightMapNode;
  12636. }
  12637. setup( builder ) {
  12638. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  12639. const RECIPROCAL_PI = float( 1 / Math.PI );
  12640. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  12641. }
  12642. }
  12643. /**
  12644. * Abstract class for implementing lighting models. The module defines
  12645. * multiple methods that concrete lighting models can implement. These
  12646. * methods are executed at different points during the light evaluation
  12647. * process.
  12648. */
  12649. class LightingModel {
  12650. /**
  12651. * This method is intended for setting up lighting model and context data
  12652. * which are later used in the evaluation process.
  12653. *
  12654. * @abstract
  12655. * @param {ContextNode} input - The current node context.
  12656. * @param {StackNode} stack - The current stack.
  12657. * @param {NodeBuilder} builder - The current node builder.
  12658. */
  12659. start( /*input, stack, builder*/ ) { }
  12660. /**
  12661. * This method is intended for executing final tasks like final updates
  12662. * to the outgoing light.
  12663. *
  12664. * @abstract
  12665. * @param {ContextNode} input - The current node context.
  12666. * @param {StackNode} stack - The current stack.
  12667. * @param {NodeBuilder} builder - The current node builder.
  12668. */
  12669. finish( /*input, stack, builder*/ ) { }
  12670. /**
  12671. * This method is intended for implementing the direct light term and
  12672. * executed during the build process of directional, point and spot light nodes.
  12673. *
  12674. * @abstract
  12675. * @param {Object} input - The input data.
  12676. * @param {StackNode} stack - The current stack.
  12677. * @param {NodeBuilder} builder - The current node builder.
  12678. */
  12679. direct( /*input, stack, builder*/ ) { }
  12680. /**
  12681. * This method is intended for implementing the direct light term for
  12682. * rect area light nodes.
  12683. *
  12684. * @abstract
  12685. * @param {Object} input - The input data.
  12686. * @param {StackNode} stack - The current stack.
  12687. * @param {NodeBuilder} builder - The current node builder.
  12688. */
  12689. directRectArea( /*input, stack, builder*/ ) {}
  12690. /**
  12691. * This method is intended for implementing the indirect light term.
  12692. *
  12693. * @abstract
  12694. * @param {ContextNode} input - The current node context.
  12695. * @param {StackNode} stack - The current stack.
  12696. * @param {NodeBuilder} builder - The current node builder.
  12697. */
  12698. indirect( /*input, stack, builder*/ ) { }
  12699. /**
  12700. * This method is intended for implementing the ambient occlusion term.
  12701. * Unlike other methods, this method must be called manually by the lighting
  12702. * model in its indirect term.
  12703. *
  12704. * @abstract
  12705. * @param {ContextNode} input - The current node context.
  12706. * @param {StackNode} stack - The current stack.
  12707. * @param {NodeBuilder} builder - The current node builder.
  12708. */
  12709. ambientOcclusion( /*input, stack, builder*/ ) { }
  12710. }
  12711. /**
  12712. * Represents the lighting model for unlit materials. The only light contribution
  12713. * is baked indirect lighting modulated with ambient occlusion and the material's
  12714. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  12715. *
  12716. * @augments LightingModel
  12717. */
  12718. class BasicLightingModel extends LightingModel {
  12719. /**
  12720. * Constructs a new basic lighting model.
  12721. */
  12722. constructor() {
  12723. super();
  12724. }
  12725. /**
  12726. * Implements the baked indirect lighting with its modulation.
  12727. *
  12728. * @param {ContextNode} context - The current node context.
  12729. * @param {StackNode} stack - The current stack.
  12730. * @param {NodeBuilder} builder - The current node builder.
  12731. */
  12732. indirect( context, stack, builder ) {
  12733. const ambientOcclusion = context.ambientOcclusion;
  12734. const reflectedLight = context.reflectedLight;
  12735. const irradianceLightMap = builder.context.irradianceLightMap;
  12736. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  12737. // accumulation (baked indirect lighting only)
  12738. if ( irradianceLightMap ) {
  12739. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  12740. } else {
  12741. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  12742. }
  12743. // modulation
  12744. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12745. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  12746. }
  12747. /**
  12748. * Implements the environment mapping.
  12749. *
  12750. * @param {ContextNode} context - The current node context.
  12751. * @param {StackNode} stack - The current stack.
  12752. * @param {NodeBuilder} builder - The current node builder.
  12753. */
  12754. finish( context, stack, builder ) {
  12755. const material = builder.material;
  12756. const outgoingLight = context.outgoingLight;
  12757. const envNode = builder.context.environment;
  12758. if ( envNode ) {
  12759. switch ( material.combine ) {
  12760. case MultiplyOperation:
  12761. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  12762. break;
  12763. case MixOperation:
  12764. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  12765. break;
  12766. case AddOperation:
  12767. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  12768. break;
  12769. default:
  12770. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  12771. break;
  12772. }
  12773. }
  12774. }
  12775. }
  12776. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  12777. /**
  12778. * Node material version of `MeshBasicMaterial`.
  12779. *
  12780. * @augments NodeMaterial
  12781. */
  12782. class MeshBasicNodeMaterial extends NodeMaterial {
  12783. static get type() {
  12784. return 'MeshBasicNodeMaterial';
  12785. }
  12786. /**
  12787. * Constructs a new mesh basic node material.
  12788. *
  12789. * @param {Object?} parameters - The configuration parameter.
  12790. */
  12791. constructor( parameters ) {
  12792. super();
  12793. /**
  12794. * This flag can be used for type testing.
  12795. *
  12796. * @type {Boolean}
  12797. * @readonly
  12798. * @default true
  12799. */
  12800. this.isMeshBasicNodeMaterial = true;
  12801. /**
  12802. * Although the basic material is by definition unlit, we set
  12803. * this property to `true` since we use a lighting model to compute
  12804. * the outgoing light of the fragment shader.
  12805. *
  12806. * @type {Boolean}
  12807. * @default true
  12808. */
  12809. this.lights = true;
  12810. this.setDefaultValues( _defaultValues$9 );
  12811. this.setValues( parameters );
  12812. }
  12813. /**
  12814. * Basic materials are not affected by normal and bump maps so we
  12815. * return by default {@link module:Normal.normalView}.
  12816. *
  12817. * @return {Node<vec3>} The normal node.
  12818. */
  12819. setupNormal() {
  12820. return normalView; // see #28839
  12821. }
  12822. /**
  12823. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12824. * to implement the default environment mapping.
  12825. *
  12826. * @param {NodeBuilder} builder - The current node builder.
  12827. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12828. */
  12829. setupEnvironment( builder ) {
  12830. const envNode = super.setupEnvironment( builder );
  12831. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12832. }
  12833. /**
  12834. * This method must be overwriten since light maps are evaluated
  12835. * with a special scaling factor for basic materials.
  12836. *
  12837. * @param {NodeBuilder} builder - The current node builder.
  12838. * @return {BasicLightMapNode<vec3>?} The light map node.
  12839. */
  12840. setupLightMap( builder ) {
  12841. let node = null;
  12842. if ( builder.material.lightMap ) {
  12843. node = new BasicLightMapNode( materialLightMap );
  12844. }
  12845. return node;
  12846. }
  12847. /**
  12848. * The material overwrites this method because `lights` is set to `true` but
  12849. * we still want to return the diffuse color as the outgoing light.
  12850. *
  12851. * @return {Node<vec3>} The outgoing light node.
  12852. */
  12853. setupOutgoingLight() {
  12854. return diffuseColor.rgb;
  12855. }
  12856. /**
  12857. * Setups the lighting model.
  12858. *
  12859. * @return {BasicLightingModel} The lighting model.
  12860. */
  12861. setupLightingModel() {
  12862. return new BasicLightingModel();
  12863. }
  12864. }
  12865. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  12866. // Original approximation by Christophe Schlick '94
  12867. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  12868. // Optimized variant (presented by Epic at SIGGRAPH '13)
  12869. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  12870. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  12871. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  12872. } ); // validated
  12873. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  12874. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  12875. } ); // validated
  12876. const G_BlinnPhong_Implicit = () => float( 0.25 );
  12877. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  12878. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  12879. } );
  12880. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  12881. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  12882. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  12883. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  12884. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  12885. const G = G_BlinnPhong_Implicit();
  12886. const D = D_BlinnPhong( { dotNH } );
  12887. return F.mul( G ).mul( D );
  12888. } );
  12889. /**
  12890. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  12891. *
  12892. * @augments BasicLightingModel
  12893. */
  12894. class PhongLightingModel extends BasicLightingModel {
  12895. /**
  12896. * Constructs a new phong lighting model.
  12897. *
  12898. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  12899. */
  12900. constructor( specular = true ) {
  12901. super();
  12902. /**
  12903. * Whether specular is supported or not. Set this to `false` if you are
  12904. * looking for a Lambert-like material meaning a material for non-shiny
  12905. * surfaces, without specular highlights.
  12906. *
  12907. * @type {Boolean}
  12908. * @default true
  12909. */
  12910. this.specular = specular;
  12911. }
  12912. /**
  12913. * Implements the direct lighting. The specular portion is optional an can be controlled
  12914. * with the {@link PhongLightingModel#specular} flag.
  12915. *
  12916. * @param {Object} input - The input data.
  12917. * @param {StackNode} stack - The current stack.
  12918. * @param {NodeBuilder} builder - The current node builder.
  12919. */
  12920. direct( { lightDirection, lightColor, reflectedLight } ) {
  12921. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  12922. const irradiance = dotNL.mul( lightColor );
  12923. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  12924. if ( this.specular === true ) {
  12925. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  12926. }
  12927. }
  12928. /**
  12929. * Implements the indirect lighting.
  12930. *
  12931. * @param {ContextNode} input - The current node context.
  12932. * @param {StackNode} stack - The current stack.
  12933. * @param {NodeBuilder} builder - The current node builder.
  12934. */
  12935. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  12936. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  12937. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12938. }
  12939. }
  12940. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  12941. /**
  12942. * Node material version of `MeshLambertMaterial`.
  12943. *
  12944. * @augments NodeMaterial
  12945. */
  12946. class MeshLambertNodeMaterial extends NodeMaterial {
  12947. static get type() {
  12948. return 'MeshLambertNodeMaterial';
  12949. }
  12950. /**
  12951. * Constructs a new mesh lambert node material.
  12952. *
  12953. * @param {Object?} parameters - The configuration parameter.
  12954. */
  12955. constructor( parameters ) {
  12956. super();
  12957. /**
  12958. * This flag can be used for type testing.
  12959. *
  12960. * @type {Boolean}
  12961. * @readonly
  12962. * @default true
  12963. */
  12964. this.isMeshLambertNodeMaterial = true;
  12965. /**
  12966. * Set to `true` because lambert materials react on lights.
  12967. *
  12968. * @type {Boolean}
  12969. * @default true
  12970. */
  12971. this.lights = true;
  12972. this.setDefaultValues( _defaultValues$8 );
  12973. this.setValues( parameters );
  12974. }
  12975. /**
  12976. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12977. * to implement the default environment mapping.
  12978. *
  12979. * @param {NodeBuilder} builder - The current node builder.
  12980. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12981. */
  12982. setupEnvironment( builder ) {
  12983. const envNode = super.setupEnvironment( builder );
  12984. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12985. }
  12986. /**
  12987. * Setups the lighting model.
  12988. *
  12989. * @return {PhongLightingModel} The lighting model.
  12990. */
  12991. setupLightingModel( /*builder*/ ) {
  12992. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  12993. }
  12994. }
  12995. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  12996. /**
  12997. * Node material version of `MeshPhongMaterial`.
  12998. *
  12999. * @augments NodeMaterial
  13000. */
  13001. class MeshPhongNodeMaterial extends NodeMaterial {
  13002. static get type() {
  13003. return 'MeshPhongNodeMaterial';
  13004. }
  13005. /**
  13006. * Constructs a new mesh lambert node material.
  13007. *
  13008. * @param {Object?} parameters - The configuration parameter.
  13009. */
  13010. constructor( parameters ) {
  13011. super();
  13012. /**
  13013. * This flag can be used for type testing.
  13014. *
  13015. * @type {Boolean}
  13016. * @readonly
  13017. * @default true
  13018. */
  13019. this.isMeshPhongNodeMaterial = true;
  13020. /**
  13021. * Set to `true` because phong materials react on lights.
  13022. *
  13023. * @type {Boolean}
  13024. * @default true
  13025. */
  13026. this.lights = true;
  13027. /**
  13028. * The shininess of phong materials is by default inferred from the `shininess`
  13029. * property. This node property allows to overwrite the default
  13030. * and define the shininess with a node instead.
  13031. *
  13032. * If you don't want to overwrite the shininess but modify the existing
  13033. * value instead, use {@link module:MaterialNode.materialShininess}.
  13034. *
  13035. * @type {Node<float>?}
  13036. * @default null
  13037. */
  13038. this.shininessNode = null;
  13039. /**
  13040. * The specular color of phong materials is by default inferred from the
  13041. * `specular` property. This node property allows to overwrite the default
  13042. * and define the specular color with a node instead.
  13043. *
  13044. * If you don't want to overwrite the specular color but modify the existing
  13045. * value instead, use {@link module:MaterialNode.materialSpecular}.
  13046. *
  13047. * @type {Node<vec3>?}
  13048. * @default null
  13049. */
  13050. this.specularNode = null;
  13051. this.setDefaultValues( _defaultValues$7 );
  13052. this.setValues( parameters );
  13053. }
  13054. /**
  13055. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13056. * to implement the default environment mapping.
  13057. *
  13058. * @param {NodeBuilder} builder - The current node builder.
  13059. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13060. */
  13061. setupEnvironment( builder ) {
  13062. const envNode = super.setupEnvironment( builder );
  13063. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13064. }
  13065. /**
  13066. * Setups the lighting model.
  13067. *
  13068. * @return {PhongLightingModel} The lighting model.
  13069. */
  13070. setupLightingModel( /*builder*/ ) {
  13071. return new PhongLightingModel();
  13072. }
  13073. /**
  13074. * Setups the phong specific node variables.
  13075. *
  13076. * @param {NodeBuilder} builder - The current node builder.
  13077. */
  13078. setupVariants( /*builder*/ ) {
  13079. // SHININESS
  13080. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13081. shininess.assign( shininessNode );
  13082. // SPECULAR COLOR
  13083. const specularNode = this.specularNode || materialSpecular;
  13084. specularColor.assign( specularNode );
  13085. }
  13086. copy( source ) {
  13087. this.shininessNode = source.shininessNode;
  13088. this.specularNode = source.specularNode;
  13089. return super.copy( source );
  13090. }
  13091. }
  13092. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13093. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13094. return float( 0 );
  13095. }
  13096. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13097. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13098. return geometryRoughness;
  13099. } );
  13100. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13101. const { roughness } = inputs;
  13102. const geometryRoughness = getGeometryRoughness();
  13103. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13104. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13105. roughnessFactor = roughnessFactor.min( 1.0 );
  13106. return roughnessFactor;
  13107. } );
  13108. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13109. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13110. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13111. const a2 = alpha.pow2();
  13112. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13113. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13114. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13115. } ).setLayout( {
  13116. name: 'V_GGX_SmithCorrelated',
  13117. type: 'float',
  13118. inputs: [
  13119. { name: 'alpha', type: 'float' },
  13120. { name: 'dotNL', type: 'float' },
  13121. { name: 'dotNV', type: 'float' }
  13122. ]
  13123. } ); // validated
  13124. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13125. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13126. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13127. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13128. const v = div( 0.5, gv.add( gl ) );
  13129. return v.saturate();
  13130. } ).setLayout( {
  13131. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13132. type: 'float',
  13133. inputs: [
  13134. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13135. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13136. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13137. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13138. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13139. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13140. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13141. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13142. ]
  13143. } );
  13144. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13145. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13146. // alpha is "roughness squared" in Disney’s reparameterization
  13147. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13148. const a2 = alpha.pow2();
  13149. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13150. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13151. } ).setLayout( {
  13152. name: 'D_GGX',
  13153. type: 'float',
  13154. inputs: [
  13155. { name: 'alpha', type: 'float' },
  13156. { name: 'dotNH', type: 'float' }
  13157. ]
  13158. } ); // validated
  13159. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13160. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13161. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13162. const a2 = alphaT.mul( alphaB );
  13163. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13164. const v2 = v.dot( v );
  13165. const w2 = a2.div( v2 );
  13166. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13167. } ).setLayout( {
  13168. name: 'D_GGX_Anisotropic',
  13169. type: 'float',
  13170. inputs: [
  13171. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13172. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13173. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13174. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13175. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13176. ]
  13177. } );
  13178. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13179. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13180. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13181. const normalView = inputs.normalView || transformedNormalView;
  13182. const alpha = roughness.pow2(); // UE4's roughness
  13183. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13184. const dotNL = normalView.dot( lightDirection ).clamp();
  13185. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13186. const dotNH = normalView.dot( halfDir ).clamp();
  13187. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13188. let F = F_Schlick( { f0, f90, dotVH } );
  13189. let V, D;
  13190. if ( defined( USE_IRIDESCENCE ) ) {
  13191. F = iridescence.mix( F, f );
  13192. }
  13193. if ( defined( USE_ANISOTROPY ) ) {
  13194. const dotTL = anisotropyT.dot( lightDirection );
  13195. const dotTV = anisotropyT.dot( positionViewDirection );
  13196. const dotTH = anisotropyT.dot( halfDir );
  13197. const dotBL = anisotropyB.dot( lightDirection );
  13198. const dotBV = anisotropyB.dot( positionViewDirection );
  13199. const dotBH = anisotropyB.dot( halfDir );
  13200. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13201. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13202. } else {
  13203. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13204. D = D_GGX( { alpha, dotNH } );
  13205. }
  13206. return F.mul( V ).mul( D );
  13207. } ); // validated
  13208. // Analytical approximation of the DFG LUT, one half of the
  13209. // split-sum approximation used in indirect specular lighting.
  13210. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13211. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13212. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13213. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  13214. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  13215. const r = roughness.mul( c0 ).add( c1 );
  13216. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  13217. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  13218. return fab;
  13219. } ).setLayout( {
  13220. name: 'DFGApprox',
  13221. type: 'vec2',
  13222. inputs: [
  13223. { name: 'roughness', type: 'float' },
  13224. { name: 'dotNV', type: 'vec3' }
  13225. ]
  13226. } );
  13227. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13228. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13229. const fab = DFGApprox( { dotNV, roughness } );
  13230. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13231. } );
  13232. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13233. const x = dotVH.oneMinus().saturate();
  13234. const x2 = x.mul( x );
  13235. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13236. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13237. } ).setLayout( {
  13238. name: 'Schlick_to_F0',
  13239. type: 'vec3',
  13240. inputs: [
  13241. { name: 'f', type: 'vec3' },
  13242. { name: 'f90', type: 'float' },
  13243. { name: 'dotVH', type: 'float' }
  13244. ]
  13245. } );
  13246. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13247. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13248. const alpha = roughness.pow2();
  13249. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13250. const invAlpha = float( 1.0 ).div( alpha );
  13251. const cos2h = dotNH.pow2();
  13252. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13253. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13254. } ).setLayout( {
  13255. name: 'D_Charlie',
  13256. type: 'float',
  13257. inputs: [
  13258. { name: 'roughness', type: 'float' },
  13259. { name: 'dotNH', type: 'float' }
  13260. ]
  13261. } );
  13262. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13263. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13264. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13265. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13266. } ).setLayout( {
  13267. name: 'V_Neubelt',
  13268. type: 'float',
  13269. inputs: [
  13270. { name: 'dotNV', type: 'float' },
  13271. { name: 'dotNL', type: 'float' }
  13272. ]
  13273. } );
  13274. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13275. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13276. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13277. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13278. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13279. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13280. const V = V_Neubelt( { dotNV, dotNL } );
  13281. return sheen.mul( D ).mul( V );
  13282. } );
  13283. // Rect Area Light
  13284. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13285. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13286. // code: https://github.com/selfshadow/ltc_code/
  13287. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13288. const LUT_SIZE = 64.0;
  13289. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13290. const LUT_BIAS = 0.5 / LUT_SIZE;
  13291. const dotNV = N.dot( V ).saturate();
  13292. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13293. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13294. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13295. return uv;
  13296. } ).setLayout( {
  13297. name: 'LTC_Uv',
  13298. type: 'vec2',
  13299. inputs: [
  13300. { name: 'N', type: 'vec3' },
  13301. { name: 'V', type: 'vec3' },
  13302. { name: 'roughness', type: 'float' }
  13303. ]
  13304. } );
  13305. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13306. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13307. // An approximation of the form factor of a horizon-clipped rectangle.
  13308. const l = f.length();
  13309. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13310. } ).setLayout( {
  13311. name: 'LTC_ClippedSphereFormFactor',
  13312. type: 'float',
  13313. inputs: [
  13314. { name: 'f', type: 'vec3' }
  13315. ]
  13316. } );
  13317. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13318. const x = v1.dot( v2 );
  13319. const y = x.abs().toVar();
  13320. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13321. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13322. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13323. const v = a.div( b );
  13324. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13325. return v1.cross( v2 ).mul( theta_sintheta );
  13326. } ).setLayout( {
  13327. name: 'LTC_EdgeVectorFormFactor',
  13328. type: 'vec3',
  13329. inputs: [
  13330. { name: 'v1', type: 'vec3' },
  13331. { name: 'v2', type: 'vec3' }
  13332. ]
  13333. } );
  13334. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13335. // bail if point is on back side of plane of light
  13336. // assumes ccw winding order of light vertices
  13337. const v1 = p1.sub( p0 ).toVar();
  13338. const v2 = p3.sub( p0 ).toVar();
  13339. const lightNormal = v1.cross( v2 );
  13340. const result = vec3().toVar();
  13341. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13342. // construct orthonormal basis around N
  13343. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13344. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13345. // compute transform
  13346. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13347. // transform rect
  13348. // & project rect onto sphere
  13349. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13350. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13351. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13352. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13353. // calculate vector form factor
  13354. const vectorFormFactor = vec3( 0 ).toVar();
  13355. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13356. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13357. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13358. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13359. // adjust for horizon clipping
  13360. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13361. } );
  13362. return result;
  13363. } ).setLayout( {
  13364. name: 'LTC_Evaluate',
  13365. type: 'vec3',
  13366. inputs: [
  13367. { name: 'N', type: 'vec3' },
  13368. { name: 'V', type: 'vec3' },
  13369. { name: 'P', type: 'vec3' },
  13370. { name: 'mInv', type: 'mat3' },
  13371. { name: 'p0', type: 'vec3' },
  13372. { name: 'p1', type: 'vec3' },
  13373. { name: 'p2', type: 'vec3' },
  13374. { name: 'p3', type: 'vec3' }
  13375. ]
  13376. } );
  13377. /** @module TextureBicubic **/
  13378. // Mipped Bicubic Texture Filtering by N8
  13379. // https://www.shadertoy.com/view/Dl2SDW
  13380. const bC = 1.0 / 6.0;
  13381. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13382. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13383. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13384. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13385. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13386. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13387. // h0 and h1 are the two offset functions
  13388. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13389. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13390. const bicubic = ( textureNode, texelSize, lod ) => {
  13391. const uv = textureNode.uvNode;
  13392. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13393. const iuv = floor( uvScaled );
  13394. const fuv = fract( uvScaled );
  13395. const g0x = g0( fuv.x );
  13396. const g1x = g1( fuv.x );
  13397. const h0x = h0( fuv.x );
  13398. const h1x = h1( fuv.x );
  13399. const h0y = h0( fuv.y );
  13400. const h1y = h1( fuv.y );
  13401. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13402. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13403. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13404. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13405. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13406. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13407. return a.add( b );
  13408. };
  13409. /**
  13410. * Applies mipped bicubic texture filtering to the given texture node.
  13411. *
  13412. * @method
  13413. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13414. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13415. * @return {Node} The filtered texture sample.
  13416. */
  13417. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13418. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13419. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13420. const fLodSizeInv = div( 1.0, fLodSize );
  13421. const cLodSizeInv = div( 1.0, cLodSize );
  13422. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13423. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13424. return fract( lodNode ).mix( fSample, cSample );
  13425. } );
  13426. //
  13427. // Transmission
  13428. //
  13429. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13430. // Direction of refracted light.
  13431. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13432. // Compute rotation-independent scaling of the model matrix.
  13433. const modelScale = vec3(
  13434. length( modelMatrix[ 0 ].xyz ),
  13435. length( modelMatrix[ 1 ].xyz ),
  13436. length( modelMatrix[ 2 ].xyz )
  13437. );
  13438. // The thickness is specified in local space.
  13439. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13440. } ).setLayout( {
  13441. name: 'getVolumeTransmissionRay',
  13442. type: 'vec3',
  13443. inputs: [
  13444. { name: 'n', type: 'vec3' },
  13445. { name: 'v', type: 'vec3' },
  13446. { name: 'thickness', type: 'float' },
  13447. { name: 'ior', type: 'float' },
  13448. { name: 'modelMatrix', type: 'mat4' }
  13449. ]
  13450. } );
  13451. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13452. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13453. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13454. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13455. } ).setLayout( {
  13456. name: 'applyIorToRoughness',
  13457. type: 'float',
  13458. inputs: [
  13459. { name: 'roughness', type: 'float' },
  13460. { name: 'ior', type: 'float' }
  13461. ]
  13462. } );
  13463. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13464. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13465. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13466. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13467. const transmissionSample = vTexture.sample( fragCoord );
  13468. //const transmissionSample = viewportMipTexture( fragCoord );
  13469. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13470. return textureBicubic( transmissionSample, lod );
  13471. } );
  13472. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13473. If( attenuationDistance.notEqual( 0 ), () => {
  13474. // Compute light attenuation using Beer's law.
  13475. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13476. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13477. return transmittance;
  13478. } );
  13479. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13480. return vec3( 1.0 );
  13481. } ).setLayout( {
  13482. name: 'volumeAttenuation',
  13483. type: 'vec3',
  13484. inputs: [
  13485. { name: 'transmissionDistance', type: 'float' },
  13486. { name: 'attenuationColor', type: 'vec3' },
  13487. { name: 'attenuationDistance', type: 'float' }
  13488. ]
  13489. } );
  13490. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13491. let transmittedLight, transmittance;
  13492. if ( dispersion ) {
  13493. transmittedLight = vec4().toVar();
  13494. transmittance = vec3().toVar();
  13495. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13496. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13497. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13498. const ior = iors.element( i );
  13499. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13500. const refractedRayExit = position.add( transmissionRay );
  13501. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13502. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13503. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13504. refractionCoords.addAssign( 1.0 );
  13505. refractionCoords.divAssign( 2.0 );
  13506. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13507. // Sample framebuffer to get pixel the refracted ray hits.
  13508. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  13509. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  13510. transmittedLight.a.addAssign( transmissionSample.a );
  13511. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  13512. } );
  13513. transmittedLight.a.divAssign( 3.0 );
  13514. } else {
  13515. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13516. const refractedRayExit = position.add( transmissionRay );
  13517. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13518. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13519. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13520. refractionCoords.addAssign( 1.0 );
  13521. refractionCoords.divAssign( 2.0 );
  13522. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13523. // Sample framebuffer to get pixel the refracted ray hits.
  13524. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  13525. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  13526. }
  13527. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  13528. const dotNV = n.dot( v ).clamp();
  13529. // Get the specular component.
  13530. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  13531. dotNV,
  13532. specularColor,
  13533. specularF90,
  13534. roughness
  13535. } ) );
  13536. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  13537. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  13538. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  13539. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  13540. } );
  13541. //
  13542. // Iridescence
  13543. //
  13544. // XYZ to linear-sRGB color space
  13545. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  13546. 3.2404542, - 0.9692660, 0.0556434,
  13547. - 1.5371385, 1.8760108, - 0.2040259,
  13548. - 0.4985314, 0.0415560, 1.0572252
  13549. );
  13550. // Assume air interface for top
  13551. // Note: We don't handle the case fresnel0 == 1
  13552. const Fresnel0ToIor = ( fresnel0 ) => {
  13553. const sqrtF0 = fresnel0.sqrt();
  13554. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  13555. };
  13556. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  13557. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  13558. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  13559. };
  13560. // Fresnel equations for dielectric/dielectric interfaces.
  13561. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  13562. // Evaluation XYZ sensitivity curves in Fourier space
  13563. const evalSensitivity = ( OPD, shift ) => {
  13564. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  13565. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  13566. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  13567. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  13568. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( - 4.5282e+09 ).exp() );
  13569. let xyz = val.mul( VAR.mul( 2.0 * Math.PI ).sqrt() ).mul( pos.mul( phase ).add( shift ).cos() ).mul( phase.pow2().negate().mul( VAR ).exp() );
  13570. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  13571. const rgb = XYZ_TO_REC709.mul( xyz );
  13572. return rgb;
  13573. };
  13574. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  13575. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  13576. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  13577. // Evaluate the cosTheta on the base layer (Snell law)
  13578. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  13579. // Handle TIR:
  13580. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  13581. If( cosTheta2Sq.lessThan( 0 ), () => {
  13582. return vec3( 1.0 );
  13583. } );
  13584. const cosTheta2 = cosTheta2Sq.sqrt();
  13585. // First interface
  13586. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  13587. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  13588. //const R21 = R12;
  13589. const T121 = R12.oneMinus();
  13590. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  13591. const phi21 = float( Math.PI ).sub( phi12 );
  13592. // Second interface
  13593. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  13594. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  13595. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  13596. const phi23 = vec3(
  13597. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13598. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13599. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  13600. );
  13601. // Phase shift
  13602. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  13603. const phi = vec3( phi21 ).add( phi23 );
  13604. // Compound terms
  13605. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  13606. const r123 = R123.sqrt();
  13607. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  13608. // Reflectance term for m = 0 (DC term amplitude)
  13609. const C0 = R12.add( Rs );
  13610. const I = C0.toVar();
  13611. // Reflectance term for m > 0 (pairs of diracs)
  13612. const Cm = Rs.sub( T121 ).toVar();
  13613. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  13614. Cm.mulAssign( r123 );
  13615. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  13616. I.addAssign( Cm.mul( Sm ) );
  13617. } );
  13618. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  13619. return I.max( vec3( 0.0 ) );
  13620. } ).setLayout( {
  13621. name: 'evalIridescence',
  13622. type: 'vec3',
  13623. inputs: [
  13624. { name: 'outsideIOR', type: 'float' },
  13625. { name: 'eta2', type: 'float' },
  13626. { name: 'cosTheta1', type: 'float' },
  13627. { name: 'thinFilmThickness', type: 'float' },
  13628. { name: 'baseF0', type: 'vec3' }
  13629. ]
  13630. } );
  13631. //
  13632. // Sheen
  13633. //
  13634. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  13635. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  13636. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  13637. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  13638. const dotNV = normal.dot( viewDir ).saturate();
  13639. const r2 = roughness.pow2();
  13640. const a = select(
  13641. roughness.lessThan( 0.25 ),
  13642. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  13643. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  13644. );
  13645. const b = select(
  13646. roughness.lessThan( 0.25 ),
  13647. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  13648. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  13649. );
  13650. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  13651. return DG.mul( 1.0 / Math.PI ).saturate();
  13652. } );
  13653. const clearcoatF0 = vec3( 0.04 );
  13654. const clearcoatF90 = float( 1 );
  13655. /**
  13656. * Represents the lighting model for a PBR material.
  13657. *
  13658. * @augments LightingModel
  13659. */
  13660. class PhysicalLightingModel extends LightingModel {
  13661. /**
  13662. * Constructs a new physical lighting model.
  13663. *
  13664. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  13665. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  13666. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  13667. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  13668. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  13669. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  13670. */
  13671. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  13672. super();
  13673. /**
  13674. * Whether clearcoat is supported or not.
  13675. *
  13676. * @type {Boolean}
  13677. * @default false
  13678. */
  13679. this.clearcoat = clearcoat;
  13680. /**
  13681. * Whether sheen is supported or not.
  13682. *
  13683. * @type {Boolean}
  13684. * @default false
  13685. */
  13686. this.sheen = sheen;
  13687. /**
  13688. * Whether iridescence is supported or not.
  13689. *
  13690. * @type {Boolean}
  13691. * @default false
  13692. */
  13693. this.iridescence = iridescence;
  13694. /**
  13695. * Whether anisotropy is supported or not.
  13696. *
  13697. * @type {Boolean}
  13698. * @default false
  13699. */
  13700. this.anisotropy = anisotropy;
  13701. /**
  13702. * Whether transmission is supported or not.
  13703. *
  13704. * @type {Boolean}
  13705. * @default false
  13706. */
  13707. this.transmission = transmission;
  13708. /**
  13709. * Whether dispersion is supported or not.
  13710. *
  13711. * @type {Boolean}
  13712. * @default false
  13713. */
  13714. this.dispersion = dispersion;
  13715. /**
  13716. * The clear coat radiance.
  13717. *
  13718. * @type {Node?}
  13719. * @default null
  13720. */
  13721. this.clearcoatRadiance = null;
  13722. /**
  13723. * The clear coat specular direct.
  13724. *
  13725. * @type {Node?}
  13726. * @default null
  13727. */
  13728. this.clearcoatSpecularDirect = null;
  13729. /**
  13730. * The clear coat specular indirect.
  13731. *
  13732. * @type {Node?}
  13733. * @default null
  13734. */
  13735. this.clearcoatSpecularIndirect = null;
  13736. /**
  13737. * The sheen specular direct.
  13738. *
  13739. * @type {Node?}
  13740. * @default null
  13741. */
  13742. this.sheenSpecularDirect = null;
  13743. /**
  13744. * The sheen specular indirect.
  13745. *
  13746. * @type {Node?}
  13747. * @default null
  13748. */
  13749. this.sheenSpecularIndirect = null;
  13750. /**
  13751. * The iridescence Fresnel.
  13752. *
  13753. * @type {Node?}
  13754. * @default null
  13755. */
  13756. this.iridescenceFresnel = null;
  13757. /**
  13758. * The iridescence F0.
  13759. *
  13760. * @type {Node?}
  13761. * @default null
  13762. */
  13763. this.iridescenceF0 = null;
  13764. }
  13765. /**
  13766. * Depending on what features are requested, the method prepares certain node variables
  13767. * which are later used for lighting computations.
  13768. *
  13769. * @param {ContextNode} context - The current node context.
  13770. */
  13771. start( context ) {
  13772. if ( this.clearcoat === true ) {
  13773. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  13774. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  13775. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  13776. }
  13777. if ( this.sheen === true ) {
  13778. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  13779. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  13780. }
  13781. if ( this.iridescence === true ) {
  13782. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  13783. this.iridescenceFresnel = evalIridescence( {
  13784. outsideIOR: float( 1.0 ),
  13785. eta2: iridescenceIOR,
  13786. cosTheta1: dotNVi,
  13787. thinFilmThickness: iridescenceThickness,
  13788. baseF0: specularColor
  13789. } );
  13790. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  13791. }
  13792. if ( this.transmission === true ) {
  13793. const position = positionWorld;
  13794. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  13795. const n = transformedNormalWorld;
  13796. context.backdrop = getIBLVolumeRefraction(
  13797. n,
  13798. v,
  13799. roughness,
  13800. diffuseColor,
  13801. specularColor,
  13802. specularF90, // specularF90
  13803. position, // positionWorld
  13804. modelWorldMatrix, // modelMatrix
  13805. cameraViewMatrix, // viewMatrix
  13806. cameraProjectionMatrix, // projMatrix
  13807. ior,
  13808. thickness,
  13809. attenuationColor,
  13810. attenuationDistance,
  13811. this.dispersion ? dispersion : null
  13812. );
  13813. context.backdropAlpha = transmission;
  13814. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  13815. }
  13816. }
  13817. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  13818. // Approximates multi-scattering in order to preserve energy.
  13819. // http://www.jcgt.org/published/0008/01/03/
  13820. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  13821. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13822. const fab = DFGApprox( { roughness, dotNV } );
  13823. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  13824. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13825. const Ess = fab.x.add( fab.y );
  13826. const Ems = Ess.oneMinus();
  13827. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  13828. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  13829. singleScatter.addAssign( FssEss );
  13830. multiScatter.addAssign( Fms.mul( Ems ) );
  13831. }
  13832. /**
  13833. * Implements the direct light.
  13834. *
  13835. * @param {Object} input - The input data.
  13836. * @param {StackNode} stack - The current stack.
  13837. * @param {NodeBuilder} builder - The current node builder.
  13838. */
  13839. direct( { lightDirection, lightColor, reflectedLight } ) {
  13840. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13841. const irradiance = dotNL.mul( lightColor );
  13842. if ( this.sheen === true ) {
  13843. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  13844. }
  13845. if ( this.clearcoat === true ) {
  13846. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  13847. const ccIrradiance = dotNLcc.mul( lightColor );
  13848. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  13849. }
  13850. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13851. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX( { lightDirection, f0: specularColor, f90: 1, roughness, iridescence: this.iridescence, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  13852. }
  13853. /**
  13854. * This method is intended for implementing the direct light term for
  13855. * rect area light nodes.
  13856. *
  13857. * @param {Object} input - The input data.
  13858. * @param {StackNode} stack - The current stack.
  13859. * @param {NodeBuilder} builder - The current node builder.
  13860. */
  13861. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  13862. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  13863. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  13864. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  13865. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  13866. const N = transformedNormalView;
  13867. const V = positionViewDirection;
  13868. const P = positionView.toVar();
  13869. const uv = LTC_Uv( { N, V, roughness } );
  13870. const t1 = ltc_1.sample( uv ).toVar();
  13871. const t2 = ltc_2.sample( uv ).toVar();
  13872. const mInv = mat3(
  13873. vec3( t1.x, 0, t1.y ),
  13874. vec3( 0, 1, 0 ),
  13875. vec3( t1.z, 0, t1.w )
  13876. ).toVar();
  13877. // LTC Fresnel Approximation by Stephen Hill
  13878. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  13879. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  13880. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  13881. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseColor ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  13882. }
  13883. /**
  13884. * Implements the indirect lighting.
  13885. *
  13886. * @param {ContextNode} context - The current node context.
  13887. * @param {StackNode} stack - The current stack.
  13888. * @param {NodeBuilder} builder - The current node builder.
  13889. */
  13890. indirect( context, stack, builder ) {
  13891. this.indirectDiffuse( context, stack, builder );
  13892. this.indirectSpecular( context, stack, builder );
  13893. this.ambientOcclusion( context, stack, builder );
  13894. }
  13895. /**
  13896. * Implements the indirect diffuse term.
  13897. *
  13898. * @param {ContextNode} input - The current node context.
  13899. * @param {StackNode} stack - The current stack.
  13900. * @param {NodeBuilder} builder - The current node builder.
  13901. */
  13902. indirectDiffuse( { irradiance, reflectedLight } ) {
  13903. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13904. }
  13905. /**
  13906. * Implements the indirect specular term.
  13907. *
  13908. * @param {ContextNode} input - The current node context.
  13909. * @param {StackNode} stack - The current stack.
  13910. * @param {NodeBuilder} builder - The current node builder.
  13911. */
  13912. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  13913. if ( this.sheen === true ) {
  13914. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  13915. sheen,
  13916. IBLSheenBRDF( {
  13917. normal: transformedNormalView,
  13918. viewDir: positionViewDirection,
  13919. roughness: sheenRoughness
  13920. } )
  13921. ) );
  13922. }
  13923. if ( this.clearcoat === true ) {
  13924. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13925. const clearcoatEnv = EnvironmentBRDF( {
  13926. dotNV: dotNVcc,
  13927. specularColor: clearcoatF0,
  13928. specularF90: clearcoatF90,
  13929. roughness: clearcoatRoughness
  13930. } );
  13931. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  13932. }
  13933. // Both indirect specular and indirect diffuse light accumulate here
  13934. const singleScattering = vec3().toVar( 'singleScattering' );
  13935. const multiScattering = vec3().toVar( 'multiScattering' );
  13936. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  13937. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  13938. const totalScattering = singleScattering.add( multiScattering );
  13939. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  13940. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  13941. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  13942. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  13943. }
  13944. /**
  13945. * Implements the ambient occlusion term.
  13946. *
  13947. * @param {ContextNode} input - The current node context.
  13948. * @param {StackNode} stack - The current stack.
  13949. * @param {NodeBuilder} builder - The current node builder.
  13950. */
  13951. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  13952. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13953. const aoNV = dotNV.add( ambientOcclusion );
  13954. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  13955. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  13956. if ( this.clearcoat === true ) {
  13957. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  13958. }
  13959. if ( this.sheen === true ) {
  13960. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  13961. }
  13962. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13963. reflectedLight.indirectSpecular.mulAssign( aoNode );
  13964. }
  13965. /**
  13966. * Used for final lighting accumulations depending on the requested features.
  13967. *
  13968. * @param {ContextNode} context - The current node context.
  13969. * @param {StackNode} stack - The current stack.
  13970. * @param {NodeBuilder} builder - The current node builder.
  13971. */
  13972. finish( context ) {
  13973. const { outgoingLight } = context;
  13974. if ( this.clearcoat === true ) {
  13975. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13976. const Fcc = F_Schlick( {
  13977. dotVH: dotNVcc,
  13978. f0: clearcoatF0,
  13979. f90: clearcoatF90
  13980. } );
  13981. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  13982. outgoingLight.assign( clearcoatLight );
  13983. }
  13984. if ( this.sheen === true ) {
  13985. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  13986. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  13987. outgoingLight.assign( sheenLight );
  13988. }
  13989. }
  13990. }
  13991. // These defines must match with PMREMGenerator
  13992. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  13993. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  13994. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  13995. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  13996. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  13997. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  13998. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  13999. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14000. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14001. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14002. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14003. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14004. // These shader functions convert between the UV coordinates of a single face of
  14005. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14006. // sampling a textureCube (not generally normalized ).
  14007. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14008. const absDirection = vec3( abs( direction ) ).toVar();
  14009. const face = float( - 1.0 ).toVar();
  14010. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14011. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14012. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14013. } ).Else( () => {
  14014. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14015. } );
  14016. } ).Else( () => {
  14017. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14018. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14019. } ).Else( () => {
  14020. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14021. } );
  14022. } );
  14023. return face;
  14024. } ).setLayout( {
  14025. name: 'getFace',
  14026. type: 'float',
  14027. inputs: [
  14028. { name: 'direction', type: 'vec3' }
  14029. ]
  14030. } );
  14031. // RH coordinate system; PMREM face-indexing convention
  14032. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14033. const uv = vec2().toVar();
  14034. If( face.equal( 0.0 ), () => {
  14035. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14036. } ).ElseIf( face.equal( 1.0 ), () => {
  14037. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14038. } ).ElseIf( face.equal( 2.0 ), () => {
  14039. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14040. } ).ElseIf( face.equal( 3.0 ), () => {
  14041. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14042. } ).ElseIf( face.equal( 4.0 ), () => {
  14043. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14044. } ).Else( () => {
  14045. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14046. } );
  14047. return mul( 0.5, uv.add( 1.0 ) );
  14048. } ).setLayout( {
  14049. name: 'getUV',
  14050. type: 'vec2',
  14051. inputs: [
  14052. { name: 'direction', type: 'vec3' },
  14053. { name: 'face', type: 'float' }
  14054. ]
  14055. } );
  14056. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14057. const mip = float( 0.0 ).toVar();
  14058. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14059. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14060. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14061. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14062. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14063. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14064. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14065. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14066. } ).Else( () => {
  14067. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14068. } );
  14069. return mip;
  14070. } ).setLayout( {
  14071. name: 'roughnessToMip',
  14072. type: 'float',
  14073. inputs: [
  14074. { name: 'roughness', type: 'float' }
  14075. ]
  14076. } );
  14077. // RH coordinate system; PMREM face-indexing convention
  14078. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14079. const uv = uv_immutable.toVar();
  14080. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14081. const direction = vec3( uv, 1.0 ).toVar();
  14082. If( face.equal( 0.0 ), () => {
  14083. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14084. } ).ElseIf( face.equal( 1.0 ), () => {
  14085. direction.assign( direction.xzy );
  14086. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  14087. } ).ElseIf( face.equal( 2.0 ), () => {
  14088. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  14089. } ).ElseIf( face.equal( 3.0 ), () => {
  14090. direction.assign( direction.zyx );
  14091. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  14092. } ).ElseIf( face.equal( 4.0 ), () => {
  14093. direction.assign( direction.xzy );
  14094. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  14095. } ).ElseIf( face.equal( 5.0 ), () => {
  14096. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  14097. } );
  14098. return direction;
  14099. } ).setLayout( {
  14100. name: 'getDirection',
  14101. type: 'vec3',
  14102. inputs: [
  14103. { name: 'uv', type: 'vec2' },
  14104. { name: 'face', type: 'float' }
  14105. ]
  14106. } );
  14107. //
  14108. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14109. const roughness = float( roughness_immutable );
  14110. const sampleDir = vec3( sampleDir_immutable );
  14111. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14112. const mipF = fract( mip );
  14113. const mipInt = floor( mip );
  14114. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14115. If( mipF.notEqual( 0.0 ), () => {
  14116. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14117. color0.assign( mix( color0, color1, mipF ) );
  14118. } );
  14119. return color0;
  14120. } );
  14121. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14122. const mipInt = float( mipInt_immutable ).toVar();
  14123. const direction = vec3( direction_immutable );
  14124. const face = float( getFace( direction ) ).toVar();
  14125. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14126. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14127. const faceSize = float( exp2( mipInt ) ).toVar();
  14128. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14129. If( face.greaterThan( 2.0 ), () => {
  14130. uv.y.addAssign( faceSize );
  14131. face.subAssign( 3.0 );
  14132. } );
  14133. uv.x.addAssign( face.mul( faceSize ) );
  14134. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14135. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14136. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14137. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14138. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14139. } );
  14140. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14141. const cosTheta = cos( theta );
  14142. // Rodrigues' axis-angle rotation
  14143. const sampleDirection = outputDirection.mul( cosTheta )
  14144. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14145. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14146. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14147. } );
  14148. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14149. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14150. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14151. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14152. } );
  14153. axis.assign( normalize( axis ) );
  14154. const gl_FragColor = vec3().toVar();
  14155. gl_FragColor.addAssign( weights.element( int( 0 ) ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14156. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14157. If( i.greaterThanEqual( samples ), () => {
  14158. Break();
  14159. } );
  14160. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14161. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( - 1.0 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14162. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14163. } );
  14164. return vec4( gl_FragColor, 1 );
  14165. } );
  14166. /** @module PMREMNode **/
  14167. let _generator = null;
  14168. const _cache = new WeakMap();
  14169. /**
  14170. * Generates the cubeUV size based on the given image height.
  14171. *
  14172. * @private
  14173. * @param {Number} imageHeight - The image height.
  14174. * @return {{texelWidth: Number,texelHeight: Number, maxMip: Number}} The result object.
  14175. */
  14176. function _generateCubeUVSize( imageHeight ) {
  14177. const maxMip = Math.log2( imageHeight ) - 2;
  14178. const texelHeight = 1.0 / imageHeight;
  14179. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14180. return { texelWidth, texelHeight, maxMip };
  14181. }
  14182. /**
  14183. * Generates a PMREM from the given texture .
  14184. *
  14185. * @private
  14186. * @param {Texture} texture - The texture to create the PMREM for.
  14187. * @return {Texture} The PMREM.
  14188. */
  14189. function _getPMREMFromTexture( texture ) {
  14190. let cacheTexture = _cache.get( texture );
  14191. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  14192. if ( pmremVersion !== texture.pmremVersion ) {
  14193. const image = texture.image;
  14194. if ( texture.isCubeTexture ) {
  14195. if ( isCubeMapReady( image ) ) {
  14196. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14197. } else {
  14198. return null;
  14199. }
  14200. } else {
  14201. if ( isEquirectangularMapReady( image ) ) {
  14202. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14203. } else {
  14204. return null;
  14205. }
  14206. }
  14207. cacheTexture.pmremVersion = texture.pmremVersion;
  14208. _cache.set( texture, cacheTexture );
  14209. }
  14210. return cacheTexture.texture;
  14211. }
  14212. /**
  14213. * This node represents a PMREM which is a special type of preprocessed
  14214. * environment map intended for PBR materials.
  14215. *
  14216. * ```js
  14217. * const material = new MeshStandardNodeMaterial();
  14218. * material.envNode = pmremTexture( envMap );
  14219. * ```
  14220. *
  14221. * @augments TempNode
  14222. */
  14223. class PMREMNode extends TempNode {
  14224. static get type() {
  14225. return 'PMREMNode';
  14226. }
  14227. /**
  14228. * Constructs a new function overloading node.
  14229. *
  14230. * @param {Texture} value - The input texture.
  14231. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14232. * @param {Node<float>} [levelNode=null] - The level node.
  14233. */
  14234. constructor( value, uvNode = null, levelNode = null ) {
  14235. super( 'vec3' );
  14236. /**
  14237. * Reference to the input texture.
  14238. *
  14239. * @private
  14240. * @type {Texture}
  14241. */
  14242. this._value = value;
  14243. /**
  14244. * Reference to the generated PMREM.
  14245. *
  14246. * @private
  14247. * @type {Texture | null}
  14248. * @default null
  14249. */
  14250. this._pmrem = null;
  14251. /**
  14252. * The uv node.
  14253. *
  14254. * @type {Node<vec2>}
  14255. */
  14256. this.uvNode = uvNode;
  14257. /**
  14258. * The level node.
  14259. *
  14260. * @type {Node<float>}
  14261. */
  14262. this.levelNode = levelNode;
  14263. /**
  14264. * Reference to a PMREM generator.
  14265. *
  14266. * @private
  14267. * @type {PMREMGenerator}
  14268. * @default null
  14269. */
  14270. this._generator = null;
  14271. const defaultTexture = new Texture();
  14272. defaultTexture.isRenderTargetTexture = true;
  14273. /**
  14274. * The texture node holding the generated PMREM.
  14275. *
  14276. * @private
  14277. * @type {TextureNode}
  14278. */
  14279. this._texture = texture( defaultTexture );
  14280. /**
  14281. * A uniform representing the PMREM's width.
  14282. *
  14283. * @private
  14284. * @type {UniformNode<float>}
  14285. */
  14286. this._width = uniform( 0 );
  14287. /**
  14288. * A uniform representing the PMREM's height.
  14289. *
  14290. * @private
  14291. * @type {UniformNode<float>}
  14292. */
  14293. this._height = uniform( 0 );
  14294. /**
  14295. * A uniform representing the PMREM's max Mip.
  14296. *
  14297. * @private
  14298. * @type {UniformNode<float>}
  14299. */
  14300. this._maxMip = uniform( 0 );
  14301. /**
  14302. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14303. *
  14304. * @type {String}
  14305. * @default 'render'
  14306. */
  14307. this.updateBeforeType = NodeUpdateType.RENDER;
  14308. }
  14309. set value( value ) {
  14310. this._value = value;
  14311. this._pmrem = null;
  14312. }
  14313. /**
  14314. * The node's texture value.
  14315. *
  14316. * @type {Texture}
  14317. */
  14318. get value() {
  14319. return this._value;
  14320. }
  14321. /**
  14322. * Uses the given PMREM texture to update internal values.
  14323. *
  14324. * @param {Texture} texture - The PMREM texture.
  14325. */
  14326. updateFromTexture( texture ) {
  14327. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14328. this._texture.value = texture;
  14329. this._width.value = cubeUVSize.texelWidth;
  14330. this._height.value = cubeUVSize.texelHeight;
  14331. this._maxMip.value = cubeUVSize.maxMip;
  14332. }
  14333. updateBefore() {
  14334. let pmrem = this._pmrem;
  14335. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  14336. const texture = this._value;
  14337. if ( pmremVersion !== texture.pmremVersion ) {
  14338. if ( texture.isPMREMTexture === true ) {
  14339. pmrem = texture;
  14340. } else {
  14341. pmrem = _getPMREMFromTexture( texture );
  14342. }
  14343. if ( pmrem !== null ) {
  14344. this._pmrem = pmrem;
  14345. this.updateFromTexture( pmrem );
  14346. }
  14347. }
  14348. }
  14349. setup( builder ) {
  14350. if ( _generator === null ) {
  14351. _generator = builder.createPMREMGenerator();
  14352. }
  14353. //
  14354. this.updateBefore( builder );
  14355. //
  14356. let uvNode = this.uvNode;
  14357. if ( uvNode === null && builder.context.getUV ) {
  14358. uvNode = builder.context.getUV( this );
  14359. }
  14360. //
  14361. const texture = this.value;
  14362. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14363. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14364. }
  14365. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14366. //
  14367. let levelNode = this.levelNode;
  14368. if ( levelNode === null && builder.context.getTextureLevel ) {
  14369. levelNode = builder.context.getTextureLevel( this );
  14370. }
  14371. //
  14372. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14373. }
  14374. }
  14375. /**
  14376. * Returns `true` if the given cube map image has been fully loaded.
  14377. *
  14378. * @private
  14379. * @param {Array<(Image|Object)>} image - The cube map image.
  14380. * @return {Boolean} Whether the given cube map is ready or not.
  14381. */
  14382. function isCubeMapReady( image ) {
  14383. if ( image === null || image === undefined ) return false;
  14384. let count = 0;
  14385. const length = 6;
  14386. for ( let i = 0; i < length; i ++ ) {
  14387. if ( image[ i ] !== undefined ) count ++;
  14388. }
  14389. return count === length;
  14390. }
  14391. /**
  14392. * Returns `true` if the given equirectangular image has been fully loaded.
  14393. *
  14394. * @private
  14395. * @param {(Image|Object)} image - The equirectangular image.
  14396. * @return {Boolean} Whether the given cube map is ready or not.
  14397. */
  14398. function isEquirectangularMapReady( image ) {
  14399. if ( image === null || image === undefined ) return false;
  14400. return image.height > 0;
  14401. }
  14402. /**
  14403. * TSL function for creating a PMREM node.
  14404. *
  14405. * @function
  14406. * @param {Texture} value - The input texture.
  14407. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14408. * @param {Node<float>} [levelNode=null] - The level node.
  14409. * @returns {PMREMNode}
  14410. */
  14411. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14412. const _envNodeCache = new WeakMap();
  14413. /**
  14414. * Represents a physical model for Image-based lighting (IBL). The environment
  14415. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14416. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14417. *
  14418. * @augments LightingNode
  14419. */
  14420. class EnvironmentNode extends LightingNode {
  14421. static get type() {
  14422. return 'EnvironmentNode';
  14423. }
  14424. /**
  14425. * Constructs a new environment node.
  14426. *
  14427. * @param {Node} [envNode=null] - A node representing the environment.
  14428. */
  14429. constructor( envNode = null ) {
  14430. super();
  14431. /**
  14432. * A node representing the environment.
  14433. *
  14434. * @type {Node?}
  14435. * @default null
  14436. */
  14437. this.envNode = envNode;
  14438. }
  14439. setup( builder ) {
  14440. const { material } = builder;
  14441. let envNode = this.envNode;
  14442. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14443. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14444. let cacheEnvNode = _envNodeCache.get( value );
  14445. if ( cacheEnvNode === undefined ) {
  14446. cacheEnvNode = pmremTexture( value );
  14447. _envNodeCache.set( value, cacheEnvNode );
  14448. }
  14449. envNode = cacheEnvNode;
  14450. }
  14451. //
  14452. const envMap = material.envMap;
  14453. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14454. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14455. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14456. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14457. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14458. const isolateRadiance = cache( radiance );
  14459. const isolateIrradiance = cache( irradiance );
  14460. //
  14461. builder.context.radiance.addAssign( isolateRadiance );
  14462. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14463. //
  14464. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14465. if ( clearcoatRadiance ) {
  14466. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14467. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14468. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14469. }
  14470. }
  14471. }
  14472. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14473. let reflectVec = null;
  14474. return {
  14475. getUV: () => {
  14476. if ( reflectVec === null ) {
  14477. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14478. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14479. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14480. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14481. }
  14482. return reflectVec;
  14483. },
  14484. getTextureLevel: () => {
  14485. return roughnessNode;
  14486. }
  14487. };
  14488. };
  14489. const createIrradianceContext = ( normalWorldNode ) => {
  14490. return {
  14491. getUV: () => {
  14492. return normalWorldNode;
  14493. },
  14494. getTextureLevel: () => {
  14495. return float( 1.0 );
  14496. }
  14497. };
  14498. };
  14499. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14500. /**
  14501. * Node material version of `MeshStandardMaterial`.
  14502. *
  14503. * @augments NodeMaterial
  14504. */
  14505. class MeshStandardNodeMaterial extends NodeMaterial {
  14506. static get type() {
  14507. return 'MeshStandardNodeMaterial';
  14508. }
  14509. /**
  14510. * Constructs a new mesh standard node material.
  14511. *
  14512. * @param {Object?} parameters - The configuration parameter.
  14513. */
  14514. constructor( parameters ) {
  14515. super();
  14516. /**
  14517. * This flag can be used for type testing.
  14518. *
  14519. * @type {Boolean}
  14520. * @readonly
  14521. * @default true
  14522. */
  14523. this.isMeshStandardNodeMaterial = true;
  14524. /**
  14525. * Set to `true` because standard materials react on lights.
  14526. *
  14527. * @type {Boolean}
  14528. * @default true
  14529. */
  14530. this.lights = true;
  14531. /**
  14532. * The emissive color of standard materials is by default inferred from the `emissive`,
  14533. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  14534. * overwrite the default and define the emissive color with a node instead.
  14535. *
  14536. * If you don't want to overwrite the emissive color but modify the existing
  14537. * value instead, use {@link module:MaterialNode.materialEmissive}.
  14538. *
  14539. * @type {Node<vec3>?}
  14540. * @default null
  14541. */
  14542. this.emissiveNode = null;
  14543. /**
  14544. * The metalness of standard materials is by default inferred from the `metalness`,
  14545. * and `metalnessMap` properties. This node property allows to
  14546. * overwrite the default and define the metalness with a node instead.
  14547. *
  14548. * If you don't want to overwrite the metalness but modify the existing
  14549. * value instead, use {@link module:MaterialNode.materialMetalness}.
  14550. *
  14551. * @type {Node<float>?}
  14552. * @default null
  14553. */
  14554. this.metalnessNode = null;
  14555. /**
  14556. * The roughness of standard materials is by default inferred from the `roughness`,
  14557. * and `roughnessMap` properties. This node property allows to
  14558. * overwrite the default and define the roughness with a node instead.
  14559. *
  14560. * If you don't want to overwrite the roughness but modify the existing
  14561. * value instead, use {@link module:MaterialNode.materialRoughness}.
  14562. *
  14563. * @type {Node<float>?}
  14564. * @default null
  14565. */
  14566. this.roughnessNode = null;
  14567. this.setDefaultValues( _defaultValues$6 );
  14568. this.setValues( parameters );
  14569. }
  14570. /**
  14571. * Overwritten since this type of material uses {@link EnvironmentNode}
  14572. * to implement the PBR (PMREM based) environment mapping. Besides, the
  14573. * method honors `Scene.environment`.
  14574. *
  14575. * @param {NodeBuilder} builder - The current node builder.
  14576. * @return {EnvironmentNode<vec3>?} The environment node.
  14577. */
  14578. setupEnvironment( builder ) {
  14579. let envNode = super.setupEnvironment( builder );
  14580. if ( envNode === null && builder.environmentNode ) {
  14581. envNode = builder.environmentNode;
  14582. }
  14583. return envNode ? new EnvironmentNode( envNode ) : null;
  14584. }
  14585. /**
  14586. * Setups the lighting model.
  14587. *
  14588. * @return {PhysicalLightingModel} The lighting model.
  14589. */
  14590. setupLightingModel( /*builder*/ ) {
  14591. return new PhysicalLightingModel();
  14592. }
  14593. /**
  14594. * Setups the specular related node variables.
  14595. */
  14596. setupSpecular() {
  14597. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  14598. specularColor.assign( specularColorNode );
  14599. specularF90.assign( 1.0 );
  14600. }
  14601. /**
  14602. * Setups the standard specific node variables.
  14603. *
  14604. * @param {NodeBuilder} builder - The current node builder.
  14605. */
  14606. setupVariants() {
  14607. // METALNESS
  14608. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  14609. metalness.assign( metalnessNode );
  14610. // ROUGHNESS
  14611. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  14612. roughnessNode = getRoughness( { roughness: roughnessNode } );
  14613. roughness.assign( roughnessNode );
  14614. // SPECULAR COLOR
  14615. this.setupSpecular();
  14616. // DIFFUSE COLOR
  14617. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  14618. }
  14619. copy( source ) {
  14620. this.emissiveNode = source.emissiveNode;
  14621. this.metalnessNode = source.metalnessNode;
  14622. this.roughnessNode = source.roughnessNode;
  14623. return super.copy( source );
  14624. }
  14625. }
  14626. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  14627. /**
  14628. * Node material version of `MeshPhysicalMaterial`.
  14629. *
  14630. * @augments MeshStandardNodeMaterial
  14631. */
  14632. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  14633. static get type() {
  14634. return 'MeshPhysicalNodeMaterial';
  14635. }
  14636. /**
  14637. * Constructs a new mesh physical node material.
  14638. *
  14639. * @param {Object?} parameters - The configuration parameter.
  14640. */
  14641. constructor( parameters ) {
  14642. super();
  14643. /**
  14644. * This flag can be used for type testing.
  14645. *
  14646. * @type {Boolean}
  14647. * @readonly
  14648. * @default true
  14649. */
  14650. this.isMeshPhysicalNodeMaterial = true;
  14651. /**
  14652. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  14653. * and `clearcoatMap` properties. This node property allows to overwrite the default
  14654. * and define the clearcoat with a node instead.
  14655. *
  14656. * If you don't want to overwrite the clearcoat but modify the existing
  14657. * value instead, use {@link module:MaterialNode.materialClearcoat}.
  14658. *
  14659. * @type {Node<float>?}
  14660. * @default null
  14661. */
  14662. this.clearcoatNode = null;
  14663. /**
  14664. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  14665. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  14666. * and define the clearcoat roughness with a node instead.
  14667. *
  14668. * If you don't want to overwrite the clearcoat roughness but modify the existing
  14669. * value instead, use {@link module:MaterialNode.materialClearcoatRoughness}.
  14670. *
  14671. * @type {Node<float>?}
  14672. * @default null
  14673. */
  14674. this.clearcoatRoughnessNode = null;
  14675. /**
  14676. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  14677. * property. This node property allows to overwrite the default
  14678. * and define the clearcoat normal with a node instead.
  14679. *
  14680. * If you don't want to overwrite the clearcoat normal but modify the existing
  14681. * value instead, use {@link module:MaterialNode.materialClearcoatNormal}.
  14682. *
  14683. * @type {Node<vec3>?}
  14684. * @default null
  14685. */
  14686. this.clearcoatNormalNode = null;
  14687. /**
  14688. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  14689. * and `sheenColorMap` properties. This node property allows to overwrite the default
  14690. * and define the sheen with a node instead.
  14691. *
  14692. * If you don't want to overwrite the sheen but modify the existing
  14693. * value instead, use {@link module:MaterialNode.materialSheen}.
  14694. *
  14695. * @type {Node<vec3>?}
  14696. * @default null
  14697. */
  14698. this.sheenNode = null;
  14699. /**
  14700. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  14701. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  14702. * and define the sheen roughness with a node instead.
  14703. *
  14704. * If you don't want to overwrite the sheen roughness but modify the existing
  14705. * value instead, use {@link module:MaterialNode.materialSheenRoughness}.
  14706. *
  14707. * @type {Node<float>?}
  14708. * @default null
  14709. */
  14710. this.sheenRoughnessNode = null;
  14711. /**
  14712. * The iridescence of physical materials is by default inferred from the `iridescence`
  14713. * property. This node property allows to overwrite the default
  14714. * and define the iridescence with a node instead.
  14715. *
  14716. * If you don't want to overwrite the iridescence but modify the existing
  14717. * value instead, use {@link module:MaterialNode.materialIridescence}.
  14718. *
  14719. * @type {Node<float>?}
  14720. * @default null
  14721. */
  14722. this.iridescenceNode = null;
  14723. /**
  14724. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  14725. * property. This node property allows to overwrite the default
  14726. * and define the iridescence IOR with a node instead.
  14727. *
  14728. * If you don't want to overwrite the iridescence IOR but modify the existing
  14729. * value instead, use {@link module:MaterialNode.materialIridescenceIOR}.
  14730. *
  14731. * @type {Node<float>?}
  14732. * @default null
  14733. */
  14734. this.iridescenceIORNode = null;
  14735. /**
  14736. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  14737. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  14738. * and define the iridescence thickness with a node instead.
  14739. *
  14740. * If you don't want to overwrite the iridescence thickness but modify the existing
  14741. * value instead, use {@link module:MaterialNode.materialIridescenceThickness}.
  14742. *
  14743. * @type {Node<float>?}
  14744. * @default null
  14745. */
  14746. this.iridescenceThicknessNode = null;
  14747. /**
  14748. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  14749. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  14750. * and define the specular intensity with a node instead.
  14751. *
  14752. * If you don't want to overwrite the specular intensity but modify the existing
  14753. * value instead, use {@link module:MaterialNode.materialSpecularIntensity}.
  14754. *
  14755. * @type {Node<float>?}
  14756. * @default null
  14757. */
  14758. this.specularIntensityNode = null;
  14759. /**
  14760. * The specular color of physical materials is by default inferred from the `specularColor`
  14761. * and `specularColorMap` properties. This node property allows to overwrite the default
  14762. * and define the specular color with a node instead.
  14763. *
  14764. * If you don't want to overwrite the specular color but modify the existing
  14765. * value instead, use {@link module:MaterialNode.materialSpecularColor}.
  14766. *
  14767. * @type {Node<vec3>?}
  14768. * @default null
  14769. */
  14770. this.specularColorNode = null;
  14771. /**
  14772. * The ior of physical materials is by default inferred from the `ior`
  14773. * property. This node property allows to overwrite the default
  14774. * and define the ior with a node instead.
  14775. *
  14776. * If you don't want to overwrite the ior but modify the existing
  14777. * value instead, use {@link module:MaterialNode.materialIOR}.
  14778. *
  14779. * @type {Node<float>?}
  14780. * @default null
  14781. */
  14782. this.iorNode = null;
  14783. /**
  14784. * The transmission of physical materials is by default inferred from the `transmission` and
  14785. * `transmissionMap` properties. This node property allows to overwrite the default
  14786. * and define the transmission with a node instead.
  14787. *
  14788. * If you don't want to overwrite the transmission but modify the existing
  14789. * value instead, use {@link module:MaterialNode.materialTransmission}.
  14790. *
  14791. * @type {Node<float>?}
  14792. * @default null
  14793. */
  14794. this.transmissionNode = null;
  14795. /**
  14796. * The thickness of physical materials is by default inferred from the `thickness` and
  14797. * `thicknessMap` properties. This node property allows to overwrite the default
  14798. * and define the thickness with a node instead.
  14799. *
  14800. * If you don't want to overwrite the thickness but modify the existing
  14801. * value instead, use {@link module:MaterialNode.materialThickness}.
  14802. *
  14803. * @type {Node<float>?}
  14804. * @default null
  14805. */
  14806. this.thicknessNode = null;
  14807. /**
  14808. * The attenuation distance of physical materials is by default inferred from the
  14809. * `attenuationDistance` property. This node property allows to overwrite the default
  14810. * and define the attenuation distance with a node instead.
  14811. *
  14812. * If you don't want to overwrite the attenuation distance but modify the existing
  14813. * value instead, use {@link module:MaterialNode.materialAttenuationDistance}.
  14814. *
  14815. * @type {Node<float>?}
  14816. * @default null
  14817. */
  14818. this.attenuationDistanceNode = null;
  14819. /**
  14820. * The attenuation color of physical materials is by default inferred from the
  14821. * `attenuationColor` property. This node property allows to overwrite the default
  14822. * and define the attenuation color with a node instead.
  14823. *
  14824. * If you don't want to overwrite the attenuation color but modify the existing
  14825. * value instead, use {@link module:MaterialNode.materialAttenuationColor}.
  14826. *
  14827. * @type {Node<vec3>?}
  14828. * @default null
  14829. */
  14830. this.attenuationColorNode = null;
  14831. /**
  14832. * The dispersion of physical materials is by default inferred from the
  14833. * `dispersion` property. This node property allows to overwrite the default
  14834. * and define the dispersion with a node instead.
  14835. *
  14836. * If you don't want to overwrite the dispersion but modify the existing
  14837. * value instead, use {@link module:MaterialNode.materialDispersion}.
  14838. *
  14839. * @type {Node<float>?}
  14840. * @default null
  14841. */
  14842. this.dispersionNode = null;
  14843. /**
  14844. * The anisotropy of physical materials is by default inferred from the
  14845. * `anisotropy` property. This node property allows to overwrite the default
  14846. * and define the anisotropy with a node instead.
  14847. *
  14848. * If you don't want to overwrite the anisotropy but modify the existing
  14849. * value instead, use {@link module:MaterialNode.materialAnisotropy}.
  14850. *
  14851. * @type {Node<float>?}
  14852. * @default null
  14853. */
  14854. this.anisotropyNode = null;
  14855. this.setDefaultValues( _defaultValues$5 );
  14856. this.setValues( parameters );
  14857. }
  14858. /**
  14859. * Whether the lighting model should use clearcoat or not.
  14860. *
  14861. * @type {Boolean}
  14862. * @default true
  14863. */
  14864. get useClearcoat() {
  14865. return this.clearcoat > 0 || this.clearcoatNode !== null;
  14866. }
  14867. /**
  14868. * Whether the lighting model should use iridescence or not.
  14869. *
  14870. * @type {Boolean}
  14871. * @default true
  14872. */
  14873. get useIridescence() {
  14874. return this.iridescence > 0 || this.iridescenceNode !== null;
  14875. }
  14876. /**
  14877. * Whether the lighting model should use sheen or not.
  14878. *
  14879. * @type {Boolean}
  14880. * @default true
  14881. */
  14882. get useSheen() {
  14883. return this.sheen > 0 || this.sheenNode !== null;
  14884. }
  14885. /**
  14886. * Whether the lighting model should use anisotropy or not.
  14887. *
  14888. * @type {Boolean}
  14889. * @default true
  14890. */
  14891. get useAnisotropy() {
  14892. return this.anisotropy > 0 || this.anisotropyNode !== null;
  14893. }
  14894. /**
  14895. * Whether the lighting model should use transmission or not.
  14896. *
  14897. * @type {Boolean}
  14898. * @default true
  14899. */
  14900. get useTransmission() {
  14901. return this.transmission > 0 || this.transmissionNode !== null;
  14902. }
  14903. /**
  14904. * Whether the lighting model should use dispersion or not.
  14905. *
  14906. * @type {Boolean}
  14907. * @default true
  14908. */
  14909. get useDispersion() {
  14910. return this.dispersion > 0 || this.dispersionNode !== null;
  14911. }
  14912. /**
  14913. * Setups the specular related node variables.
  14914. */
  14915. setupSpecular() {
  14916. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  14917. ior.assign( iorNode );
  14918. specularColor.assign( mix( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ), diffuseColor.rgb, metalness ) );
  14919. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  14920. }
  14921. /**
  14922. * Setups the lighting model.
  14923. *
  14924. * @return {PhysicalLightingModel} The lighting model.
  14925. */
  14926. setupLightingModel( /*builder*/ ) {
  14927. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  14928. }
  14929. /**
  14930. * Setups the physical specific node variables.
  14931. *
  14932. * @param {NodeBuilder} builder - The current node builder.
  14933. */
  14934. setupVariants( builder ) {
  14935. super.setupVariants( builder );
  14936. // CLEARCOAT
  14937. if ( this.useClearcoat ) {
  14938. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  14939. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  14940. clearcoat.assign( clearcoatNode );
  14941. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  14942. }
  14943. // SHEEN
  14944. if ( this.useSheen ) {
  14945. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  14946. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  14947. sheen.assign( sheenNode );
  14948. sheenRoughness.assign( sheenRoughnessNode );
  14949. }
  14950. // IRIDESCENCE
  14951. if ( this.useIridescence ) {
  14952. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  14953. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  14954. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  14955. iridescence.assign( iridescenceNode );
  14956. iridescenceIOR.assign( iridescenceIORNode );
  14957. iridescenceThickness.assign( iridescenceThicknessNode );
  14958. }
  14959. // ANISOTROPY
  14960. if ( this.useAnisotropy ) {
  14961. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  14962. anisotropy.assign( anisotropyV.length() );
  14963. If( anisotropy.equal( 0.0 ), () => {
  14964. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  14965. } ).Else( () => {
  14966. anisotropyV.divAssign( vec2( anisotropy ) );
  14967. anisotropy.assign( anisotropy.saturate() );
  14968. } );
  14969. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  14970. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  14971. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  14972. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  14973. }
  14974. // TRANSMISSION
  14975. if ( this.useTransmission ) {
  14976. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  14977. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  14978. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  14979. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  14980. transmission.assign( transmissionNode );
  14981. thickness.assign( thicknessNode );
  14982. attenuationDistance.assign( attenuationDistanceNode );
  14983. attenuationColor.assign( attenuationColorNode );
  14984. if ( this.useDispersion ) {
  14985. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  14986. dispersion.assign( dispersionNode );
  14987. }
  14988. }
  14989. }
  14990. /**
  14991. * Setups the clearcoat normal node.
  14992. *
  14993. * @return {Node<vec3>} The clearcoat noraml.
  14994. */
  14995. setupClearcoatNormal() {
  14996. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  14997. }
  14998. setup( builder ) {
  14999. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  15000. super.setup( builder );
  15001. }
  15002. copy( source ) {
  15003. this.clearcoatNode = source.clearcoatNode;
  15004. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  15005. this.clearcoatNormalNode = source.clearcoatNormalNode;
  15006. this.sheenNode = source.sheenNode;
  15007. this.sheenRoughnessNode = source.sheenRoughnessNode;
  15008. this.iridescenceNode = source.iridescenceNode;
  15009. this.iridescenceIORNode = source.iridescenceIORNode;
  15010. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  15011. this.specularIntensityNode = source.specularIntensityNode;
  15012. this.specularColorNode = source.specularColorNode;
  15013. this.transmissionNode = source.transmissionNode;
  15014. this.thicknessNode = source.thicknessNode;
  15015. this.attenuationDistanceNode = source.attenuationDistanceNode;
  15016. this.attenuationColorNode = source.attenuationColorNode;
  15017. this.dispersionNode = source.dispersionNode;
  15018. this.anisotropyNode = source.anisotropyNode;
  15019. return super.copy( source );
  15020. }
  15021. }
  15022. /** @module MeshSSSNodeMaterial **/
  15023. /**
  15024. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  15025. *
  15026. * @augments PhysicalLightingModel
  15027. */
  15028. class SSSLightingModel extends PhysicalLightingModel {
  15029. /**
  15030. * Constructs a new physical lighting model.
  15031. *
  15032. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15033. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  15034. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  15035. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15036. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  15037. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  15038. * @param {Boolean} [sss=false] - Whether SSS is supported or not.
  15039. */
  15040. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  15041. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  15042. /**
  15043. * Whether the lighting model should use SSS or not.
  15044. *
  15045. * @type {Boolean}
  15046. * @default false
  15047. */
  15048. this.useSSS = sss;
  15049. }
  15050. /**
  15051. * Extends the default implementation with a SSS term.
  15052. *
  15053. * Reference: [Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look]{@link https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/}
  15054. *
  15055. * @param {Object} input - The input data.
  15056. * @param {StackNode} stack - The current stack.
  15057. * @param {NodeBuilder} builder - The current node builder.
  15058. */
  15059. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15060. if ( this.useSSS === true ) {
  15061. const material = builder.material;
  15062. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  15063. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  15064. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  15065. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  15066. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  15067. }
  15068. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  15069. }
  15070. }
  15071. /**
  15072. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  15073. * that implements a Subsurface scattering (SSS) term.
  15074. *
  15075. * @augments MeshPhysicalNodeMaterial
  15076. */
  15077. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15078. static get type() {
  15079. return 'MeshSSSNodeMaterial';
  15080. }
  15081. /**
  15082. * Constructs a new mesh SSS node material.
  15083. *
  15084. * @param {Object?} parameters - The configuration parameter.
  15085. */
  15086. constructor( parameters ) {
  15087. super( parameters );
  15088. /**
  15089. * Represents the thickness color.
  15090. *
  15091. * @type {Node<vec3>?}
  15092. * @default null
  15093. */
  15094. this.thicknessColorNode = null;
  15095. /**
  15096. * Represents the distortion factor.
  15097. *
  15098. * @type {Node<float>?}
  15099. */
  15100. this.thicknessDistortionNode = float( 0.1 );
  15101. /**
  15102. * Represents the thickness ambient factor.
  15103. *
  15104. * @type {Node<float>?}
  15105. */
  15106. this.thicknessAmbientNode = float( 0.0 );
  15107. /**
  15108. * Represents the thickness attenuation.
  15109. *
  15110. * @type {Node<float>?}
  15111. */
  15112. this.thicknessAttenuationNode = float( .1 );
  15113. /**
  15114. * Represents the thickness power.
  15115. *
  15116. * @type {Node<float>?}
  15117. */
  15118. this.thicknessPowerNode = float( 2.0 );
  15119. /**
  15120. * Represents the thickness scale.
  15121. *
  15122. * @type {Node<float>?}
  15123. */
  15124. this.thicknessScaleNode = float( 10.0 );
  15125. }
  15126. /**
  15127. * Whether the lighting model should use SSS or not.
  15128. *
  15129. * @type {Boolean}
  15130. * @default true
  15131. */
  15132. get useSSS() {
  15133. return this.thicknessColorNode !== null;
  15134. }
  15135. /**
  15136. * Setups the lighting model.
  15137. *
  15138. * @return {SSSLightingModel} The lighting model.
  15139. */
  15140. setupLightingModel( /*builder*/ ) {
  15141. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15142. }
  15143. copy( source ) {
  15144. this.thicknessColorNode = source.thicknessColorNode;
  15145. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15146. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15147. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15148. this.thicknessPowerNode = source.thicknessPowerNode;
  15149. this.thicknessScaleNode = source.thicknessScaleNode;
  15150. return super.copy( source );
  15151. }
  15152. }
  15153. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15154. // dotNL will be from -1.0 to 1.0
  15155. const dotNL = normal.dot( lightDirection );
  15156. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15157. if ( builder.material.gradientMap ) {
  15158. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15159. return vec3( gradientMap.r );
  15160. } else {
  15161. const fw = coord.fwidth().mul( 0.5 );
  15162. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15163. }
  15164. } );
  15165. /**
  15166. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15167. *
  15168. * @augments LightingModel
  15169. */
  15170. class ToonLightingModel extends LightingModel {
  15171. /**
  15172. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15173. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15174. *
  15175. * @param {Object} input - The input data.
  15176. * @param {StackNode} stack - The current stack.
  15177. * @param {NodeBuilder} builder - The current node builder.
  15178. */
  15179. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15180. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15181. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15182. }
  15183. /**
  15184. * Implements the indirect lighting.
  15185. *
  15186. * @param {ContextNode} input - The current node context.
  15187. * @param {StackNode} stack - The current stack.
  15188. * @param {NodeBuilder} builder - The current node builder.
  15189. */
  15190. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15191. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15192. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15193. }
  15194. }
  15195. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15196. /**
  15197. * Node material version of `MeshToonMaterial`.
  15198. *
  15199. * @augments NodeMaterial
  15200. */
  15201. class MeshToonNodeMaterial extends NodeMaterial {
  15202. static get type() {
  15203. return 'MeshToonNodeMaterial';
  15204. }
  15205. /**
  15206. * Constructs a new mesh toon node material.
  15207. *
  15208. * @param {Object?} parameters - The configuration parameter.
  15209. */
  15210. constructor( parameters ) {
  15211. super();
  15212. /**
  15213. * This flag can be used for type testing.
  15214. *
  15215. * @type {Boolean}
  15216. * @readonly
  15217. * @default true
  15218. */
  15219. this.isMeshToonNodeMaterial = true;
  15220. /**
  15221. * Set to `true` because toon materials react on lights.
  15222. *
  15223. * @type {Boolean}
  15224. * @default true
  15225. */
  15226. this.lights = true;
  15227. this.setDefaultValues( _defaultValues$4 );
  15228. this.setValues( parameters );
  15229. }
  15230. /**
  15231. * Setups the lighting model.
  15232. *
  15233. * @return {ToonLightingModel} The lighting model.
  15234. */
  15235. setupLightingModel( /*builder*/ ) {
  15236. return new ToonLightingModel();
  15237. }
  15238. }
  15239. /** @module MatcapUVNode **/
  15240. /**
  15241. * Can be used to compute texture coordinates for projecting a
  15242. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15243. *
  15244. * @augments TempNode
  15245. */
  15246. class MatcapUVNode extends TempNode {
  15247. static get type() {
  15248. return 'MatcapUVNode';
  15249. }
  15250. /**
  15251. * Constructs a new matcap uv node.
  15252. */
  15253. constructor() {
  15254. super( 'vec2' );
  15255. }
  15256. setup() {
  15257. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15258. const y = positionViewDirection.cross( x );
  15259. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15260. }
  15261. }
  15262. /**
  15263. * TSL function for creating a matcap uv node.
  15264. *
  15265. * @function
  15266. * @returns {MatcapUVNode}
  15267. */
  15268. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15269. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15270. /**
  15271. * Node material version of `MeshMatcapMaterial`.
  15272. *
  15273. * @augments NodeMaterial
  15274. */
  15275. class MeshMatcapNodeMaterial extends NodeMaterial {
  15276. static get type() {
  15277. return 'MeshMatcapNodeMaterial';
  15278. }
  15279. /**
  15280. * Constructs a new mesh normal node material.
  15281. *
  15282. * @param {Object?} parameters - The configuration parameter.
  15283. */
  15284. constructor( parameters ) {
  15285. super();
  15286. /**
  15287. * This flag can be used for type testing.
  15288. *
  15289. * @type {Boolean}
  15290. * @readonly
  15291. * @default true
  15292. */
  15293. this.isMeshMatcapNodeMaterial = true;
  15294. this.setDefaultValues( _defaultValues$3 );
  15295. this.setValues( parameters );
  15296. }
  15297. /**
  15298. * Setups the matcap specific node variables.
  15299. *
  15300. * @param {NodeBuilder} builder - The current node builder.
  15301. */
  15302. setupVariants( builder ) {
  15303. const uv = matcapUV;
  15304. let matcapColor;
  15305. if ( builder.material.matcap ) {
  15306. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15307. } else {
  15308. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15309. }
  15310. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15311. }
  15312. }
  15313. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  15314. /**
  15315. * Node material version of `PointsMaterial`.
  15316. *
  15317. * Since WebGPU can render point primitives only with a size of one pixel,
  15318. * this material type does not evaluate the `size` and `sizeAttenuation`
  15319. * property of `PointsMaterial`. Use {@link InstancedPointsNodeMaterial}
  15320. * instead if you need points with a size larger than one pixel.
  15321. *
  15322. * @augments NodeMaterial
  15323. */
  15324. class PointsNodeMaterial extends NodeMaterial {
  15325. static get type() {
  15326. return 'PointsNodeMaterial';
  15327. }
  15328. /**
  15329. * Constructs a new points node material.
  15330. *
  15331. * @param {Object?} parameters - The configuration parameter.
  15332. */
  15333. constructor( parameters ) {
  15334. super();
  15335. /**
  15336. * This flag can be used for type testing.
  15337. *
  15338. * @type {Boolean}
  15339. * @readonly
  15340. * @default true
  15341. */
  15342. this.isPointsNodeMaterial = true;
  15343. this.setDefaultValues( _defaultValues$2 );
  15344. this.setValues( parameters );
  15345. }
  15346. }
  15347. /** @module RotateNode **/
  15348. /**
  15349. * Applies a rotation to the given position node.
  15350. *
  15351. * @augments TempNode
  15352. */
  15353. class RotateNode extends TempNode {
  15354. static get type() {
  15355. return 'RotateNode';
  15356. }
  15357. /**
  15358. * Constructs a new rotate node.
  15359. *
  15360. * @param {Node} positionNode - The position node.
  15361. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15362. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15363. */
  15364. constructor( positionNode, rotationNode ) {
  15365. super();
  15366. /**
  15367. * The position node.
  15368. *
  15369. * @type {Node}
  15370. */
  15371. this.positionNode = positionNode;
  15372. /**
  15373. * Represents the rotation that is applied to the position node.
  15374. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15375. *
  15376. * @type {Node}
  15377. */
  15378. this.rotationNode = rotationNode;
  15379. }
  15380. /**
  15381. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15382. *
  15383. * @param {NodeBuilder} builder - The current node builder.
  15384. * @return {String} The node's type.
  15385. */
  15386. getNodeType( builder ) {
  15387. return this.positionNode.getNodeType( builder );
  15388. }
  15389. setup( builder ) {
  15390. const { rotationNode, positionNode } = this;
  15391. const nodeType = this.getNodeType( builder );
  15392. if ( nodeType === 'vec2' ) {
  15393. const cosAngle = rotationNode.cos();
  15394. const sinAngle = rotationNode.sin();
  15395. const rotationMatrix = mat2(
  15396. cosAngle, sinAngle,
  15397. sinAngle.negate(), cosAngle
  15398. );
  15399. return rotationMatrix.mul( positionNode );
  15400. } else {
  15401. const rotation = rotationNode;
  15402. const rotationXMatrix = mat4( vec4( 1.0, 0.0, 0.0, 0.0 ), vec4( 0.0, cos( rotation.x ), sin( rotation.x ).negate(), 0.0 ), vec4( 0.0, sin( rotation.x ), cos( rotation.x ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  15403. const rotationYMatrix = mat4( vec4( cos( rotation.y ), 0.0, sin( rotation.y ), 0.0 ), vec4( 0.0, 1.0, 0.0, 0.0 ), vec4( sin( rotation.y ).negate(), 0.0, cos( rotation.y ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  15404. const rotationZMatrix = mat4( vec4( cos( rotation.z ), sin( rotation.z ).negate(), 0.0, 0.0 ), vec4( sin( rotation.z ), cos( rotation.z ), 0.0, 0.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  15405. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15406. }
  15407. }
  15408. }
  15409. /**
  15410. * TSL function for creating a rotate node.
  15411. *
  15412. * @function
  15413. * @param {Node} positionNode - The position node.
  15414. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15415. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15416. * @returns {RotateNode}
  15417. */
  15418. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15419. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  15420. /**
  15421. * Node material version of `SpriteMaterial`.
  15422. *
  15423. * @augments NodeMaterial
  15424. */
  15425. class SpriteNodeMaterial extends NodeMaterial {
  15426. static get type() {
  15427. return 'SpriteNodeMaterial';
  15428. }
  15429. /**
  15430. * Constructs a new sprite node material.
  15431. *
  15432. * @param {Object?} parameters - The configuration parameter.
  15433. */
  15434. constructor( parameters ) {
  15435. super();
  15436. /**
  15437. * This flag can be used for type testing.
  15438. *
  15439. * @type {Boolean}
  15440. * @readonly
  15441. * @default true
  15442. */
  15443. this.isSpriteNodeMaterial = true;
  15444. this._useSizeAttenuation = true;
  15445. /**
  15446. * This property makes it possible to define the position of the sprite with a
  15447. * node. That can be useful when the material is used with instanced rendering
  15448. * and node data are defined with an instanced attribute node:
  15449. * ```js
  15450. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15451. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15452. * ```
  15453. * Another possibility is to compute the instanced data with a compute shader:
  15454. * ```js
  15455. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15456. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15457. * ```
  15458. *
  15459. * @type {Node<vec2>?}
  15460. * @default null
  15461. */
  15462. this.positionNode = null;
  15463. /**
  15464. * The rotation of sprite materials is by default inferred from the `rotation`,
  15465. * property. This node property allows to overwrite the default and define
  15466. * the rotation with a node instead.
  15467. *
  15468. * If you don't want to overwrite the rotation but modify the existing
  15469. * value instead, use {@link module:MaterialNode.materialRotation}.
  15470. *
  15471. * @type {Node<float>?}
  15472. * @default null
  15473. */
  15474. this.rotationNode = null;
  15475. /**
  15476. * This node property provides an additional way to scale sprites next to
  15477. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15478. * is multiplied with the scale value of this node in the vertex shader.
  15479. *
  15480. * @type {Node<vec2>?}
  15481. * @default null
  15482. */
  15483. this.scaleNode = null;
  15484. this.setDefaultValues( _defaultValues$1 );
  15485. this.setValues( parameters );
  15486. }
  15487. /**
  15488. * Setups the position node in view space. This method implements
  15489. * the sprite specific vertex shader.
  15490. *
  15491. * @param {NodeBuilder} builder - The current node builder.
  15492. * @return {Node<vec3>} The position in view space.
  15493. */
  15494. setupPositionView( builder ) {
  15495. const { object, camera } = builder;
  15496. const sizeAttenuation = this.sizeAttenuation;
  15497. const { positionNode, rotationNode, scaleNode } = this;
  15498. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15499. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15500. if ( scaleNode !== null ) {
  15501. scale = scale.mul( scaleNode );
  15502. }
  15503. if ( sizeAttenuation === false ) {
  15504. if ( camera.isPerspectiveCamera ) {
  15505. scale = scale.mul( mvPosition.z.negate() );
  15506. } else {
  15507. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15508. scale = scale.mul( orthoScale.mul( 2 ) );
  15509. }
  15510. }
  15511. let alignedPosition = positionGeometry.xy;
  15512. if ( object.center && object.center.isVector2 === true ) {
  15513. const center = reference$1( 'center', 'vec2', object );
  15514. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15515. }
  15516. alignedPosition = alignedPosition.mul( scale );
  15517. const rotation = float( rotationNode || materialRotation );
  15518. const rotatedPosition = rotate( alignedPosition, rotation );
  15519. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15520. }
  15521. copy( source ) {
  15522. this.positionNode = source.positionNode;
  15523. this.rotationNode = source.rotationNode;
  15524. this.scaleNode = source.scaleNode;
  15525. return super.copy( source );
  15526. }
  15527. /**
  15528. * Whether to use size attenuation or not.
  15529. *
  15530. * @type {Boolean}
  15531. * @default true
  15532. */
  15533. get sizeAttenuation() {
  15534. return this._useSizeAttenuation;
  15535. }
  15536. set sizeAttenuation( value ) {
  15537. if ( this._useSizeAttenuation !== value ) {
  15538. this._useSizeAttenuation = value;
  15539. this.needsUpdate = true;
  15540. }
  15541. }
  15542. }
  15543. /**
  15544. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  15545. *
  15546. * @augments LightingModel
  15547. */
  15548. class ShadowMaskModel extends LightingModel {
  15549. /**
  15550. * Constructs a new shadow mask model.
  15551. */
  15552. constructor() {
  15553. super();
  15554. /**
  15555. * The shadow mask node.
  15556. *
  15557. * @type {Node}
  15558. */
  15559. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  15560. }
  15561. /**
  15562. * Only used to save the shadow mask.
  15563. *
  15564. * @param {Object} input - The input data.
  15565. */
  15566. direct( { shadowMask } ) {
  15567. this.shadowNode.mulAssign( shadowMask );
  15568. }
  15569. /**
  15570. * Uses the shadow mask to produce the final color.
  15571. *
  15572. * @param {ContextNode} context - The current node context.
  15573. */
  15574. finish( context ) {
  15575. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  15576. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  15577. }
  15578. }
  15579. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  15580. /**
  15581. * Node material version of `ShadowMaterial`.
  15582. *
  15583. * @augments NodeMaterial
  15584. */
  15585. class ShadowNodeMaterial extends NodeMaterial {
  15586. static get type() {
  15587. return 'ShadowNodeMaterial';
  15588. }
  15589. /**
  15590. * Constructs a new shadow node material.
  15591. *
  15592. * @param {Object?} parameters - The configuration parameter.
  15593. */
  15594. constructor( parameters ) {
  15595. super();
  15596. /**
  15597. * This flag can be used for type testing.
  15598. *
  15599. * @type {Boolean}
  15600. * @readonly
  15601. * @default true
  15602. */
  15603. this.isShadowNodeMaterial = true;
  15604. /**
  15605. * Set to `true` because so it's possible to implement
  15606. * the shadow mask effect.
  15607. *
  15608. * @type {Boolean}
  15609. * @default true
  15610. */
  15611. this.lights = true;
  15612. this.setDefaultValues( _defaultValues );
  15613. this.setValues( parameters );
  15614. }
  15615. /**
  15616. * Setups the lighting model.
  15617. *
  15618. * @return {ShadowMaskModel} The lighting model.
  15619. */
  15620. setupLightingModel( /*builder*/ ) {
  15621. return new ShadowMaskModel();
  15622. }
  15623. }
  15624. /** @module Texture3DNode **/
  15625. const normal = Fn( ( { texture, uv } ) => {
  15626. const epsilon = 0.0001;
  15627. const ret = vec3().toVar();
  15628. If( uv.x.lessThan( epsilon ), () => {
  15629. ret.assign( vec3( 1, 0, 0 ) );
  15630. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  15631. ret.assign( vec3( 0, 1, 0 ) );
  15632. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  15633. ret.assign( vec3( 0, 0, 1 ) );
  15634. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  15635. ret.assign( vec3( - 1, 0, 0 ) );
  15636. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  15637. ret.assign( vec3( 0, - 1, 0 ) );
  15638. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  15639. ret.assign( vec3( 0, 0, - 1 ) );
  15640. } ).Else( () => {
  15641. const step = 0.01;
  15642. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  15643. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  15644. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  15645. ret.assign( vec3( x, y, z ) );
  15646. } );
  15647. return ret.normalize();
  15648. } );
  15649. /**
  15650. * This type of uniform node represents a 3D texture.
  15651. *
  15652. * @augments module:TextureNode~TextureNode
  15653. */
  15654. class Texture3DNode extends TextureNode {
  15655. static get type() {
  15656. return 'Texture3DNode';
  15657. }
  15658. /**
  15659. * Constructs a new 3D texture node.
  15660. *
  15661. * @param {Data3DTexture} value - The 3D texture.
  15662. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15663. * @param {Node<int>?} [levelNode=null] - The level node.
  15664. */
  15665. constructor( value, uvNode = null, levelNode = null ) {
  15666. super( value, uvNode, levelNode );
  15667. /**
  15668. * This flag can be used for type testing.
  15669. *
  15670. * @type {Boolean}
  15671. * @readonly
  15672. * @default true
  15673. */
  15674. this.isTexture3DNode = true;
  15675. }
  15676. /**
  15677. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  15678. *
  15679. * @param {NodeBuilder} builder - The current node builder.
  15680. * @return {String} The input type.
  15681. */
  15682. getInputType( /*builder*/ ) {
  15683. return 'texture3D';
  15684. }
  15685. /**
  15686. * Returns a default uv node which is in context of 3D textures a three-dimensional
  15687. * uv node.
  15688. *
  15689. * @return {Node<vec3>} The default uv node.
  15690. */
  15691. getDefaultUV() {
  15692. return vec3( 0.5, 0.5, 0.5 );
  15693. }
  15694. /**
  15695. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  15696. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  15697. *
  15698. * @param {Boolean} value - The update toggle.
  15699. */
  15700. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  15701. /**
  15702. * Overwrites the default implementation to return the unmodified uv node.
  15703. *
  15704. * @param {NodeBuilder} builder - The current node builder.
  15705. * @param {Node} uvNode - The uv node to setup.
  15706. * @return {Node} The unmodified uv node.
  15707. */
  15708. setupUV( builder, uvNode ) {
  15709. const texture = this.value;
  15710. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  15711. if ( this.sampler ) {
  15712. uvNode = uvNode.flipY();
  15713. } else {
  15714. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  15715. }
  15716. }
  15717. return uvNode;
  15718. }
  15719. /**
  15720. * Generates the uv code snippet.
  15721. *
  15722. * @param {NodeBuilder} builder - The current node builder.
  15723. * @param {Node} uvNode - The uv node to generate code for.
  15724. * @return {String} The generated code snippet.
  15725. */
  15726. generateUV( builder, uvNode ) {
  15727. return uvNode.build( builder, 'vec3' );
  15728. }
  15729. /**
  15730. * TODO.
  15731. *
  15732. * @param {Node<vec3>} uvNode - The uv node .
  15733. * @return {Node<vec3>} TODO.
  15734. */
  15735. normal( uvNode ) {
  15736. return normal( { texture: this, uv: uvNode } );
  15737. }
  15738. }
  15739. /**
  15740. * TSL function for creating a 3D texture node.
  15741. *
  15742. * @function
  15743. * @param {Data3DTexture} value - The 3D texture.
  15744. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15745. * @param {Node<int>?} [levelNode=null] - The level node.
  15746. * @returns {Texture3DNode}
  15747. */
  15748. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  15749. /** @module VolumeNodeMaterial **/
  15750. /**
  15751. * Node material intended for volume rendering. The volumetic data are
  15752. * defined with an instance of {@link Data3DTexture}.
  15753. *
  15754. * @augments NodeMaterial
  15755. */
  15756. class VolumeNodeMaterial extends NodeMaterial {
  15757. static get type() {
  15758. return 'VolumeNodeMaterial';
  15759. }
  15760. /**
  15761. * Constructs a new volume node material.
  15762. *
  15763. * @param {Object?} parameters - The configuration parameter.
  15764. */
  15765. constructor( parameters ) {
  15766. super();
  15767. /**
  15768. * This flag can be used for type testing.
  15769. *
  15770. * @type {Boolean}
  15771. * @readonly
  15772. * @default true
  15773. */
  15774. this.isVolumeNodeMaterial = true;
  15775. /**
  15776. * The base color of the volume.
  15777. *
  15778. * @type {Color}
  15779. * @default 100
  15780. */
  15781. this.base = new Color( 0xffffff );
  15782. /**
  15783. * A 3D data texture holding the volumetric data.
  15784. *
  15785. * @type {Data3DTexture?}
  15786. * @default null
  15787. */
  15788. this.map = null;
  15789. /**
  15790. * This number of samples for each ray that hits the mesh's surface
  15791. * and travels through the volume.
  15792. *
  15793. * @type {Number}
  15794. * @default 100
  15795. */
  15796. this.steps = 100;
  15797. /**
  15798. * Callback for {@link VolumeNodeMaterial#testNode}.
  15799. *
  15800. * @callback testNodeCallback
  15801. * @param {Data3DTexture<float>} map - The 3D texture.
  15802. * @param {Node<float>} mapValue - The sampled value inside the volume.
  15803. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  15804. * @param {Node<vec4>} finalColor - The final color.
  15805. */
  15806. /**
  15807. * The volume rendering of this material works by shooting rays
  15808. * from the camera position through each fragment of the mesh's
  15809. * surface and sample the inner volume in a raymarching fashion
  15810. * mutiple times.
  15811. *
  15812. * This node can be used to assign a callback function of type `Fn`
  15813. * that will be exexuted per sample. The callback receives the
  15814. * texture, the sampled texture value as well as position on the surface
  15815. * where the rays enters the volume. The last parameter is a color
  15816. * that allows the callback to determine the final color.
  15817. *
  15818. * @type {testNodeCallback?}
  15819. * @default null
  15820. */
  15821. this.testNode = null;
  15822. this.setValues( parameters );
  15823. }
  15824. /**
  15825. * Setups the vertex and fragment stage of this node material.
  15826. *
  15827. * @param {NodeBuilder} builder - The current node builder.
  15828. */
  15829. setup( builder ) {
  15830. const map = texture3D( this.map, null, 0 );
  15831. const hitBox = Fn( ( { orig, dir } ) => {
  15832. const box_min = vec3( - 0.5 );
  15833. const box_max = vec3( 0.5 );
  15834. const inv_dir = dir.reciprocal();
  15835. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  15836. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  15837. const tmin = min$1( tmin_tmp, tmax_tmp );
  15838. const tmax = max$1( tmin_tmp, tmax_tmp );
  15839. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  15840. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  15841. return vec2( t0, t1 );
  15842. } );
  15843. this.fragmentNode = Fn( () => {
  15844. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  15845. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  15846. const rayDir = vDirection.normalize();
  15847. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  15848. bounds.x.greaterThan( bounds.y ).discard();
  15849. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  15850. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  15851. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  15852. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  15853. delta.divAssign( materialReference( 'steps', 'float' ) );
  15854. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  15855. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  15856. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  15857. if ( this.testNode !== null ) {
  15858. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  15859. } else {
  15860. // default to show surface of mesh
  15861. ac.a.assign( 1 );
  15862. Break();
  15863. }
  15864. p.addAssign( rayDir.mul( delta ) );
  15865. } );
  15866. ac.a.equal( 0 ).discard();
  15867. return vec4( ac );
  15868. } )();
  15869. super.setup( builder );
  15870. }
  15871. }
  15872. /**
  15873. * This module manages the internal animation loop of the renderer.
  15874. *
  15875. * @private
  15876. */
  15877. class Animation {
  15878. /**
  15879. * Constructs a new animation loop management component.
  15880. *
  15881. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  15882. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  15883. */
  15884. constructor( nodes, info ) {
  15885. /**
  15886. * Renderer component for managing nodes related logic.
  15887. *
  15888. * @type {Nodes}
  15889. */
  15890. this.nodes = nodes;
  15891. /**
  15892. * Renderer component for managing metrics and monitoring data.
  15893. *
  15894. * @type {Info}
  15895. */
  15896. this.info = info;
  15897. /**
  15898. * A reference to the context from `requestAnimationFrame()` can
  15899. * be called (usually `window`).
  15900. *
  15901. * @type {Window|XRSession}
  15902. */
  15903. this._context = self;
  15904. /**
  15905. * The user-defined animation loop.
  15906. *
  15907. * @type {Function?}
  15908. * @default null
  15909. */
  15910. this._animationLoop = null;
  15911. /**
  15912. * The requestId whic is returned from the `requestAnimationFrame()` call.
  15913. * Can be used to cancel the stop the animation loop.
  15914. *
  15915. * @type {Number?}
  15916. * @default null
  15917. */
  15918. this._requestId = null;
  15919. }
  15920. /**
  15921. * Starts the internal animation loop.
  15922. */
  15923. start() {
  15924. const update = ( time, frame ) => {
  15925. this._requestId = this._context.requestAnimationFrame( update );
  15926. if ( this.info.autoReset === true ) this.info.reset();
  15927. this.nodes.nodeFrame.update();
  15928. this.info.frame = this.nodes.nodeFrame.frameId;
  15929. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  15930. };
  15931. update();
  15932. }
  15933. /**
  15934. * Stops the internal animation loop.
  15935. */
  15936. stop() {
  15937. this._context.cancelAnimationFrame( this._requestId );
  15938. this._requestId = null;
  15939. }
  15940. /**
  15941. * Defines the user-level animation loop.
  15942. *
  15943. * @param {Function} callback - The animation loop.
  15944. */
  15945. setAnimationLoop( callback ) {
  15946. this._animationLoop = callback;
  15947. }
  15948. /**
  15949. * Defines the context in which `requestAnimationFrame()` is executed.
  15950. *
  15951. * @param {Window|XRSession} context - The context to set.
  15952. */
  15953. setContext( context ) {
  15954. this._context = context;
  15955. }
  15956. /**
  15957. * Frees all internal resources and stops the animation loop.
  15958. */
  15959. dispose() {
  15960. this.stop();
  15961. }
  15962. }
  15963. /**
  15964. * Data structure for the renderer. It allows defining values
  15965. * with chained, hierarchical keys. Keys are meant to be
  15966. * objects since the module internally works with Weak Maps
  15967. * for perforamnce reasons.
  15968. *
  15969. * @private
  15970. */
  15971. class ChainMap {
  15972. /**
  15973. * Constructs a new chained map.
  15974. */
  15975. constructor() {
  15976. /**
  15977. * The root Weak Map.
  15978. *
  15979. * @type {WeakMap}
  15980. */
  15981. this.weakMap = new WeakMap();
  15982. }
  15983. /**
  15984. * Returns the value for the given array of keys.
  15985. *
  15986. * @param {Array<Object>} keys - List of keys.
  15987. * @return {Any} The value. Returns `undefined` if no value was found.
  15988. */
  15989. get( keys ) {
  15990. let map = this.weakMap;
  15991. for ( let i = 0; i < keys.length; i ++ ) {
  15992. map = map.get( keys[ i ] );
  15993. if ( map === undefined ) return undefined;
  15994. }
  15995. return map.get( keys[ keys.length - 1 ] );
  15996. }
  15997. /**
  15998. * Sets the value for the given keys.
  15999. *
  16000. * @param {Array<Object>} keys - List of keys.
  16001. * @param {Any} value - The value to set.
  16002. * @return {ChainMap} A reference to this chain map.
  16003. */
  16004. set( keys, value ) {
  16005. let map = this.weakMap;
  16006. for ( let i = 0; i < keys.length; i ++ ) {
  16007. const key = keys[ i ];
  16008. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  16009. map = map.get( key );
  16010. }
  16011. map.set( keys[ keys.length - 1 ], value );
  16012. return this;
  16013. }
  16014. /**
  16015. * Deletes a value for the given keys.
  16016. *
  16017. * @param {Array<Object>} keys - The keys.
  16018. * @return {Boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  16019. */
  16020. delete( keys ) {
  16021. let map = this.weakMap;
  16022. for ( let i = 0; i < keys.length; i ++ ) {
  16023. map = map.get( keys[ i ] );
  16024. if ( map === undefined ) return false;
  16025. }
  16026. return map.delete( keys[ keys.length - 1 ] );
  16027. }
  16028. }
  16029. let _id$9 = 0;
  16030. function getKeys( obj ) {
  16031. const keys = Object.keys( obj );
  16032. let proto = Object.getPrototypeOf( obj );
  16033. while ( proto ) {
  16034. const descriptors = Object.getOwnPropertyDescriptors( proto );
  16035. for ( const key in descriptors ) {
  16036. if ( descriptors[ key ] !== undefined ) {
  16037. const descriptor = descriptors[ key ];
  16038. if ( descriptor && typeof descriptor.get === 'function' ) {
  16039. keys.push( key );
  16040. }
  16041. }
  16042. }
  16043. proto = Object.getPrototypeOf( proto );
  16044. }
  16045. return keys;
  16046. }
  16047. /**
  16048. * A render object is the renderer's representation of single entity that gets drawn
  16049. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  16050. * scene since render objects also depend from the used material, the current render context
  16051. * and the current scene's lighting.
  16052. *
  16053. * In general, the basic process of the renderer is:
  16054. *
  16055. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  16056. * - Process the render lists by calling one or more render commands for each render item.
  16057. * - For each render command, request a render object and perform the draw.
  16058. *
  16059. * The module provides an interface to get data required for the draw command like the actual
  16060. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  16061. * creating render objects should only be done when necessary.
  16062. *
  16063. * @private
  16064. */
  16065. class RenderObject {
  16066. /**
  16067. * Constructs a new render object.
  16068. *
  16069. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16070. * @param {Geometries} geometries - Renderer component for managing geometries.
  16071. * @param {Renderer} renderer - The renderer.
  16072. * @param {Object3D} object - The 3D object.
  16073. * @param {Material} material - The 3D object's material.
  16074. * @param {Scene} scene - The scene the 3D object belongs to.
  16075. * @param {Camera} camera - The camera the object should be rendered with.
  16076. * @param {LightsNode} lightsNode - The lights node.
  16077. * @param {RenderContext} renderContext - The render context.
  16078. * @param {ClippingContext} clippingContext - The clipping context.
  16079. */
  16080. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  16081. this.id = _id$9 ++;
  16082. /**
  16083. * Renderer component for managing nodes related logic.
  16084. *
  16085. * @type {Nodes}
  16086. * @private
  16087. */
  16088. this._nodes = nodes;
  16089. /**
  16090. * Renderer component for managing geometries.
  16091. *
  16092. * @type {Geometries}
  16093. * @private
  16094. */
  16095. this._geometries = geometries;
  16096. /**
  16097. * The renderer.
  16098. *
  16099. * @type {Renderer}
  16100. */
  16101. this.renderer = renderer;
  16102. /**
  16103. * The 3D object.
  16104. *
  16105. * @type {Object3D}
  16106. */
  16107. this.object = object;
  16108. /**
  16109. * The 3D object's material.
  16110. *
  16111. * @type {Material}
  16112. */
  16113. this.material = material;
  16114. /**
  16115. * The scene the 3D object belongs to.
  16116. *
  16117. * @type {Scene}
  16118. */
  16119. this.scene = scene;
  16120. /**
  16121. * The camera the 3D object should be rendered with.
  16122. *
  16123. * @type {Camera}
  16124. */
  16125. this.camera = camera;
  16126. /**
  16127. * The lights node.
  16128. *
  16129. * @type {LightsNode}
  16130. */
  16131. this.lightsNode = lightsNode;
  16132. /**
  16133. * The render context.
  16134. *
  16135. * @type {RenderContext}
  16136. */
  16137. this.context = renderContext;
  16138. /**
  16139. * The 3D object's geometry.
  16140. *
  16141. * @type {BufferGeometry}
  16142. */
  16143. this.geometry = object.geometry;
  16144. /**
  16145. * The render object's version.
  16146. *
  16147. * @type {Number}
  16148. */
  16149. this.version = material.version;
  16150. /**
  16151. * The draw range of the geometry.
  16152. *
  16153. * @type {Object?}
  16154. * @default null
  16155. */
  16156. this.drawRange = null;
  16157. /**
  16158. * An array holding the buffer attributes
  16159. * of the render object. This entails attribute
  16160. * definitions on geometry and node level.
  16161. *
  16162. * @type {Array<BufferAttribute>?}
  16163. * @default null
  16164. */
  16165. this.attributes = null;
  16166. /**
  16167. * A reference to a render pipeline the render
  16168. * object is processed with.
  16169. *
  16170. * @type {RenderPipeline}
  16171. * @default null
  16172. */
  16173. this.pipeline = null;
  16174. /**
  16175. * An array holding the vertex buffers which can
  16176. * be buffer attributes but also interleaved buffers.
  16177. *
  16178. * @type {Array<BufferAttribute|InterleavedBuffer>?}
  16179. * @default null
  16180. */
  16181. this.vertexBuffers = null;
  16182. /**
  16183. * The parameters for the draw command.
  16184. *
  16185. * @type {Object?}
  16186. * @default null
  16187. */
  16188. this.drawParams = null;
  16189. /**
  16190. * If this render object is used inside a render bundle,
  16191. * this property points to the respective bundle group.
  16192. *
  16193. * @type {BundleGroup?}
  16194. * @default null
  16195. */
  16196. this.bundle = null;
  16197. /**
  16198. * The clipping context.
  16199. *
  16200. * @type {ClippingContext}
  16201. */
  16202. this.clippingContext = clippingContext;
  16203. /**
  16204. * The clipping context's cache key.
  16205. *
  16206. * @type {String}
  16207. */
  16208. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  16209. /**
  16210. * The initial node cache key.
  16211. *
  16212. * @type {Number}
  16213. */
  16214. this.initialNodesCacheKey = this.getDynamicCacheKey();
  16215. /**
  16216. * The initial cache key.
  16217. *
  16218. * @type {Number}
  16219. */
  16220. this.initialCacheKey = this.getCacheKey();
  16221. /**
  16222. * The node builder state.
  16223. *
  16224. * @type {NodeBuilderState?}
  16225. * @private
  16226. * @default null
  16227. */
  16228. this._nodeBuilderState = null;
  16229. /**
  16230. * An array of bindings.
  16231. *
  16232. * @type {Array<BindGroup>?}
  16233. * @private
  16234. * @default null
  16235. */
  16236. this._bindings = null;
  16237. /**
  16238. * Reference to the node material observer.
  16239. *
  16240. * @type {NodeMaterialObserver?}
  16241. * @private
  16242. * @default null
  16243. */
  16244. this._monitor = null;
  16245. /**
  16246. * An event listener which is defined by `RenderObjects`. It performs
  16247. * clean up tasks when `dispose()` on this render object.
  16248. *
  16249. * @method
  16250. */
  16251. this.onDispose = null;
  16252. /**
  16253. * This flag can be used for type testing.
  16254. *
  16255. * @type {Boolean}
  16256. * @readonly
  16257. * @default true
  16258. */
  16259. this.isRenderObject = true;
  16260. /**
  16261. * An event listener which is executed when `dispose()` is called on
  16262. * the render object's material.
  16263. *
  16264. * @method
  16265. */
  16266. this.onMaterialDispose = () => {
  16267. this.dispose();
  16268. };
  16269. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  16270. }
  16271. /**
  16272. * Updates the clipping context.
  16273. *
  16274. * @param {ClippingContext} context - The clipping context to set.
  16275. */
  16276. updateClipping( context ) {
  16277. this.clippingContext = context;
  16278. }
  16279. /**
  16280. * Whether the clipping requires an update or not.
  16281. *
  16282. * @type {Boolean}
  16283. * @readonly
  16284. */
  16285. get clippingNeedsUpdate() {
  16286. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  16287. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  16288. return true;
  16289. }
  16290. /**
  16291. * The number of clipping planes defined in context of hardware clipping.
  16292. *
  16293. * @type {Number}
  16294. * @readonly
  16295. */
  16296. get hardwareClippingPlanes() {
  16297. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  16298. }
  16299. /**
  16300. * Returns the node builder state of this render object.
  16301. *
  16302. * @return {NodeBuilderState} The node buider state.
  16303. */
  16304. getNodeBuilderState() {
  16305. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  16306. }
  16307. /**
  16308. * Returns the node material observer of this render object.
  16309. *
  16310. * @return {NodeMaterialObserver} The node material observer.
  16311. */
  16312. getMonitor() {
  16313. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  16314. }
  16315. /**
  16316. * Returns an array of bind groups of this render object.
  16317. *
  16318. * @return {Array<BindGroup>} The bindings.
  16319. */
  16320. getBindings() {
  16321. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  16322. }
  16323. /**
  16324. * Returns the index of the render object's geometry.
  16325. *
  16326. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  16327. */
  16328. getIndex() {
  16329. return this._geometries.getIndex( this );
  16330. }
  16331. /**
  16332. * Returns the indirect buffer attribute.
  16333. *
  16334. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  16335. */
  16336. getIndirect() {
  16337. return this._geometries.getIndirect( this );
  16338. }
  16339. /**
  16340. * Returns an array that acts as a key for identifying the render object in a chain map.
  16341. *
  16342. * @return {Array<Object>} An array with object references.
  16343. */
  16344. getChainArray() {
  16345. return [ this.object, this.material, this.context, this.lightsNode ];
  16346. }
  16347. /**
  16348. * This method is used when the geometry of a 3D object has been exchanged and the
  16349. * respective render object now requires an update.
  16350. *
  16351. * @param {BufferGeometry} geometry - The geometry to set.
  16352. */
  16353. setGeometry( geometry ) {
  16354. this.geometry = geometry;
  16355. this.attributes = null;
  16356. }
  16357. /**
  16358. * Returns the buffer attributes of the render object. The returned array holds
  16359. * attribute definitions on geometry and node level.
  16360. *
  16361. * @return {Array<BufferAttribute>} An array with buffer attributes.
  16362. */
  16363. getAttributes() {
  16364. if ( this.attributes !== null ) return this.attributes;
  16365. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  16366. const geometry = this.geometry;
  16367. const attributes = [];
  16368. const vertexBuffers = new Set();
  16369. for ( const nodeAttribute of nodeAttributes ) {
  16370. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  16371. if ( attribute === undefined ) continue;
  16372. attributes.push( attribute );
  16373. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  16374. vertexBuffers.add( bufferAttribute );
  16375. }
  16376. this.attributes = attributes;
  16377. this.vertexBuffers = Array.from( vertexBuffers.values() );
  16378. return attributes;
  16379. }
  16380. /**
  16381. * Returns the vertex buffers of the render object.
  16382. *
  16383. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  16384. */
  16385. getVertexBuffers() {
  16386. if ( this.vertexBuffers === null ) this.getAttributes();
  16387. return this.vertexBuffers;
  16388. }
  16389. /**
  16390. * Returns the draw parameters for the render object.
  16391. *
  16392. * @return {{vertexCount: Number, firstVertex: Number, instanceCount: Number, firstInstance: Number}} The draw parameters.
  16393. */
  16394. getDrawParameters() {
  16395. const { object, material, geometry, group, drawRange } = this;
  16396. const drawParams = this.drawParams || ( this.drawParams = {
  16397. vertexCount: 0,
  16398. firstVertex: 0,
  16399. instanceCount: 0,
  16400. firstInstance: 0
  16401. } );
  16402. const index = this.getIndex();
  16403. const hasIndex = ( index !== null );
  16404. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  16405. if ( instanceCount === 0 ) return null;
  16406. drawParams.instanceCount = instanceCount;
  16407. if ( object.isBatchedMesh === true ) return drawParams;
  16408. let rangeFactor = 1;
  16409. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  16410. rangeFactor = 2;
  16411. }
  16412. let firstVertex = drawRange.start * rangeFactor;
  16413. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  16414. if ( group !== null ) {
  16415. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  16416. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  16417. }
  16418. const position = geometry.attributes.position;
  16419. let itemCount = Infinity;
  16420. if ( hasIndex ) {
  16421. itemCount = index.count;
  16422. } else if ( position !== undefined && position !== null ) {
  16423. itemCount = position.count;
  16424. }
  16425. firstVertex = Math.max( firstVertex, 0 );
  16426. lastVertex = Math.min( lastVertex, itemCount );
  16427. const count = lastVertex - firstVertex;
  16428. if ( count < 0 || count === Infinity ) return null;
  16429. drawParams.vertexCount = count;
  16430. drawParams.firstVertex = firstVertex;
  16431. return drawParams;
  16432. }
  16433. /**
  16434. * Returns the render object's geometry cache key.
  16435. *
  16436. * The geometry cache key is part of the material cache key.
  16437. *
  16438. * @return {String} The geometry cache key.
  16439. */
  16440. getGeometryCacheKey() {
  16441. const { geometry } = this;
  16442. let cacheKey = '';
  16443. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  16444. const attribute = geometry.attributes[ name ];
  16445. cacheKey += name + ',';
  16446. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  16447. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  16448. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  16449. if ( attribute.normalized ) cacheKey += 'n,';
  16450. }
  16451. if ( geometry.index ) {
  16452. cacheKey += 'index,';
  16453. }
  16454. return cacheKey;
  16455. }
  16456. /**
  16457. * Returns the render object's material cache key.
  16458. *
  16459. * The material cache key is part of the render object cache key.
  16460. *
  16461. * @return {String} The material cache key.
  16462. */
  16463. getMaterialCacheKey() {
  16464. const { object, material } = this;
  16465. let cacheKey = material.customProgramCacheKey();
  16466. for ( const property of getKeys( material ) ) {
  16467. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  16468. const value = material[ property ];
  16469. let valueKey;
  16470. if ( value !== null ) {
  16471. // some material values require a formatting
  16472. const type = typeof value;
  16473. if ( type === 'number' ) {
  16474. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  16475. } else if ( type === 'object' ) {
  16476. valueKey = '{';
  16477. if ( value.isTexture ) {
  16478. valueKey += value.mapping;
  16479. }
  16480. valueKey += '}';
  16481. } else {
  16482. valueKey = String( value );
  16483. }
  16484. } else {
  16485. valueKey = String( value );
  16486. }
  16487. cacheKey += /*property + ':' +*/ valueKey + ',';
  16488. }
  16489. cacheKey += this.clippingContextCacheKey + ',';
  16490. if ( object.geometry ) {
  16491. cacheKey += this.getGeometryCacheKey();
  16492. }
  16493. if ( object.skeleton ) {
  16494. cacheKey += object.skeleton.bones.length + ',';
  16495. }
  16496. if ( object.morphTargetInfluences ) {
  16497. cacheKey += object.morphTargetInfluences.length + ',';
  16498. }
  16499. if ( object.isBatchedMesh ) {
  16500. cacheKey += object._matricesTexture.uuid + ',';
  16501. if ( object._colorsTexture !== null ) {
  16502. cacheKey += object._colorsTexture.uuid + ',';
  16503. }
  16504. }
  16505. if ( object.count > 1 ) {
  16506. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  16507. cacheKey += object.uuid + ',';
  16508. }
  16509. cacheKey += object.receiveShadow + ',';
  16510. return hashString( cacheKey );
  16511. }
  16512. /**
  16513. * Whether the geometry requires an update or not.
  16514. *
  16515. * @type {Boolean}
  16516. * @readonly
  16517. */
  16518. get needsGeometryUpdate() {
  16519. return this.geometry.id !== this.object.geometry.id;
  16520. }
  16521. /**
  16522. * Whether the render object requires an update or not.
  16523. *
  16524. * Note: There are two distinct places where render objects are checked for an update.
  16525. *
  16526. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  16527. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  16528. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  16529. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  16530. * a need for a refresh due to material, geometry or object related value changes.
  16531. *
  16532. * TODO: Investigate if it's possible to merge boths steps so there is only a single place
  16533. * that performs the 'needsUpdate' check.
  16534. *
  16535. * @type {Boolean}
  16536. * @readonly
  16537. */
  16538. get needsUpdate() {
  16539. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  16540. }
  16541. /**
  16542. * Returns the dynamic cache key which represents a key that is computed per draw command.
  16543. *
  16544. * @return {String} The cache key.
  16545. */
  16546. getDynamicCacheKey() {
  16547. // Environment Nodes Cache Key
  16548. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  16549. if ( this.object.receiveShadow ) {
  16550. cacheKey += 1;
  16551. }
  16552. return cacheKey;
  16553. }
  16554. /**
  16555. * Returns the render object's cache key.
  16556. *
  16557. * @return {String} The cache key.
  16558. */
  16559. getCacheKey() {
  16560. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  16561. }
  16562. /**
  16563. * Frees internal resources.
  16564. */
  16565. dispose() {
  16566. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  16567. this.onDispose();
  16568. }
  16569. }
  16570. const _chainArray = [];
  16571. /**
  16572. * This module manages the render objects of the renderer.
  16573. *
  16574. * @private
  16575. */
  16576. class RenderObjects {
  16577. /**
  16578. * Constructs a new render object management component.
  16579. *
  16580. * @param {Renderer} renderer - The renderer.
  16581. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16582. * @param {Geometries} geometries - Renderer component for managing geometries.
  16583. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  16584. * @param {Bindings} bindings - Renderer component for managing bindings.
  16585. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16586. */
  16587. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  16588. /**
  16589. * The renderer.
  16590. *
  16591. * @type {Renderer}
  16592. */
  16593. this.renderer = renderer;
  16594. /**
  16595. * Renderer component for managing nodes related logic.
  16596. *
  16597. * @type {Nodes}
  16598. */
  16599. this.nodes = nodes;
  16600. /**
  16601. * Renderer component for managing geometries.
  16602. *
  16603. * @type {Geometries}
  16604. */
  16605. this.geometries = geometries;
  16606. /**
  16607. * Renderer component for managing pipelines.
  16608. *
  16609. * @type {Pipelines}
  16610. */
  16611. this.pipelines = pipelines;
  16612. /**
  16613. * Renderer component for managing bindings.
  16614. *
  16615. * @type {Bindings}
  16616. */
  16617. this.bindings = bindings;
  16618. /**
  16619. * Renderer component for managing metrics and monitoring data.
  16620. *
  16621. * @type {Info}
  16622. */
  16623. this.info = info;
  16624. /**
  16625. * A dictionary that manages render contexts in chain maps
  16626. * for each pass ID.
  16627. *
  16628. * @type {Object<String,ChainMap>}
  16629. */
  16630. this.chainMaps = {};
  16631. }
  16632. /**
  16633. * Returns a render object for the given object and state data.
  16634. *
  16635. * @param {Object3D} object - The 3D object.
  16636. * @param {Material} material - The 3D object's material.
  16637. * @param {Scene} scene - The scene the 3D object belongs to.
  16638. * @param {Camera} camera - The camera the 3D object should be rendered with.
  16639. * @param {LightsNode} lightsNode - The lights node.
  16640. * @param {RenderContext} renderContext - The render context.
  16641. * @param {ClippingContext} clippingContext - The clipping context.
  16642. * @param {String?} passId - An optional ID for identifying the pass.
  16643. * @return {RenderObject} The render object.
  16644. */
  16645. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16646. const chainMap = this.getChainMap( passId );
  16647. // reuse chainArray
  16648. _chainArray[ 0 ] = object;
  16649. _chainArray[ 1 ] = material;
  16650. _chainArray[ 2 ] = renderContext;
  16651. _chainArray[ 3 ] = lightsNode;
  16652. let renderObject = chainMap.get( _chainArray );
  16653. if ( renderObject === undefined ) {
  16654. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16655. chainMap.set( _chainArray, renderObject );
  16656. } else {
  16657. renderObject.updateClipping( clippingContext );
  16658. if ( renderObject.needsGeometryUpdate ) {
  16659. renderObject.setGeometry( object.geometry );
  16660. }
  16661. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  16662. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  16663. renderObject.dispose();
  16664. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16665. } else {
  16666. renderObject.version = material.version;
  16667. }
  16668. }
  16669. }
  16670. return renderObject;
  16671. }
  16672. /**
  16673. * Returns a chain map for the given pass ID.
  16674. *
  16675. * @param {String} [passId='default'] - The pass ID.
  16676. * @return {ChainMap} The chain map.
  16677. */
  16678. getChainMap( passId = 'default' ) {
  16679. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  16680. }
  16681. /**
  16682. * Frees internal resources.
  16683. */
  16684. dispose() {
  16685. this.chainMaps = {};
  16686. }
  16687. /**
  16688. * Factory method for creating render objects with the given list of parameters.
  16689. *
  16690. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16691. * @param {Geometries} geometries - Renderer component for managing geometries.
  16692. * @param {Renderer} renderer - The renderer.
  16693. * @param {Object3D} object - The 3D object.
  16694. * @param {Material} material - The object's material.
  16695. * @param {Scene} scene - The scene the 3D object belongs to.
  16696. * @param {Camera} camera - The camera the object should be rendered with.
  16697. * @param {LightsNode} lightsNode - The lights node.
  16698. * @param {RenderContext} renderContext - The render context.
  16699. * @param {ClippingContext} clippingContext - The clipping context.
  16700. * @param {String?} passId - An optional ID for identifying the pass.
  16701. * @return {RenderObject} The render object.
  16702. */
  16703. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16704. const chainMap = this.getChainMap( passId );
  16705. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  16706. renderObject.onDispose = () => {
  16707. this.pipelines.delete( renderObject );
  16708. this.bindings.delete( renderObject );
  16709. this.nodes.delete( renderObject );
  16710. chainMap.delete( renderObject.getChainArray() );
  16711. };
  16712. return renderObject;
  16713. }
  16714. }
  16715. /**
  16716. * Data structure for the renderer. It is intended to manage
  16717. * data of objects in dictionaries.
  16718. *
  16719. * @private
  16720. */
  16721. class DataMap {
  16722. /**
  16723. * Constructs a new data map.
  16724. */
  16725. constructor() {
  16726. /**
  16727. * `DataMap` internally uses a weak map
  16728. * to manage its data.
  16729. *
  16730. * @type {WeakMap}
  16731. */
  16732. this.data = new WeakMap();
  16733. }
  16734. /**
  16735. * Returns the dictionary for the given object.
  16736. *
  16737. * @param {Object} object - The object.
  16738. * @return {Object} The dictionary.
  16739. */
  16740. get( object ) {
  16741. let map = this.data.get( object );
  16742. if ( map === undefined ) {
  16743. map = {};
  16744. this.data.set( object, map );
  16745. }
  16746. return map;
  16747. }
  16748. /**
  16749. * Deletes the dictionary for the given object.
  16750. *
  16751. * @param {Object} object - The object.
  16752. * @return {Object?} The deleted dictionary.
  16753. */
  16754. delete( object ) {
  16755. let map = null;
  16756. if ( this.data.has( object ) ) {
  16757. map = this.data.get( object );
  16758. this.data.delete( object );
  16759. }
  16760. return map;
  16761. }
  16762. /**
  16763. * Returns `true` if the given object has a dictionary defined.
  16764. *
  16765. * @param {Object} object - The object to test.
  16766. * @return {Boolean} Whether a dictionary is defined or not.
  16767. */
  16768. has( object ) {
  16769. return this.data.has( object );
  16770. }
  16771. /**
  16772. * Frees internal resources.
  16773. */
  16774. dispose() {
  16775. this.data = new WeakMap();
  16776. }
  16777. }
  16778. const AttributeType = {
  16779. VERTEX: 1,
  16780. INDEX: 2,
  16781. STORAGE: 3,
  16782. INDIRECT: 4
  16783. };
  16784. // size of a chunk in bytes (STD140 layout)
  16785. const GPU_CHUNK_BYTES = 16;
  16786. // @TODO: Move to src/constants.js
  16787. const BlendColorFactor = 211;
  16788. const OneMinusBlendColorFactor = 212;
  16789. /**
  16790. * This renderer module manages geometry attributes.
  16791. *
  16792. * @private
  16793. * @augments DataMap
  16794. */
  16795. class Attributes extends DataMap {
  16796. /**
  16797. * Constructs a new attribute management component.
  16798. *
  16799. * @param {Backend} backend - The renderer's backend.
  16800. */
  16801. constructor( backend ) {
  16802. super();
  16803. /**
  16804. * The renderer's backend.
  16805. *
  16806. * @type {Backend}
  16807. */
  16808. this.backend = backend;
  16809. }
  16810. /**
  16811. * Deletes the data for the given attribute.
  16812. *
  16813. * @param {BufferAttribute} attribute - The attribute.
  16814. * @return {Object} The deleted attribute data.
  16815. */
  16816. delete( attribute ) {
  16817. const attributeData = super.delete( attribute );
  16818. if ( attributeData !== undefined ) {
  16819. this.backend.destroyAttribute( attribute );
  16820. }
  16821. return attributeData;
  16822. }
  16823. /**
  16824. * Updates the given attribute. This method creates attribute buffers
  16825. * for new attributes and updates data for existing ones.
  16826. *
  16827. * @param {BufferAttribute} attribute - The attribute to update.
  16828. * @param {Number} type - The attribute type.
  16829. */
  16830. update( attribute, type ) {
  16831. const data = this.get( attribute );
  16832. if ( data.version === undefined ) {
  16833. if ( type === AttributeType.VERTEX ) {
  16834. this.backend.createAttribute( attribute );
  16835. } else if ( type === AttributeType.INDEX ) {
  16836. this.backend.createIndexAttribute( attribute );
  16837. } else if ( type === AttributeType.STORAGE ) {
  16838. this.backend.createStorageAttribute( attribute );
  16839. } else if ( type === AttributeType.INDIRECT ) {
  16840. this.backend.createIndirectStorageAttribute( attribute );
  16841. }
  16842. data.version = this._getBufferAttribute( attribute ).version;
  16843. } else {
  16844. const bufferAttribute = this._getBufferAttribute( attribute );
  16845. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  16846. this.backend.updateAttribute( attribute );
  16847. data.version = bufferAttribute.version;
  16848. }
  16849. }
  16850. }
  16851. /**
  16852. * Utility method for handling interleaved buffer attributes correctly.
  16853. * To process them, their `InterleavedBuffer` is returned.
  16854. *
  16855. * @param {BufferAttribute} attribute - The attribute.
  16856. * @return {BufferAttribute|InterleavedBuffer}
  16857. */
  16858. _getBufferAttribute( attribute ) {
  16859. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  16860. return attribute;
  16861. }
  16862. }
  16863. /**
  16864. * Returns `true` if the given array has values that require an Uint32 array type.
  16865. *
  16866. * @private
  16867. * @function
  16868. * @param {Array<Number>} array - The array to test.
  16869. * @return {Booolean} Whether the given array has values that require an Uint32 array type or not.
  16870. */
  16871. function arrayNeedsUint32( array ) {
  16872. // assumes larger values usually on last
  16873. for ( let i = array.length - 1; i >= 0; -- i ) {
  16874. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  16875. }
  16876. return false;
  16877. }
  16878. /**
  16879. * Returns the wireframe version for the given geometry.
  16880. *
  16881. * @private
  16882. * @function
  16883. * @param {BufferGeometry} geometry - The geometry.
  16884. * @return {Number} The versio.
  16885. */
  16886. function getWireframeVersion( geometry ) {
  16887. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  16888. }
  16889. /**
  16890. * Returns a wireframe index attribute for the given geometry.
  16891. *
  16892. * @private
  16893. * @function
  16894. * @param {BufferGeometry} geometry - The geometry.
  16895. * @return {BufferAttribute} The wireframe index attribute.
  16896. */
  16897. function getWireframeIndex( geometry ) {
  16898. const indices = [];
  16899. const geometryIndex = geometry.index;
  16900. const geometryPosition = geometry.attributes.position;
  16901. if ( geometryIndex !== null ) {
  16902. const array = geometryIndex.array;
  16903. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  16904. const a = array[ i + 0 ];
  16905. const b = array[ i + 1 ];
  16906. const c = array[ i + 2 ];
  16907. indices.push( a, b, b, c, c, a );
  16908. }
  16909. } else {
  16910. const array = geometryPosition.array;
  16911. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  16912. const a = i + 0;
  16913. const b = i + 1;
  16914. const c = i + 2;
  16915. indices.push( a, b, b, c, c, a );
  16916. }
  16917. }
  16918. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  16919. attribute.version = getWireframeVersion( geometry );
  16920. return attribute;
  16921. }
  16922. /**
  16923. * This renderer module manages geometries.
  16924. *
  16925. * @private
  16926. * @augments DataMap
  16927. */
  16928. class Geometries extends DataMap {
  16929. /**
  16930. * Constructs a new geometry management component.
  16931. *
  16932. * @param {Attributes} attributes - Renderer component for managing attributes.
  16933. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16934. */
  16935. constructor( attributes, info ) {
  16936. super();
  16937. /**
  16938. * Renderer component for managing attributes.
  16939. *
  16940. * @type {Attributes}
  16941. */
  16942. this.attributes = attributes;
  16943. /**
  16944. * Renderer component for managing metrics and monitoring data.
  16945. *
  16946. * @type {Info}
  16947. */
  16948. this.info = info;
  16949. /**
  16950. * Weak Map for managing attributes for wireframe rendering.
  16951. *
  16952. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  16953. */
  16954. this.wireframes = new WeakMap();
  16955. /**
  16956. * This Weak Map is used to make sure buffer attributes are
  16957. * updated only once per render call.
  16958. *
  16959. * @type {WeakMap<BufferAttribute,Number>}
  16960. */
  16961. this.attributeCall = new WeakMap();
  16962. }
  16963. /**
  16964. * Returns `true` if the given render object has an initialized geometry.
  16965. *
  16966. * @param {RenderObject} renderObject - The render object.
  16967. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  16968. */
  16969. has( renderObject ) {
  16970. const geometry = renderObject.geometry;
  16971. return super.has( geometry ) && this.get( geometry ).initialized === true;
  16972. }
  16973. /**
  16974. * Prepares the geometry of the given render object for rendering.
  16975. *
  16976. * @param {RenderObject} renderObject - The render object.
  16977. */
  16978. updateForRender( renderObject ) {
  16979. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  16980. this.updateAttributes( renderObject );
  16981. }
  16982. /**
  16983. * Initializes the geometry of the given render object.
  16984. *
  16985. * @param {RenderObject} renderObject - The render object.
  16986. */
  16987. initGeometry( renderObject ) {
  16988. const geometry = renderObject.geometry;
  16989. const geometryData = this.get( geometry );
  16990. geometryData.initialized = true;
  16991. this.info.memory.geometries ++;
  16992. const onDispose = () => {
  16993. this.info.memory.geometries --;
  16994. const index = geometry.index;
  16995. const geometryAttributes = renderObject.getAttributes();
  16996. if ( index !== null ) {
  16997. this.attributes.delete( index );
  16998. }
  16999. for ( const geometryAttribute of geometryAttributes ) {
  17000. this.attributes.delete( geometryAttribute );
  17001. }
  17002. const wireframeAttribute = this.wireframes.get( geometry );
  17003. if ( wireframeAttribute !== undefined ) {
  17004. this.attributes.delete( wireframeAttribute );
  17005. }
  17006. geometry.removeEventListener( 'dispose', onDispose );
  17007. };
  17008. geometry.addEventListener( 'dispose', onDispose );
  17009. }
  17010. /**
  17011. * Updates the geometry attributes of the given render object.
  17012. *
  17013. * @param {RenderObject} renderObject - The render object.
  17014. */
  17015. updateAttributes( renderObject ) {
  17016. // attributes
  17017. const attributes = renderObject.getAttributes();
  17018. for ( const attribute of attributes ) {
  17019. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  17020. this.updateAttribute( attribute, AttributeType.STORAGE );
  17021. } else {
  17022. this.updateAttribute( attribute, AttributeType.VERTEX );
  17023. }
  17024. }
  17025. // indexes
  17026. const index = this.getIndex( renderObject );
  17027. if ( index !== null ) {
  17028. this.updateAttribute( index, AttributeType.INDEX );
  17029. }
  17030. // indirect
  17031. const indirect = renderObject.geometry.indirect;
  17032. if ( indirect !== null ) {
  17033. this.updateAttribute( indirect, AttributeType.INDIRECT );
  17034. }
  17035. }
  17036. /**
  17037. * Updates the given attribute.
  17038. *
  17039. * @param {BufferAttribute} attribute - The attribute to update.
  17040. * @param {Number} type - The attribute type.
  17041. */
  17042. updateAttribute( attribute, type ) {
  17043. const callId = this.info.render.calls;
  17044. if ( ! attribute.isInterleavedBufferAttribute ) {
  17045. if ( this.attributeCall.get( attribute ) !== callId ) {
  17046. this.attributes.update( attribute, type );
  17047. this.attributeCall.set( attribute, callId );
  17048. }
  17049. } else {
  17050. if ( this.attributeCall.get( attribute ) === undefined ) {
  17051. this.attributes.update( attribute, type );
  17052. this.attributeCall.set( attribute, callId );
  17053. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  17054. this.attributes.update( attribute, type );
  17055. this.attributeCall.set( attribute.data, callId );
  17056. this.attributeCall.set( attribute, callId );
  17057. }
  17058. }
  17059. }
  17060. /**
  17061. * Returns the indirect buffer attribute of the given render object.
  17062. *
  17063. * @param {RenderObject} renderObject - The render object.
  17064. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  17065. */
  17066. getIndirect( renderObject ) {
  17067. return renderObject.geometry.indirect;
  17068. }
  17069. /**
  17070. * Returns the index of the given render object's geometry. This is implemented
  17071. * in a method to return a wireframe index if necessary.
  17072. *
  17073. * @param {RenderObject} renderObject - The render object.
  17074. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  17075. */
  17076. getIndex( renderObject ) {
  17077. const { geometry, material } = renderObject;
  17078. let index = geometry.index;
  17079. if ( material.wireframe === true ) {
  17080. const wireframes = this.wireframes;
  17081. let wireframeAttribute = wireframes.get( geometry );
  17082. if ( wireframeAttribute === undefined ) {
  17083. wireframeAttribute = getWireframeIndex( geometry );
  17084. wireframes.set( geometry, wireframeAttribute );
  17085. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  17086. this.attributes.delete( wireframeAttribute );
  17087. wireframeAttribute = getWireframeIndex( geometry );
  17088. wireframes.set( geometry, wireframeAttribute );
  17089. }
  17090. index = wireframeAttribute;
  17091. }
  17092. return index;
  17093. }
  17094. }
  17095. /**
  17096. * This renderer module provides a series of statistical information
  17097. * about the GPU memory and the rendering process. Useful for debugging
  17098. * and monitoring.
  17099. */
  17100. class Info {
  17101. /**
  17102. * Constructs a new info component.
  17103. */
  17104. constructor() {
  17105. /**
  17106. * Whether frame related metrics should automatically
  17107. * be resetted or not. This property should be set to `false`
  17108. * by apps which manage their own animation loop. They must
  17109. * then call `renderer.info.reset()` once per frame manually.
  17110. *
  17111. * @type {Boolean}
  17112. * @default true
  17113. */
  17114. this.autoReset = true;
  17115. /**
  17116. * The current frame ID. This ID is managed
  17117. * by `NodeFrame`.
  17118. *
  17119. * @type {Number}
  17120. * @readonly
  17121. * @default 0
  17122. */
  17123. this.frame = 0;
  17124. /**
  17125. * The number of render calls since the
  17126. * app has been started.
  17127. *
  17128. * @type {Number}
  17129. * @readonly
  17130. * @default 0
  17131. */
  17132. this.calls = 0;
  17133. /**
  17134. * Render related metrics.
  17135. *
  17136. * @type {Object}
  17137. * @readonly
  17138. * @property {Number} calls - The number of render calls since the app has been started.
  17139. * @property {Number} frameCalls - The number of render calls of the current frame.
  17140. * @property {Number} drawCalls - The number of draw calls of the current frame.
  17141. * @property {Number} triangles - The number of rendered triangle primitives of the current frame.
  17142. * @property {Number} points - The number of rendered point primitives of the current frame.
  17143. * @property {Number} lines - The number of rendered line primitives of the current frame.
  17144. * @property {Number} previousFrameCalls - The number of render calls of the previous frame.
  17145. * @property {Number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  17146. * @property {Number} timestampCalls - The number of render calls using `renderer.renderAsync()`.
  17147. */
  17148. this.render = {
  17149. calls: 0,
  17150. frameCalls: 0,
  17151. drawCalls: 0,
  17152. triangles: 0,
  17153. points: 0,
  17154. lines: 0,
  17155. timestamp: 0,
  17156. previousFrameCalls: 0,
  17157. timestampCalls: 0
  17158. };
  17159. /**
  17160. * Compute related metrics.
  17161. *
  17162. * @type {Object}
  17163. * @readonly
  17164. * @property {Number} calls - The number of compute calls since the app has been started.
  17165. * @property {Number} frameCalls - The number of compute calls of the current frame.
  17166. * @property {Number} previousFrameCalls - The number of compute calls of the previous frame.
  17167. * @property {Number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  17168. * @property {Number} timestampCalls - The number of render calls using `renderer.computeAsync()`.
  17169. */
  17170. this.compute = {
  17171. calls: 0,
  17172. frameCalls: 0,
  17173. timestamp: 0,
  17174. previousFrameCalls: 0,
  17175. timestampCalls: 0
  17176. };
  17177. /**
  17178. * Memory related metrics.
  17179. *
  17180. * @type {Object}
  17181. * @readonly
  17182. * @property {Number} geometries - The number of active geometries.
  17183. * @property {Number} frameCalls - The number of active textures.
  17184. */
  17185. this.memory = {
  17186. geometries: 0,
  17187. textures: 0
  17188. };
  17189. }
  17190. /**
  17191. * This method should be executed per draw call and updates the corresponding metrics.
  17192. *
  17193. * @param {Object3D} object - The 3D object that is going to be rendered.
  17194. * @param {Number} count - The vertex or index count.
  17195. * @param {Number} instanceCount - The instance count.
  17196. */
  17197. update( object, count, instanceCount ) {
  17198. this.render.drawCalls ++;
  17199. if ( object.isMesh || object.isSprite ) {
  17200. this.render.triangles += instanceCount * ( count / 3 );
  17201. } else if ( object.isPoints ) {
  17202. this.render.points += instanceCount * count;
  17203. } else if ( object.isLineSegments ) {
  17204. this.render.lines += instanceCount * ( count / 2 );
  17205. } else if ( object.isLine ) {
  17206. this.render.lines += instanceCount * ( count - 1 );
  17207. } else {
  17208. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  17209. }
  17210. }
  17211. /**
  17212. * Used by async render methods to updated timestamp metrics.
  17213. *
  17214. * @param {('render'|'compute')} type - The type of render call.
  17215. * @param {Number} time - The duration of the compute/render call in milliseconds.
  17216. */
  17217. updateTimestamp( type, time ) {
  17218. if ( this[ type ].timestampCalls === 0 ) {
  17219. this[ type ].timestamp = 0;
  17220. }
  17221. this[ type ].timestamp += time;
  17222. this[ type ].timestampCalls ++;
  17223. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  17224. this[ type ].timestampCalls = 0;
  17225. }
  17226. }
  17227. /**
  17228. * Resets frame related metrics.
  17229. */
  17230. reset() {
  17231. const previousRenderFrameCalls = this.render.frameCalls;
  17232. this.render.previousFrameCalls = previousRenderFrameCalls;
  17233. const previousComputeFrameCalls = this.compute.frameCalls;
  17234. this.compute.previousFrameCalls = previousComputeFrameCalls;
  17235. this.render.drawCalls = 0;
  17236. this.render.frameCalls = 0;
  17237. this.compute.frameCalls = 0;
  17238. this.render.triangles = 0;
  17239. this.render.points = 0;
  17240. this.render.lines = 0;
  17241. }
  17242. /**
  17243. * Performs a complete reset of the object.
  17244. */
  17245. dispose() {
  17246. this.reset();
  17247. this.calls = 0;
  17248. this.render.calls = 0;
  17249. this.compute.calls = 0;
  17250. this.render.timestamp = 0;
  17251. this.compute.timestamp = 0;
  17252. this.memory.geometries = 0;
  17253. this.memory.textures = 0;
  17254. }
  17255. }
  17256. /**
  17257. * Abstract class for representing pipelines.
  17258. *
  17259. * @private
  17260. * @abstract
  17261. */
  17262. class Pipeline {
  17263. /**
  17264. * Constructs a new pipeline.
  17265. *
  17266. * @param {String} cacheKey - The pipeline's cache key.
  17267. */
  17268. constructor( cacheKey ) {
  17269. /**
  17270. * The pipeline's cache key.
  17271. *
  17272. * @type {String}
  17273. */
  17274. this.cacheKey = cacheKey;
  17275. /**
  17276. * How often the pipeline is currently in use.
  17277. *
  17278. * @type {Number}
  17279. * @default 0
  17280. */
  17281. this.usedTimes = 0;
  17282. }
  17283. }
  17284. /**
  17285. * Class for representing render pipelines.
  17286. *
  17287. * @private
  17288. * @augments Pipeline
  17289. */
  17290. class RenderPipeline extends Pipeline {
  17291. /**
  17292. * Constructs a new render pipeline.
  17293. *
  17294. * @param {String} cacheKey - The pipeline's cache key.
  17295. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  17296. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  17297. */
  17298. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  17299. super( cacheKey );
  17300. /**
  17301. * The pipeline's vertex shader.
  17302. *
  17303. * @type {ProgrammableStage}
  17304. */
  17305. this.vertexProgram = vertexProgram;
  17306. /**
  17307. * The pipeline's fragment shader.
  17308. *
  17309. * @type {ProgrammableStage}
  17310. */
  17311. this.fragmentProgram = fragmentProgram;
  17312. }
  17313. }
  17314. /**
  17315. * Class for representing compute pipelines.
  17316. *
  17317. * @private
  17318. * @augments Pipeline
  17319. */
  17320. class ComputePipeline extends Pipeline {
  17321. /**
  17322. * Constructs a new render pipeline.
  17323. *
  17324. * @param {String} cacheKey - The pipeline's cache key.
  17325. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  17326. */
  17327. constructor( cacheKey, computeProgram ) {
  17328. super( cacheKey );
  17329. /**
  17330. * The pipeline's compute shader.
  17331. *
  17332. * @type {ProgrammableStage}
  17333. */
  17334. this.computeProgram = computeProgram;
  17335. /**
  17336. * This flag can be used for type testing.
  17337. *
  17338. * @type {Boolean}
  17339. * @readonly
  17340. * @default true
  17341. */
  17342. this.isComputePipeline = true;
  17343. }
  17344. }
  17345. let _id$8 = 0;
  17346. /**
  17347. * Class for representing programmable stages which are vertex,
  17348. * fragment or compute shaders. Unlike fixed-function states (like blending),
  17349. * they represent the programmable part of a pipeline.
  17350. *
  17351. * @private
  17352. */
  17353. class ProgrammableStage {
  17354. /**
  17355. * Constructs a new programmable stage.
  17356. *
  17357. * @param {String} code - The shader code.
  17358. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  17359. * @param {String} name - The name of the shader.
  17360. * @param {Array<Object>?} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17361. * @param {Array<Object>?} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17362. */
  17363. constructor( code, stage, name, transforms = null, attributes = null ) {
  17364. /**
  17365. * The id of the programmable stage.
  17366. *
  17367. * @type {Number}
  17368. */
  17369. this.id = _id$8 ++;
  17370. /**
  17371. * The shader code.
  17372. *
  17373. * @type {String}
  17374. */
  17375. this.code = code;
  17376. /**
  17377. * The type of stage.
  17378. *
  17379. * @type {String}
  17380. */
  17381. this.stage = stage;
  17382. /**
  17383. * The name of the stage.
  17384. * This is used for debugging purposes.
  17385. *
  17386. * @type {String}
  17387. */
  17388. this.name = name;
  17389. /**
  17390. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17391. *
  17392. * @type {Array<Object>?}
  17393. */
  17394. this.transforms = transforms;
  17395. /**
  17396. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17397. *
  17398. * @type {Array<Object>?}
  17399. */
  17400. this.attributes = attributes;
  17401. /**
  17402. * How often the programmable stage is currently in use.
  17403. *
  17404. * @type {Number}
  17405. * @default 0
  17406. */
  17407. this.usedTimes = 0;
  17408. }
  17409. }
  17410. /**
  17411. * This renderer module manages the pipelines of the renderer.
  17412. *
  17413. * @private
  17414. * @augments DataMap
  17415. */
  17416. class Pipelines extends DataMap {
  17417. /**
  17418. * Constructs a new pipeline management component.
  17419. *
  17420. * @param {Backend} backend - The renderer's backend.
  17421. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17422. */
  17423. constructor( backend, nodes ) {
  17424. super();
  17425. /**
  17426. * The renderer's backend.
  17427. *
  17428. * @type {Backend}
  17429. */
  17430. this.backend = backend;
  17431. /**
  17432. * Renderer component for managing nodes related logic.
  17433. *
  17434. * @type {Nodes}
  17435. */
  17436. this.nodes = nodes;
  17437. /**
  17438. * A references to the bindings management component.
  17439. * This reference will be set inside the `Bindings`
  17440. * constructor.
  17441. *
  17442. * @type {Bindings?}
  17443. * @default null
  17444. */
  17445. this.bindings = null;
  17446. /**
  17447. * Internal cache for maintaining pipelines.
  17448. * The key of the map is a cache key, the value the pipeline.
  17449. *
  17450. * @type {Map<String,Pipeline>}
  17451. */
  17452. this.caches = new Map();
  17453. /**
  17454. * This dictionary maintains for each shader stage type (vertex,
  17455. * fragment and compute) the progammable stage objects which
  17456. * represent the actual shader code.
  17457. *
  17458. * @type {Object<String,Map>}
  17459. */
  17460. this.programs = {
  17461. vertex: new Map(),
  17462. fragment: new Map(),
  17463. compute: new Map()
  17464. };
  17465. }
  17466. /**
  17467. * Returns a compute pipeline for the given compute node.
  17468. *
  17469. * @param {Node} computeNode - The compute node.
  17470. * @param {Array<BindGroup>} bindings - The bindings.
  17471. * @return {ComputePipeline} The compute pipeline.
  17472. */
  17473. getForCompute( computeNode, bindings ) {
  17474. const { backend } = this;
  17475. const data = this.get( computeNode );
  17476. if ( this._needsComputeUpdate( computeNode ) ) {
  17477. const previousPipeline = data.pipeline;
  17478. if ( previousPipeline ) {
  17479. previousPipeline.usedTimes --;
  17480. previousPipeline.computeProgram.usedTimes --;
  17481. }
  17482. // get shader
  17483. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  17484. // programmable stage
  17485. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  17486. if ( stageCompute === undefined ) {
  17487. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  17488. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  17489. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  17490. backend.createProgram( stageCompute );
  17491. }
  17492. // determine compute pipeline
  17493. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  17494. let pipeline = this.caches.get( cacheKey );
  17495. if ( pipeline === undefined ) {
  17496. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17497. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  17498. }
  17499. // keep track of all used times
  17500. pipeline.usedTimes ++;
  17501. stageCompute.usedTimes ++;
  17502. //
  17503. data.version = computeNode.version;
  17504. data.pipeline = pipeline;
  17505. }
  17506. return data.pipeline;
  17507. }
  17508. /**
  17509. * Returns a render pipeline for the given render object.
  17510. *
  17511. * @param {RenderObject} renderObject - The render object.
  17512. * @param {Array<Promise>?} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17513. * @return {RenderPipeline} The render pipeline.
  17514. */
  17515. getForRender( renderObject, promises = null ) {
  17516. const { backend } = this;
  17517. const data = this.get( renderObject );
  17518. if ( this._needsRenderUpdate( renderObject ) ) {
  17519. const previousPipeline = data.pipeline;
  17520. if ( previousPipeline ) {
  17521. previousPipeline.usedTimes --;
  17522. previousPipeline.vertexProgram.usedTimes --;
  17523. previousPipeline.fragmentProgram.usedTimes --;
  17524. }
  17525. // get shader
  17526. const nodeBuilderState = renderObject.getNodeBuilderState();
  17527. const name = renderObject.material ? renderObject.material.name : '';
  17528. // programmable stages
  17529. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  17530. if ( stageVertex === undefined ) {
  17531. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  17532. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  17533. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  17534. backend.createProgram( stageVertex );
  17535. }
  17536. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  17537. if ( stageFragment === undefined ) {
  17538. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  17539. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  17540. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  17541. backend.createProgram( stageFragment );
  17542. }
  17543. // determine render pipeline
  17544. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17545. let pipeline = this.caches.get( cacheKey );
  17546. if ( pipeline === undefined ) {
  17547. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17548. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  17549. } else {
  17550. renderObject.pipeline = pipeline;
  17551. }
  17552. // keep track of all used times
  17553. pipeline.usedTimes ++;
  17554. stageVertex.usedTimes ++;
  17555. stageFragment.usedTimes ++;
  17556. //
  17557. data.pipeline = pipeline;
  17558. }
  17559. return data.pipeline;
  17560. }
  17561. /**
  17562. * Deletes the pipeline for the given render object.
  17563. *
  17564. * @param {RenderObject} object - The render object.
  17565. * @return {Object?} The deleted dictionary.
  17566. */
  17567. delete( object ) {
  17568. const pipeline = this.get( object ).pipeline;
  17569. if ( pipeline ) {
  17570. // pipeline
  17571. pipeline.usedTimes --;
  17572. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  17573. // programs
  17574. if ( pipeline.isComputePipeline ) {
  17575. pipeline.computeProgram.usedTimes --;
  17576. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  17577. } else {
  17578. pipeline.fragmentProgram.usedTimes --;
  17579. pipeline.vertexProgram.usedTimes --;
  17580. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  17581. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  17582. }
  17583. }
  17584. return super.delete( object );
  17585. }
  17586. /**
  17587. * Frees internal resources.
  17588. */
  17589. dispose() {
  17590. super.dispose();
  17591. this.caches = new Map();
  17592. this.programs = {
  17593. vertex: new Map(),
  17594. fragment: new Map(),
  17595. compute: new Map()
  17596. };
  17597. }
  17598. /**
  17599. * Updates the pipeline for the given render object.
  17600. *
  17601. * @param {RenderObject} renderObject - The render object.
  17602. */
  17603. updateForRender( renderObject ) {
  17604. this.getForRender( renderObject );
  17605. }
  17606. /**
  17607. * Returns a compute pipeline for the given parameters.
  17608. *
  17609. * @private
  17610. * @param {Node} computeNode - The compute node.
  17611. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17612. * @param {String} cacheKey - The cache key.
  17613. * @param {Array<BindGroup>} bindings - The bindings.
  17614. * @return {ComputePipeline} The compute pipeline.
  17615. */
  17616. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  17617. // check for existing pipeline
  17618. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  17619. let pipeline = this.caches.get( cacheKey );
  17620. if ( pipeline === undefined ) {
  17621. pipeline = new ComputePipeline( cacheKey, stageCompute );
  17622. this.caches.set( cacheKey, pipeline );
  17623. this.backend.createComputePipeline( pipeline, bindings );
  17624. }
  17625. return pipeline;
  17626. }
  17627. /**
  17628. * Returns a render pipeline for the given parameters.
  17629. *
  17630. * @private
  17631. * @param {RenderObject} renderObject - The render object.
  17632. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17633. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17634. * @param {String} cacheKey - The cache key.
  17635. * @param {Array} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17636. * @return {ComputePipeline} The compute pipeline.
  17637. */
  17638. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  17639. // check for existing pipeline
  17640. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17641. let pipeline = this.caches.get( cacheKey );
  17642. if ( pipeline === undefined ) {
  17643. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  17644. this.caches.set( cacheKey, pipeline );
  17645. renderObject.pipeline = pipeline;
  17646. // The `promises` array is `null` by default and only set to an empty array when
  17647. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  17648. // pending promises that resolve when the render pipelines are ready for rendering.
  17649. this.backend.createRenderPipeline( renderObject, promises );
  17650. }
  17651. return pipeline;
  17652. }
  17653. /**
  17654. * Computes a cache key representing a compute pipeline.
  17655. *
  17656. * @private
  17657. * @param {Node} computeNode - The compute node.
  17658. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17659. * @return {String} The cache key.
  17660. */
  17661. _getComputeCacheKey( computeNode, stageCompute ) {
  17662. return computeNode.id + ',' + stageCompute.id;
  17663. }
  17664. /**
  17665. * Computes a cache key representing a render pipeline.
  17666. *
  17667. * @private
  17668. * @param {RenderObject} renderObject - The render object.
  17669. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17670. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17671. * @return {String} The cache key.
  17672. */
  17673. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  17674. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  17675. }
  17676. /**
  17677. * Releases the given pipeline.
  17678. *
  17679. * @private
  17680. * @param {Pipeline} pipeline - The pipeline to release.
  17681. */
  17682. _releasePipeline( pipeline ) {
  17683. this.caches.delete( pipeline.cacheKey );
  17684. }
  17685. /**
  17686. * Releases the shader program.
  17687. *
  17688. * @private
  17689. * @param {Object} program - The shdaer program to release.
  17690. */
  17691. _releaseProgram( program ) {
  17692. const code = program.code;
  17693. const stage = program.stage;
  17694. this.programs[ stage ].delete( code );
  17695. }
  17696. /**
  17697. * Returns `true` if the compute pipeline for the given compute node requires an update.
  17698. *
  17699. * @private
  17700. * @param {Node} computeNode - The compute node.
  17701. * @return {Boolean} Whether the compute pipeline for the given compute node requires an update or not.
  17702. */
  17703. _needsComputeUpdate( computeNode ) {
  17704. const data = this.get( computeNode );
  17705. return data.pipeline === undefined || data.version !== computeNode.version;
  17706. }
  17707. /**
  17708. * Returns `true` if the render pipeline for the given render object requires an update.
  17709. *
  17710. * @private
  17711. * @param {RenderObject} renderObject - The render object.
  17712. * @return {Boolean} Whether the render object for the given render object requires an update or not.
  17713. */
  17714. _needsRenderUpdate( renderObject ) {
  17715. const data = this.get( renderObject );
  17716. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  17717. }
  17718. }
  17719. /**
  17720. * This renderer module manages the bindings of the renderer.
  17721. *
  17722. * @private
  17723. * @augments DataMap
  17724. */
  17725. class Bindings extends DataMap {
  17726. /**
  17727. * Constructs a new bindings management component.
  17728. *
  17729. * @param {Backend} backend - The renderer's backend.
  17730. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17731. * @param {Textures} textures - Renderer component for managing textures.
  17732. * @param {Attributes} attributes - Renderer component for managing attributes.
  17733. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17734. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17735. */
  17736. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  17737. super();
  17738. /**
  17739. * The renderer's backend.
  17740. *
  17741. * @type {Backend}
  17742. */
  17743. this.backend = backend;
  17744. /**
  17745. * Renderer component for managing textures.
  17746. *
  17747. * @type {Textures}
  17748. */
  17749. this.textures = textures;
  17750. /**
  17751. * Renderer component for managing pipelines.
  17752. *
  17753. * @type {Pipelines}
  17754. */
  17755. this.pipelines = pipelines;
  17756. /**
  17757. * Renderer component for managing attributes.
  17758. *
  17759. * @type {Attributes}
  17760. */
  17761. this.attributes = attributes;
  17762. /**
  17763. * Renderer component for managing nodes related logic.
  17764. *
  17765. * @type {Nodes}
  17766. */
  17767. this.nodes = nodes;
  17768. /**
  17769. * Renderer component for managing metrics and monitoring data.
  17770. *
  17771. * @type {Info}
  17772. */
  17773. this.info = info;
  17774. this.pipelines.bindings = this; // assign bindings to pipelines
  17775. }
  17776. /**
  17777. * Returns the bind groups for the given render object.
  17778. *
  17779. * @param {RenderObject} renderObject - The render object.
  17780. * @return {Array<BindGroup>} The bind groups.
  17781. */
  17782. getForRender( renderObject ) {
  17783. const bindings = renderObject.getBindings();
  17784. for ( const bindGroup of bindings ) {
  17785. const groupData = this.get( bindGroup );
  17786. if ( groupData.bindGroup === undefined ) {
  17787. // each object defines an array of bindings (ubos, textures, samplers etc.)
  17788. this._init( bindGroup );
  17789. this.backend.createBindings( bindGroup, bindings, 0 );
  17790. groupData.bindGroup = bindGroup;
  17791. }
  17792. }
  17793. return bindings;
  17794. }
  17795. /**
  17796. * Returns the bind groups for the given compute node.
  17797. *
  17798. * @param {Node} computeNode - The compute node.
  17799. * @return {Array<BindGroup>} The bind groups.
  17800. */
  17801. getForCompute( computeNode ) {
  17802. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  17803. for ( const bindGroup of bindings ) {
  17804. const groupData = this.get( bindGroup );
  17805. if ( groupData.bindGroup === undefined ) {
  17806. this._init( bindGroup );
  17807. this.backend.createBindings( bindGroup, bindings, 0 );
  17808. groupData.bindGroup = bindGroup;
  17809. }
  17810. }
  17811. return bindings;
  17812. }
  17813. /**
  17814. * Updates the bindings for the given compute node.
  17815. *
  17816. * @param {Node} computeNode - The compute node.
  17817. */
  17818. updateForCompute( computeNode ) {
  17819. this._updateBindings( this.getForCompute( computeNode ) );
  17820. }
  17821. /**
  17822. * Updates the bindings for the given render object.
  17823. *
  17824. * @param {RenderObject} renderObject - The render object.
  17825. */
  17826. updateForRender( renderObject ) {
  17827. this._updateBindings( this.getForRender( renderObject ) );
  17828. }
  17829. /**
  17830. * Updates the given array of bindings.
  17831. *
  17832. * @param {Array<BindGroup>} bindings - The bind groups.
  17833. */
  17834. _updateBindings( bindings ) {
  17835. for ( const bindGroup of bindings ) {
  17836. this._update( bindGroup, bindings );
  17837. }
  17838. }
  17839. /**
  17840. * Initializes the given bind group.
  17841. *
  17842. * @param {BindGroup} bindGroup - The bind group to initialize.
  17843. */
  17844. _init( bindGroup ) {
  17845. for ( const binding of bindGroup.bindings ) {
  17846. if ( binding.isSampledTexture ) {
  17847. this.textures.updateTexture( binding.texture );
  17848. } else if ( binding.isStorageBuffer ) {
  17849. const attribute = binding.attribute;
  17850. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  17851. this.attributes.update( attribute, attributeType );
  17852. }
  17853. }
  17854. }
  17855. /**
  17856. * Updates the given bind group.
  17857. *
  17858. * @param {BindGroup} bindGroup - The bind group to update.
  17859. * @param {Array<BindGroup>} bindings - The bind groups.
  17860. */
  17861. _update( bindGroup, bindings ) {
  17862. const { backend } = this;
  17863. let needsBindingsUpdate = false;
  17864. let cacheBindings = true;
  17865. let cacheIndex = 0;
  17866. let version = 0;
  17867. // iterate over all bindings and check if buffer updates or a new binding group is required
  17868. for ( const binding of bindGroup.bindings ) {
  17869. if ( binding.isNodeUniformsGroup ) {
  17870. const updated = this.nodes.updateGroup( binding );
  17871. // every uniforms group is a uniform buffer. So if no update is required,
  17872. // we move one with the next binding. Otherwise the next if block will update the group.
  17873. if ( updated === false ) continue;
  17874. }
  17875. if ( binding.isUniformBuffer ) {
  17876. const updated = binding.update();
  17877. if ( updated ) {
  17878. backend.updateBinding( binding );
  17879. }
  17880. } else if ( binding.isSampler ) {
  17881. binding.update();
  17882. } else if ( binding.isSampledTexture ) {
  17883. const texturesTextureData = this.textures.get( binding.texture );
  17884. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  17885. const updated = binding.update();
  17886. const texture = binding.texture;
  17887. if ( updated ) {
  17888. this.textures.updateTexture( texture );
  17889. }
  17890. const textureData = backend.get( texture );
  17891. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  17892. cacheBindings = false;
  17893. } else {
  17894. cacheIndex = cacheIndex * 10 + texture.id;
  17895. version += texture.version;
  17896. }
  17897. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  17898. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  17899. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  17900. this.textures.updateTexture( texture );
  17901. needsBindingsUpdate = true;
  17902. }
  17903. if ( texture.isStorageTexture === true ) {
  17904. const textureData = this.get( texture );
  17905. if ( binding.store === true ) {
  17906. textureData.needsMipmap = true;
  17907. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  17908. this.backend.generateMipmaps( texture );
  17909. textureData.needsMipmap = false;
  17910. }
  17911. }
  17912. }
  17913. }
  17914. if ( needsBindingsUpdate === true ) {
  17915. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  17916. }
  17917. }
  17918. }
  17919. /**
  17920. * Default sorting function for opaque render items.
  17921. *
  17922. * @private
  17923. * @function
  17924. * @param {Object} a - The first render item.
  17925. * @param {Object} b - The second render item.
  17926. * @return {Number} A numeric value which defines the sort order.
  17927. */
  17928. function painterSortStable( a, b ) {
  17929. if ( a.groupOrder !== b.groupOrder ) {
  17930. return a.groupOrder - b.groupOrder;
  17931. } else if ( a.renderOrder !== b.renderOrder ) {
  17932. return a.renderOrder - b.renderOrder;
  17933. } else if ( a.material.id !== b.material.id ) {
  17934. return a.material.id - b.material.id;
  17935. } else if ( a.z !== b.z ) {
  17936. return a.z - b.z;
  17937. } else {
  17938. return a.id - b.id;
  17939. }
  17940. }
  17941. /**
  17942. * Default sorting function for transparent render items.
  17943. *
  17944. * @private
  17945. * @function
  17946. * @param {Object} a - The first render item.
  17947. * @param {Object} b - The second render item.
  17948. * @return {Number} A numeric value which defines the sort order.
  17949. */
  17950. function reversePainterSortStable( a, b ) {
  17951. if ( a.groupOrder !== b.groupOrder ) {
  17952. return a.groupOrder - b.groupOrder;
  17953. } else if ( a.renderOrder !== b.renderOrder ) {
  17954. return a.renderOrder - b.renderOrder;
  17955. } else if ( a.z !== b.z ) {
  17956. return b.z - a.z;
  17957. } else {
  17958. return a.id - b.id;
  17959. }
  17960. }
  17961. /**
  17962. * Returns `true` if the given transparent material requires a double pass.
  17963. *
  17964. * @private
  17965. * @function
  17966. * @param {Material} material - The transparent material.
  17967. * @return {Boolean} Whether the given material requires a double pass or not.
  17968. */
  17969. function needsDoublePass( material ) {
  17970. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  17971. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  17972. }
  17973. /**
  17974. * When the renderer analyzes the scene at the beginning of a render call,
  17975. * it stores 3D object for further processing in render lists. Depending on the
  17976. * properties of a 3D objects (like their transformation or material state), the
  17977. * objects are maintained in ordered lists for the actual rendering.
  17978. *
  17979. * Render lists are unique per scene and camera combination.
  17980. *
  17981. * @private
  17982. * @augments Pipeline
  17983. */
  17984. class RenderList {
  17985. /**
  17986. * Constructs a render list.
  17987. *
  17988. * @param {Lighting} lighting - The lighting management component.
  17989. * @param {Scene} scene - The scene.
  17990. * @param {Camera} camera - The camera the scene is rendered with.
  17991. */
  17992. constructor( lighting, scene, camera ) {
  17993. /**
  17994. * 3D objects are transformed into render items and stored in this array.
  17995. *
  17996. * @type {Array<Object>}
  17997. */
  17998. this.renderItems = [];
  17999. /**
  18000. * The current render items index.
  18001. *
  18002. * @type {Number}
  18003. * @default 0
  18004. */
  18005. this.renderItemsIndex = 0;
  18006. /**
  18007. * A list with opaque render items.
  18008. *
  18009. * @type {Array<Object>}
  18010. */
  18011. this.opaque = [];
  18012. /**
  18013. * A list with transparent render items which require
  18014. * double pass rendering (e.g. transmissive objects).
  18015. *
  18016. * @type {Array<Object>}
  18017. */
  18018. this.transparentDoublePass = [];
  18019. /**
  18020. * A list with transparent render items.
  18021. *
  18022. * @type {Array<Object>}
  18023. */
  18024. this.transparent = [];
  18025. /**
  18026. * A list with transparent render bundle data.
  18027. *
  18028. * @type {Array<Object>}
  18029. */
  18030. this.bundles = [];
  18031. /**
  18032. * The render list's lights node. This node is later
  18033. * relevant for the actual analytical light nodes which
  18034. * compute the scene's lighting in the shader.
  18035. *
  18036. * @type {LightsNode}
  18037. */
  18038. this.lightsNode = lighting.getNode( scene, camera );
  18039. /**
  18040. * The scene's lights stored in an array. This array
  18041. * is used to setup the lights node.
  18042. *
  18043. * @type {Array<Light>}
  18044. */
  18045. this.lightsArray = [];
  18046. /**
  18047. * The scene.
  18048. *
  18049. * @type {Scene}
  18050. */
  18051. this.scene = scene;
  18052. /**
  18053. * The camera the scene is rendered with.
  18054. *
  18055. * @type {Camera}
  18056. */
  18057. this.camera = camera;
  18058. /**
  18059. * How many objects perform occlusion query tests.
  18060. *
  18061. * @type {Number}
  18062. * @default 0
  18063. */
  18064. this.occlusionQueryCount = 0;
  18065. }
  18066. /**
  18067. * This method is called right at the beginning of a render call
  18068. * before the scene is analyzed. It prepares the internal data
  18069. * structures for the upcoming render lists generation.
  18070. *
  18071. * @return {RenderList} A reference to this render list.
  18072. */
  18073. begin() {
  18074. this.renderItemsIndex = 0;
  18075. this.opaque.length = 0;
  18076. this.transparentDoublePass.length = 0;
  18077. this.transparent.length = 0;
  18078. this.bundles.length = 0;
  18079. this.lightsArray.length = 0;
  18080. this.occlusionQueryCount = 0;
  18081. return this;
  18082. }
  18083. /**
  18084. * Returns a render item for the giving render item state. The state is defined
  18085. * by a series of object-related parameters.
  18086. *
  18087. * The method avoids object creation by holding render items and reusing them in
  18088. * subsequent render calls (just with different property values).
  18089. *
  18090. * @param {Object3D} object - The 3D object.
  18091. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18092. * @param {Material} material - The 3D object's material.
  18093. * @param {Number} groupOrder - The current group order.
  18094. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18095. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18096. * @param {ClippingContext} clippingContext - The current clipping context.
  18097. * @return {Object} The render item.
  18098. */
  18099. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18100. let renderItem = this.renderItems[ this.renderItemsIndex ];
  18101. if ( renderItem === undefined ) {
  18102. renderItem = {
  18103. id: object.id,
  18104. object: object,
  18105. geometry: geometry,
  18106. material: material,
  18107. groupOrder: groupOrder,
  18108. renderOrder: object.renderOrder,
  18109. z: z,
  18110. group: group,
  18111. clippingContext: clippingContext
  18112. };
  18113. this.renderItems[ this.renderItemsIndex ] = renderItem;
  18114. } else {
  18115. renderItem.id = object.id;
  18116. renderItem.object = object;
  18117. renderItem.geometry = geometry;
  18118. renderItem.material = material;
  18119. renderItem.groupOrder = groupOrder;
  18120. renderItem.renderOrder = object.renderOrder;
  18121. renderItem.z = z;
  18122. renderItem.group = group;
  18123. renderItem.clippingContext = clippingContext;
  18124. }
  18125. this.renderItemsIndex ++;
  18126. return renderItem;
  18127. }
  18128. /**
  18129. * Pushes the given object as a render item to the internal render lists.
  18130. * The selected lists depend on the object properties.
  18131. *
  18132. * @param {Object3D} object - The 3D object.
  18133. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18134. * @param {Material} material - The 3D object's material.
  18135. * @param {Number} groupOrder - The current group order.
  18136. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18137. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18138. * @param {ClippingContext} clippingContext - The current clipping context.
  18139. */
  18140. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18141. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18142. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  18143. if ( material.transparent === true || material.transmission > 0 ) {
  18144. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  18145. this.transparent.push( renderItem );
  18146. } else {
  18147. this.opaque.push( renderItem );
  18148. }
  18149. }
  18150. /**
  18151. * Inserts the given object as a render item at the start of the internal render lists.
  18152. * The selected lists depend on the object properties.
  18153. *
  18154. * @param {Object3D} object - The 3D object.
  18155. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18156. * @param {Material} material - The 3D object's material.
  18157. * @param {Number} groupOrder - The current group order.
  18158. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18159. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18160. * @param {ClippingContext} clippingContext - The current clipping context.
  18161. */
  18162. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18163. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18164. if ( material.transparent === true || material.transmission > 0 ) {
  18165. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  18166. this.transparent.unshift( renderItem );
  18167. } else {
  18168. this.opaque.unshift( renderItem );
  18169. }
  18170. }
  18171. /**
  18172. * Pushes render bundle group data into the render list.
  18173. *
  18174. * @param {Object} group - Bundle group data.
  18175. */
  18176. pushBundle( group ) {
  18177. this.bundles.push( group );
  18178. }
  18179. /**
  18180. * Pushes a light into the render list.
  18181. *
  18182. * @param {Light} light - The light.
  18183. */
  18184. pushLight( light ) {
  18185. this.lightsArray.push( light );
  18186. }
  18187. /**
  18188. * Sorts the internal render lists.
  18189. *
  18190. * @param {Function} customOpaqueSort - A custom sort function for opaque objects.
  18191. * @param {Function} customTransparentSort - A custom sort function for transparent objects.
  18192. */
  18193. sort( customOpaqueSort, customTransparentSort ) {
  18194. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  18195. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  18196. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  18197. }
  18198. /**
  18199. * This method performs finalizing tasks right after the render lists
  18200. * have been generated.
  18201. */
  18202. finish() {
  18203. // update lights
  18204. this.lightsNode.setLights( this.lightsArray );
  18205. // Clear references from inactive renderItems in the list
  18206. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  18207. const renderItem = this.renderItems[ i ];
  18208. if ( renderItem.id === null ) break;
  18209. renderItem.id = null;
  18210. renderItem.object = null;
  18211. renderItem.geometry = null;
  18212. renderItem.material = null;
  18213. renderItem.groupOrder = null;
  18214. renderItem.renderOrder = null;
  18215. renderItem.z = null;
  18216. renderItem.group = null;
  18217. renderItem.clippingContext = null;
  18218. }
  18219. }
  18220. }
  18221. /**
  18222. * This renderer module manages the render lists which are unique
  18223. * per scene and camera combination.
  18224. *
  18225. * @private
  18226. */
  18227. class RenderLists {
  18228. /**
  18229. * Constructs a render lists management component.
  18230. *
  18231. * @param {Lighting} lighting - The lighting management component.
  18232. */
  18233. constructor( lighting ) {
  18234. /**
  18235. * The lighting management component.
  18236. *
  18237. * @type {Lighting}
  18238. */
  18239. this.lighting = lighting;
  18240. /**
  18241. * The internal chain map which holds the render lists.
  18242. *
  18243. * @type {ChainMap}
  18244. */
  18245. this.lists = new ChainMap();
  18246. }
  18247. /**
  18248. * Returns a render list for the given scene and camera.
  18249. *
  18250. * @param {Scene} scene - The scene.
  18251. * @param {Camera} camera - The camera.
  18252. * @return {RenderList} The render list.
  18253. */
  18254. get( scene, camera ) {
  18255. const lists = this.lists;
  18256. const keys = [ scene, camera ];
  18257. let list = lists.get( keys );
  18258. if ( list === undefined ) {
  18259. list = new RenderList( this.lighting, scene, camera );
  18260. lists.set( keys, list );
  18261. }
  18262. return list;
  18263. }
  18264. /**
  18265. * Frees all internal resources.
  18266. */
  18267. dispose() {
  18268. this.lists = new ChainMap();
  18269. }
  18270. }
  18271. let _id$7 = 0;
  18272. /**
  18273. * Any render or compute command is executed in a specific context that defines
  18274. * the state of the renderer and its backend. Typical examples for such context
  18275. * data are the current clear values or data from the active framebuffer. This
  18276. * module is used to represent these contexts as objects.
  18277. *
  18278. * @private
  18279. */
  18280. class RenderContext {
  18281. /**
  18282. * Constructs a new render context.
  18283. */
  18284. constructor() {
  18285. /**
  18286. * The context's ID.
  18287. *
  18288. * @type {Number}
  18289. */
  18290. this.id = _id$7 ++;
  18291. /**
  18292. * Whether the current active framebuffer has a color attachment.
  18293. *
  18294. * @type {Boolean}
  18295. * @default true
  18296. */
  18297. this.color = true;
  18298. /**
  18299. * Whether the color attachment should be cleared or not.
  18300. *
  18301. * @type {Boolean}
  18302. * @default true
  18303. */
  18304. this.clearColor = true;
  18305. /**
  18306. * The clear color value.
  18307. *
  18308. * @type {Object}
  18309. * @default true
  18310. */
  18311. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  18312. /**
  18313. * Whether the current active framebuffer has a depth attachment.
  18314. *
  18315. * @type {Boolean}
  18316. * @default true
  18317. */
  18318. this.depth = true;
  18319. /**
  18320. * Whether the depth attachment should be cleared or not.
  18321. *
  18322. * @type {Boolean}
  18323. * @default true
  18324. */
  18325. this.clearDepth = true;
  18326. /**
  18327. * The clear depth value.
  18328. *
  18329. * @type {Number}
  18330. * @default 1
  18331. */
  18332. this.clearDepthValue = 1;
  18333. /**
  18334. * Whether the current active framebuffer has a stencil attachment.
  18335. *
  18336. * @type {Boolean}
  18337. * @default false
  18338. */
  18339. this.stencil = false;
  18340. /**
  18341. * Whether the stencil attachment should be cleared or not.
  18342. *
  18343. * @type {Boolean}
  18344. * @default true
  18345. */
  18346. this.clearStencil = true;
  18347. /**
  18348. * The clear stencil value.
  18349. *
  18350. * @type {Number}
  18351. * @default 1
  18352. */
  18353. this.clearStencilValue = 1;
  18354. /**
  18355. * By default the viewport encloses the entire framebuffer If a smaller
  18356. * viewport is manually defined, this property is to `true` by the renderer.
  18357. *
  18358. * @type {Boolean}
  18359. * @default false
  18360. */
  18361. this.viewport = false;
  18362. /**
  18363. * The viewport value. This value is in physical pixels meaning it incorporates
  18364. * the renderer's pixel ratio. The viewport property of render targets or
  18365. * the renderer is in logical pixels.
  18366. *
  18367. * @type {Vector4}
  18368. */
  18369. this.viewportValue = new Vector4();
  18370. /**
  18371. * When the scissor test is active and scissor rectangle smaller than the
  18372. * framebuffers dimensions, this property is to `true` by the renderer.
  18373. *
  18374. * @type {Boolean}
  18375. * @default false
  18376. */
  18377. this.scissor = false;
  18378. /**
  18379. * The scissor rectangle.
  18380. *
  18381. * @type {Vector4}
  18382. */
  18383. this.scissorValue = new Vector4();
  18384. /**
  18385. * The textures of the active render target.
  18386. * `null` when no render target is set.
  18387. *
  18388. * @type {Array<Texture>?}
  18389. * @default null
  18390. */
  18391. this.textures = null;
  18392. /**
  18393. * The depth texture of the active render target.
  18394. * `null` when no render target is set.
  18395. *
  18396. * @type {DepthTexture?}
  18397. * @default null
  18398. */
  18399. this.depthTexture = null;
  18400. /**
  18401. * The active cube face.
  18402. *
  18403. * @type {Number}
  18404. * @default 0
  18405. */
  18406. this.activeCubeFace = 0;
  18407. /**
  18408. * The number of MSAA samples. This value is always `1` when
  18409. * MSAA isn't used.
  18410. *
  18411. * @type {Number}
  18412. * @default 1
  18413. */
  18414. this.sampleCount = 1;
  18415. /**
  18416. * The framebuffers width in physical pixels.
  18417. *
  18418. * @type {Number}
  18419. * @default 0
  18420. */
  18421. this.width = 0;
  18422. /**
  18423. * The framebuffers height in physical pixels.
  18424. *
  18425. * @type {Number}
  18426. * @default 0
  18427. */
  18428. this.height = 0;
  18429. /**
  18430. * This flag can be used for type testing.
  18431. *
  18432. * @type {Boolean}
  18433. * @readonly
  18434. * @default true
  18435. */
  18436. this.isRenderContext = true;
  18437. }
  18438. /**
  18439. * Returns the cache key of this render context.
  18440. *
  18441. * @return {Number} The cache key.
  18442. */
  18443. getCacheKey() {
  18444. return getCacheKey( this );
  18445. }
  18446. }
  18447. /**
  18448. * Computes a cache key for the given render context.
  18449. *
  18450. * @param {RenderContext} renderContext - The render context.
  18451. * @return {Number} The cache key.
  18452. */
  18453. function getCacheKey( renderContext ) {
  18454. const { textures, activeCubeFace } = renderContext;
  18455. const values = [ activeCubeFace ];
  18456. for ( const texture of textures ) {
  18457. values.push( texture.id );
  18458. }
  18459. return hashArray( values );
  18460. }
  18461. /**
  18462. * This module manages the render contexts of the renderer.
  18463. *
  18464. * @private
  18465. */
  18466. class RenderContexts {
  18467. /**
  18468. * Constructs a new render context management component.
  18469. */
  18470. constructor() {
  18471. /**
  18472. * A dictionary that manages render contexts in chain maps
  18473. * for each attachment state.
  18474. *
  18475. * @type {Object<String,ChainMap>}
  18476. */
  18477. this.chainMaps = {};
  18478. }
  18479. /**
  18480. * Returns a render context for the given scene, camera and render target.
  18481. *
  18482. * @param {Scene?} [scene=null] - The scene. The parameter can become `null` e.g. when the renderer clears a render target.
  18483. * @param {Camera?} [camera=null] - The camera that is used to render the scene. The parameter can become `null` e.g. when the renderer clears a render target.
  18484. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18485. * @return {RenderContext} The render context.
  18486. */
  18487. get( scene = null, camera = null, renderTarget = null ) {
  18488. const chainKey = [];
  18489. if ( scene !== null ) chainKey.push( scene );
  18490. if ( camera !== null ) chainKey.push( camera );
  18491. if ( chainKey.length === 0 ) {
  18492. chainKey.push( { id: 'default' } );
  18493. }
  18494. let attachmentState;
  18495. if ( renderTarget === null ) {
  18496. attachmentState = 'default';
  18497. } else {
  18498. const format = renderTarget.texture.format;
  18499. const count = renderTarget.textures.length;
  18500. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  18501. }
  18502. const chainMap = this.getChainMap( attachmentState );
  18503. let renderState = chainMap.get( chainKey );
  18504. if ( renderState === undefined ) {
  18505. renderState = new RenderContext();
  18506. chainMap.set( chainKey, renderState );
  18507. }
  18508. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18509. return renderState;
  18510. }
  18511. /**
  18512. * Returns a chain map for the given attachment state.
  18513. *
  18514. * @param {String} attachmentState - The attachment state.
  18515. * @return {ChainMap} The chain map.
  18516. */
  18517. getChainMap( attachmentState ) {
  18518. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  18519. }
  18520. /**
  18521. * Frees internal resources.
  18522. */
  18523. dispose() {
  18524. this.chainMaps = {};
  18525. }
  18526. }
  18527. const _size$3 = /*@__PURE__*/ new Vector3();
  18528. /**
  18529. * This module manages the textures of the renderer.
  18530. *
  18531. * @private
  18532. * @augments DataMap
  18533. */
  18534. class Textures extends DataMap {
  18535. /**
  18536. * Constructs a new texture management component.
  18537. *
  18538. * @param {Renderer} renderer - The renderer.
  18539. * @param {Backend} backend - The renderer's backend.
  18540. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18541. */
  18542. constructor( renderer, backend, info ) {
  18543. super();
  18544. /**
  18545. * The renderer.
  18546. *
  18547. * @type {Renderer}
  18548. */
  18549. this.renderer = renderer;
  18550. /**
  18551. * The backend.
  18552. *
  18553. * @type {Backend}
  18554. */
  18555. this.backend = backend;
  18556. /**
  18557. * Renderer component for managing metrics and monitoring data.
  18558. *
  18559. * @type {Info}
  18560. */
  18561. this.info = info;
  18562. }
  18563. /**
  18564. * Updates the given render target. Based on the given render target configuration,
  18565. * it updates the texture states representing the attachments of the framebuffer.
  18566. *
  18567. * @param {RenderTarget} renderTarget - The render target to update.
  18568. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  18569. */
  18570. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  18571. const renderTargetData = this.get( renderTarget );
  18572. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18573. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  18574. const textures = renderTarget.textures;
  18575. const size = this.getSize( textures[ 0 ] );
  18576. const mipWidth = size.width >> activeMipmapLevel;
  18577. const mipHeight = size.height >> activeMipmapLevel;
  18578. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  18579. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  18580. let textureNeedsUpdate = false;
  18581. if ( depthTexture === undefined && useDepthTexture ) {
  18582. depthTexture = new DepthTexture();
  18583. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  18584. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  18585. depthTexture.image.width = mipWidth;
  18586. depthTexture.image.height = mipHeight;
  18587. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  18588. }
  18589. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  18590. textureNeedsUpdate = true;
  18591. if ( depthTexture ) {
  18592. depthTexture.needsUpdate = true;
  18593. depthTexture.image.width = mipWidth;
  18594. depthTexture.image.height = mipHeight;
  18595. }
  18596. }
  18597. renderTargetData.width = size.width;
  18598. renderTargetData.height = size.height;
  18599. renderTargetData.textures = textures;
  18600. renderTargetData.depthTexture = depthTexture || null;
  18601. renderTargetData.depth = renderTarget.depthBuffer;
  18602. renderTargetData.stencil = renderTarget.stencilBuffer;
  18603. renderTargetData.renderTarget = renderTarget;
  18604. if ( renderTargetData.sampleCount !== sampleCount ) {
  18605. textureNeedsUpdate = true;
  18606. if ( depthTexture ) {
  18607. depthTexture.needsUpdate = true;
  18608. }
  18609. renderTargetData.sampleCount = sampleCount;
  18610. }
  18611. //
  18612. const options = { sampleCount };
  18613. for ( let i = 0; i < textures.length; i ++ ) {
  18614. const texture = textures[ i ];
  18615. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  18616. this.updateTexture( texture, options );
  18617. }
  18618. if ( depthTexture ) {
  18619. this.updateTexture( depthTexture, options );
  18620. }
  18621. // dispose handler
  18622. if ( renderTargetData.initialized !== true ) {
  18623. renderTargetData.initialized = true;
  18624. // dispose
  18625. const onDispose = () => {
  18626. renderTarget.removeEventListener( 'dispose', onDispose );
  18627. for ( let i = 0; i < textures.length; i ++ ) {
  18628. this._destroyTexture( textures[ i ] );
  18629. }
  18630. if ( depthTexture ) {
  18631. this._destroyTexture( depthTexture );
  18632. }
  18633. this.delete( renderTarget );
  18634. };
  18635. renderTarget.addEventListener( 'dispose', onDispose );
  18636. }
  18637. }
  18638. /**
  18639. * Updates the given texture. Depending on the texture state, this method
  18640. * triggers the upload of texture data to the GPU memory. If the texture data are
  18641. * not yet ready for the upload, it uses default texture data for as a placeholder.
  18642. *
  18643. * @param {Texture} texture - The texture to update.
  18644. * @param {Object} [options={}] - The options.
  18645. */
  18646. updateTexture( texture, options = {} ) {
  18647. const textureData = this.get( texture );
  18648. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  18649. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  18650. const backend = this.backend;
  18651. if ( isRenderTarget && textureData.initialized === true ) {
  18652. // it's an update
  18653. backend.destroySampler( texture );
  18654. backend.destroyTexture( texture );
  18655. }
  18656. //
  18657. if ( texture.isFramebufferTexture ) {
  18658. const renderTarget = this.renderer.getRenderTarget();
  18659. if ( renderTarget ) {
  18660. texture.type = renderTarget.texture.type;
  18661. } else {
  18662. texture.type = UnsignedByteType;
  18663. }
  18664. }
  18665. //
  18666. const { width, height, depth } = this.getSize( texture );
  18667. options.width = width;
  18668. options.height = height;
  18669. options.depth = depth;
  18670. options.needsMipmaps = this.needsMipmaps( texture );
  18671. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  18672. //
  18673. if ( isRenderTarget || texture.isStorageTexture === true ) {
  18674. backend.createSampler( texture );
  18675. backend.createTexture( texture, options );
  18676. textureData.generation = texture.version;
  18677. } else {
  18678. const needsCreate = textureData.initialized !== true;
  18679. if ( needsCreate ) backend.createSampler( texture );
  18680. if ( texture.version > 0 ) {
  18681. const image = texture.image;
  18682. if ( image === undefined ) {
  18683. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  18684. } else if ( image.complete === false ) {
  18685. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  18686. } else {
  18687. if ( texture.images ) {
  18688. const images = [];
  18689. for ( const image of texture.images ) {
  18690. images.push( image );
  18691. }
  18692. options.images = images;
  18693. } else {
  18694. options.image = image;
  18695. }
  18696. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  18697. backend.createTexture( texture, options );
  18698. textureData.isDefaultTexture = false;
  18699. textureData.generation = texture.version;
  18700. }
  18701. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  18702. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  18703. }
  18704. } else {
  18705. // async update
  18706. backend.createDefaultTexture( texture );
  18707. textureData.isDefaultTexture = true;
  18708. textureData.generation = texture.version;
  18709. }
  18710. }
  18711. // dispose handler
  18712. if ( textureData.initialized !== true ) {
  18713. textureData.initialized = true;
  18714. textureData.generation = texture.version;
  18715. //
  18716. this.info.memory.textures ++;
  18717. // dispose
  18718. const onDispose = () => {
  18719. texture.removeEventListener( 'dispose', onDispose );
  18720. this._destroyTexture( texture );
  18721. this.info.memory.textures --;
  18722. };
  18723. texture.addEventListener( 'dispose', onDispose );
  18724. }
  18725. //
  18726. textureData.version = texture.version;
  18727. }
  18728. /**
  18729. * Computes the size of the given texture and writes the result
  18730. * into the target vector. This vector is also returned by the
  18731. * method.
  18732. *
  18733. * If no texture data are available for the compute yet, the method
  18734. * returns default size values.
  18735. *
  18736. * @param {Texture} texture - The texture to compute the size for.
  18737. * @param {Vector3} target - The target vector.
  18738. * @return {Vector3} The target vector.
  18739. */
  18740. getSize( texture, target = _size$3 ) {
  18741. let image = texture.images ? texture.images[ 0 ] : texture.image;
  18742. if ( image ) {
  18743. if ( image.image !== undefined ) image = image.image;
  18744. target.width = image.width || 1;
  18745. target.height = image.height || 1;
  18746. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  18747. } else {
  18748. target.width = target.height = target.depth = 1;
  18749. }
  18750. return target;
  18751. }
  18752. /**
  18753. * Computes the number of mipmap levels for the given texture.
  18754. *
  18755. * @param {Texture} texture - The texture.
  18756. * @param {Number} width - The texture's width.
  18757. * @param {Number} height - The texture's height.
  18758. * @return {Number} The number of mipmap levels.
  18759. */
  18760. getMipLevels( texture, width, height ) {
  18761. let mipLevelCount;
  18762. if ( texture.isCompressedTexture ) {
  18763. if ( texture.mipmaps ) {
  18764. mipLevelCount = texture.mipmaps.length;
  18765. } else {
  18766. mipLevelCount = 1;
  18767. }
  18768. } else {
  18769. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  18770. }
  18771. return mipLevelCount;
  18772. }
  18773. /**
  18774. * Returns `true` if the given texture requires mipmaps.
  18775. *
  18776. * @param {Texture} texture - The texture.
  18777. * @return {Boolean} Whether mipmaps are required or not.
  18778. */
  18779. needsMipmaps( texture ) {
  18780. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  18781. }
  18782. /**
  18783. * Returns `true` if the given texture is an environment map.
  18784. *
  18785. * @param {Texture} texture - The texture.
  18786. * @return {Boolean} Whether the given texture is an environment map or not.
  18787. */
  18788. isEnvironmentTexture( texture ) {
  18789. const mapping = texture.mapping;
  18790. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  18791. }
  18792. /**
  18793. * Frees internal resource when the given texture isn't
  18794. * required anymore.
  18795. *
  18796. * @param {Texture} texture - The texture to destroy.
  18797. */
  18798. _destroyTexture( texture ) {
  18799. this.backend.destroySampler( texture );
  18800. this.backend.destroyTexture( texture );
  18801. this.delete( texture );
  18802. }
  18803. }
  18804. /**
  18805. * A four-component version of {@link Color} which is internally
  18806. * used by the renderer to represents clear color with alpha as
  18807. * one object.
  18808. *
  18809. * @private
  18810. * @augments Color
  18811. */
  18812. class Color4 extends Color {
  18813. /**
  18814. * Constructs a new four-component color.
  18815. *
  18816. * @param {Number|String} r - The red value.
  18817. * @param {Number} g - The green value.
  18818. * @param {Number} b - The blue value.
  18819. * @param {Number} [a=1] - The alpha value.
  18820. */
  18821. constructor( r, g, b, a = 1 ) {
  18822. super( r, g, b );
  18823. this.a = a;
  18824. }
  18825. /**
  18826. * Overwrites the default to honor alpha.
  18827. *
  18828. * @param {Number|String} r - The red value.
  18829. * @param {Number} g - The green value.
  18830. * @param {Number} b - The blue value.
  18831. * @param {Number} [a=1] - The alpha value.
  18832. * @return {Color4} A reference to this object.
  18833. */
  18834. set( r, g, b, a = 1 ) {
  18835. this.a = a;
  18836. return super.set( r, g, b );
  18837. }
  18838. /**
  18839. * Overwrites the default to honor alpha.
  18840. *
  18841. * @param {Color4} color - The color to copy.
  18842. * @return {Color4} A reference to this object.
  18843. */
  18844. copy( color ) {
  18845. if ( color.a !== undefined ) this.a = color.a;
  18846. return super.copy( color );
  18847. }
  18848. /**
  18849. * Overwrites the default to honor alpha.
  18850. *
  18851. * @return {Color4} The cloned color.
  18852. */
  18853. clone() {
  18854. return new this.constructor( this.r, this.g, this.b, this.a );
  18855. }
  18856. }
  18857. /** @module ParameterNode **/
  18858. /**
  18859. * Special version of {@link PropertyNode} which is used for parameters.
  18860. *
  18861. * @augments PropertyNode
  18862. */
  18863. class ParameterNode extends PropertyNode {
  18864. static get type() {
  18865. return 'ParameterNode';
  18866. }
  18867. /**
  18868. * Constructs a new parameter node.
  18869. *
  18870. * @param {String} nodeType - The type of the node.
  18871. * @param {String?} [name=null] - The name of the parameter in the shader.
  18872. */
  18873. constructor( nodeType, name = null ) {
  18874. super( nodeType, name );
  18875. /**
  18876. * This flag can be used for type testing.
  18877. *
  18878. * @type {Boolean}
  18879. * @readonly
  18880. * @default true
  18881. */
  18882. this.isParameterNode = true;
  18883. }
  18884. getHash() {
  18885. return this.uuid;
  18886. }
  18887. generate() {
  18888. return this.name;
  18889. }
  18890. }
  18891. /**
  18892. * TSL function for creating a parameter node.
  18893. *
  18894. * @function
  18895. * @param {String} type - The type of the node.
  18896. * @param {String?} name - The name of the parameter in the shader.
  18897. * @returns {ParameterNode}
  18898. */
  18899. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  18900. /** @module StackNode **/
  18901. /**
  18902. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  18903. * They are usually needed in cases like `If`, `Else`.
  18904. *
  18905. * @augments Node
  18906. */
  18907. class StackNode extends Node {
  18908. static get type() {
  18909. return 'StackNode';
  18910. }
  18911. /**
  18912. * Constructs a new stack node.
  18913. *
  18914. * @param {StackNode?} [parent=null] - The parent stack node.
  18915. */
  18916. constructor( parent = null ) {
  18917. super();
  18918. /**
  18919. * List of nodes.
  18920. *
  18921. * @type {Array<Node>}
  18922. */
  18923. this.nodes = [];
  18924. /**
  18925. * The output node.
  18926. *
  18927. * @type {Node?}
  18928. * @default null
  18929. */
  18930. this.outputNode = null;
  18931. /**
  18932. * The parent stack node.
  18933. *
  18934. * @type {StackNode}
  18935. * @default null
  18936. */
  18937. this.parent = parent;
  18938. /**
  18939. * The current conditional node.
  18940. *
  18941. * @private
  18942. * @type {ConditionalNode}
  18943. * @default null
  18944. */
  18945. this._currentCond = null;
  18946. /**
  18947. * This flag can be used for type testing.
  18948. *
  18949. * @type {Boolean}
  18950. * @readonly
  18951. * @default true
  18952. */
  18953. this.isStackNode = true;
  18954. }
  18955. getNodeType( builder ) {
  18956. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  18957. }
  18958. /**
  18959. * Adds a node to this stack.
  18960. *
  18961. * @param {Node} node - The node to add.
  18962. * @return {StackNode} A reference to this stack node.
  18963. */
  18964. add( node ) {
  18965. this.nodes.push( node );
  18966. return this;
  18967. }
  18968. /**
  18969. * Represent an `if` statement in TSL.
  18970. *
  18971. * @param {Node} boolNode - Represents the condition.
  18972. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  18973. * @return {StackNode} A reference to this stack node.
  18974. */
  18975. If( boolNode, method ) {
  18976. const methodNode = new ShaderNode( method );
  18977. this._currentCond = select( boolNode, methodNode );
  18978. return this.add( this._currentCond );
  18979. }
  18980. /**
  18981. * Represent an `elseif` statement in TSL.
  18982. *
  18983. * @param {Node} boolNode - Represents the condition.
  18984. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  18985. * @return {StackNode} A reference to this stack node.
  18986. */
  18987. ElseIf( boolNode, method ) {
  18988. const methodNode = new ShaderNode( method );
  18989. const ifNode = select( boolNode, methodNode );
  18990. this._currentCond.elseNode = ifNode;
  18991. this._currentCond = ifNode;
  18992. return this;
  18993. }
  18994. /**
  18995. * Represent an `else` statement in TSL.
  18996. *
  18997. * @param {Function} method - TSL code which is executed in the `else` case.
  18998. * @return {StackNode} A reference to this stack node.
  18999. */
  19000. Else( method ) {
  19001. this._currentCond.elseNode = new ShaderNode( method );
  19002. return this;
  19003. }
  19004. build( builder, ...params ) {
  19005. const previousStack = getCurrentStack();
  19006. setCurrentStack( this );
  19007. for ( const node of this.nodes ) {
  19008. node.build( builder, 'void' );
  19009. }
  19010. setCurrentStack( previousStack );
  19011. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  19012. }
  19013. //
  19014. else( ...params ) { // @deprecated, r168
  19015. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  19016. return this.Else( ...params );
  19017. }
  19018. elseif( ...params ) { // @deprecated, r168
  19019. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  19020. return this.ElseIf( ...params );
  19021. }
  19022. }
  19023. /**
  19024. * TSL function for creating a stack node.
  19025. *
  19026. * @function
  19027. * @param {StackNode?} [parent=null] - The parent stack node.
  19028. * @returns {StackNode}
  19029. */
  19030. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  19031. /** @module OutputStructNode **/
  19032. /**
  19033. * This node can be used to define multiple outputs in a shader programs.
  19034. *
  19035. * @augments Node
  19036. */
  19037. class OutputStructNode extends Node {
  19038. static get type() {
  19039. return 'OutputStructNode';
  19040. }
  19041. /**
  19042. * Constructs a new output struct node. The constructor can be invoked with an
  19043. * arbitrary number of nodes representing the members.
  19044. *
  19045. * @param {...Node} members - A parameter list of nodes.
  19046. */
  19047. constructor( ...members ) {
  19048. super();
  19049. /**
  19050. * An array of nodes which defines the output.
  19051. *
  19052. * @type {Array<Node>}
  19053. */
  19054. this.members = members;
  19055. /**
  19056. * This flag can be used for type testing.
  19057. *
  19058. * @type {Boolean}
  19059. * @readonly
  19060. * @default true
  19061. */
  19062. this.isOutputStructNode = true;
  19063. }
  19064. setup( builder ) {
  19065. super.setup( builder );
  19066. const members = this.members;
  19067. const types = [];
  19068. for ( let i = 0; i < members.length; i ++ ) {
  19069. types.push( members[ i ].getNodeType( builder ) );
  19070. }
  19071. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  19072. }
  19073. generate( builder, output ) {
  19074. const propertyName = builder.getOutputStructName();
  19075. const members = this.members;
  19076. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  19077. for ( let i = 0; i < members.length; i ++ ) {
  19078. const snippet = members[ i ].build( builder, output );
  19079. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  19080. }
  19081. return propertyName;
  19082. }
  19083. }
  19084. /**
  19085. * TSL function for creating an output struct node.
  19086. *
  19087. * @function
  19088. * @param {...Node} members - A parameter list of nodes.
  19089. * @returns {OutputStructNode}
  19090. */
  19091. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  19092. /** @module MRTNode **/
  19093. /**
  19094. * Returns the MRT texture index for the given name.
  19095. *
  19096. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  19097. * @param {String} name - The name of the MRT texture which index is requested.
  19098. * @return {Number} The texture index.
  19099. */
  19100. function getTextureIndex( textures, name ) {
  19101. for ( let i = 0; i < textures.length; i ++ ) {
  19102. if ( textures[ i ].name === name ) {
  19103. return i;
  19104. }
  19105. }
  19106. return - 1;
  19107. }
  19108. /**
  19109. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  19110. * post-processing is shown below:
  19111. * ```js
  19112. * const mrtNode = mrt( {
  19113. * output: output,
  19114. * normal: normalView
  19115. * } ) );
  19116. * ```
  19117. * The MRT output is defined as a dictionary.
  19118. *
  19119. * @augments OutputStructNode
  19120. */
  19121. class MRTNode extends OutputStructNode {
  19122. static get type() {
  19123. return 'MRTNode';
  19124. }
  19125. /**
  19126. * Constructs a new output struct node.
  19127. *
  19128. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19129. */
  19130. constructor( outputNodes ) {
  19131. super();
  19132. /**
  19133. * A dictionary representing the MRT outputs. The key
  19134. * is the name of the output, the value the node which produces
  19135. * the output result.
  19136. *
  19137. * @type {Object<String, Node>}
  19138. */
  19139. this.outputNodes = outputNodes;
  19140. /**
  19141. * This flag can be used for type testing.
  19142. *
  19143. * @type {Boolean}
  19144. * @readonly
  19145. * @default true
  19146. */
  19147. this.isMRTNode = true;
  19148. }
  19149. /**
  19150. * Returns `true` if the MRT node has an output with the given name.
  19151. *
  19152. * @param {String} name - The name of the output.
  19153. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  19154. */
  19155. has( name ) {
  19156. return this.outputNodes[ name ] !== undefined;
  19157. }
  19158. /**
  19159. * Returns the output node for the given name.
  19160. *
  19161. * @param {String} name - The name of the output.
  19162. * @return {Node} The output node.
  19163. */
  19164. get( name ) {
  19165. return this.outputNodes[ name ];
  19166. }
  19167. /**
  19168. * Merges the outputs of the given MRT node with the outputs of this node.
  19169. *
  19170. * @param {MRTNode} mrtNode - The MRT to merge.
  19171. * @return {MRTNode} A new MRT node with merged outputs..
  19172. */
  19173. merge( mrtNode ) {
  19174. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  19175. return mrt( outputs );
  19176. }
  19177. setup( builder ) {
  19178. const outputNodes = this.outputNodes;
  19179. const mrt = builder.renderer.getRenderTarget();
  19180. const members = [];
  19181. const textures = mrt.textures;
  19182. for ( const name in outputNodes ) {
  19183. const index = getTextureIndex( textures, name );
  19184. members[ index ] = vec4( outputNodes[ name ] );
  19185. }
  19186. this.members = members;
  19187. return super.setup( builder );
  19188. }
  19189. }
  19190. /**
  19191. * TSL function for creating a MRT node.
  19192. *
  19193. * @function
  19194. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19195. * @returns {MRTNode}
  19196. */
  19197. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  19198. /** @module Hash **/
  19199. /**
  19200. * Generates a hash value in the range `[0, 1]` from the given seed.
  19201. *
  19202. * @method
  19203. * @param {Node<float>} seed - The seed.
  19204. * @return {Node<float>} The hash value.
  19205. */
  19206. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  19207. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  19208. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  19209. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  19210. const result = word.shiftRight( 22 ).bitXor( word );
  19211. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  19212. } );
  19213. /** @module MathUtils **/
  19214. /**
  19215. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19216. * The corners are mapped to `0` and the center to `1`.
  19217. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19218. *
  19219. * @method
  19220. * @param {Node<float>} x - The value to remap.
  19221. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  19222. * @return {Node<float>} The remapped value.
  19223. */
  19224. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  19225. /**
  19226. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19227. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  19228. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19229. *
  19230. * @method
  19231. * @param {Node<float>} x - The value to remap.
  19232. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  19233. * @return {Node<float>} The remapped value.
  19234. */
  19235. const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) );
  19236. /**
  19237. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19238. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  19239. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19240. *
  19241. * @method
  19242. * @param {Node<float>} x - The value to remap.
  19243. * @param {Node<float>} a - First control parameter.
  19244. * @param {Node<float>} b - Second control parameter.
  19245. * @return {Node<float>} The remapped value.
  19246. */
  19247. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  19248. /**
  19249. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  19250. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19251. *
  19252. * @method
  19253. * @param {Node<float>} x - The value to compute the sin for.
  19254. * @param {Node<float>} k - Controls the amount of bounces.
  19255. * @return {Node<float>} The result value.
  19256. */
  19257. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  19258. // https://github.com/cabbibo/glsl-tri-noise-3d
  19259. /** @module TriNoise3D **/
  19260. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  19261. return x.fract().sub( .5 ).abs();
  19262. } ).setLayout( {
  19263. name: 'tri',
  19264. type: 'float',
  19265. inputs: [
  19266. { name: 'x', type: 'float' }
  19267. ]
  19268. } );
  19269. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  19270. return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) );
  19271. } ).setLayout( {
  19272. name: 'tri3',
  19273. type: 'vec3',
  19274. inputs: [
  19275. { name: 'p', type: 'vec3' }
  19276. ]
  19277. } );
  19278. /**
  19279. * Generates a noise value from the given position, speed and time parameters.
  19280. *
  19281. * @method
  19282. * @param {Node<vec3>} position - The position.
  19283. * @param {Node<float>} speed - The speed.
  19284. * @param {Node<float>} time - The time.
  19285. * @return {Node<float>} The generated noise.
  19286. */
  19287. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  19288. const p = vec3( position ).toVar();
  19289. const z = float( 1.4 ).toVar();
  19290. const rz = float( 0.0 ).toVar();
  19291. const bp = vec3( p ).toVar();
  19292. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  19293. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  19294. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  19295. bp.mulAssign( 1.8 );
  19296. z.mulAssign( 1.5 );
  19297. p.mulAssign( 1.2 );
  19298. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  19299. rz.addAssign( t.div( z ) );
  19300. bp.addAssign( 0.14 );
  19301. } );
  19302. return rz;
  19303. } ).setLayout( {
  19304. name: 'triNoise3D',
  19305. type: 'float',
  19306. inputs: [
  19307. { name: 'position', type: 'vec3' },
  19308. { name: 'speed', type: 'float' },
  19309. { name: 'time', type: 'float' }
  19310. ]
  19311. } );
  19312. /** @module FunctionOverloadingNode **/
  19313. /**
  19314. * This class allows to define multiple overloaded versions
  19315. * of the same function. Depending on the parameters of the function
  19316. * call, the node picks the best-fit overloaded version.
  19317. *
  19318. * @augments Node
  19319. */
  19320. class FunctionOverloadingNode extends Node {
  19321. static get type() {
  19322. return 'FunctionOverloadingNode';
  19323. }
  19324. /**
  19325. * Constructs a new function overloading node.
  19326. *
  19327. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19328. * @param {...Node} parametersNodes - A list of parameter nodes.
  19329. */
  19330. constructor( functionNodes = [], ...parametersNodes ) {
  19331. super();
  19332. /**
  19333. * Array of `Fn` function definitions.
  19334. *
  19335. * @type {Array<Function>}
  19336. */
  19337. this.functionNodes = functionNodes;
  19338. /**
  19339. * A list of parameter nodes.
  19340. *
  19341. * @type {Array<Node>}
  19342. */
  19343. this.parametersNodes = parametersNodes;
  19344. /**
  19345. * The selected overloaded function call.
  19346. *
  19347. * @private
  19348. * @type {ShaderCallNodeInternal}
  19349. */
  19350. this._candidateFnCall = null;
  19351. /**
  19352. * This node is marked as global.
  19353. *
  19354. * @type {Boolean}
  19355. * @default true
  19356. */
  19357. this.global = true;
  19358. }
  19359. /**
  19360. * This method is overwritten since the node type is inferred from
  19361. * the function's return type.
  19362. *
  19363. * @param {NodeBuilder} builder - The current node builder.
  19364. * @return {String} The node type.
  19365. */
  19366. getNodeType() {
  19367. return this.functionNodes[ 0 ].shaderNode.layout.type;
  19368. }
  19369. setup( builder ) {
  19370. const params = this.parametersNodes;
  19371. let candidateFnCall = this._candidateFnCall;
  19372. if ( candidateFnCall === null ) {
  19373. let candidateFn = null;
  19374. let candidateScore = - 1;
  19375. for ( const functionNode of this.functionNodes ) {
  19376. const shaderNode = functionNode.shaderNode;
  19377. const layout = shaderNode.layout;
  19378. if ( layout === null ) {
  19379. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  19380. }
  19381. const inputs = layout.inputs;
  19382. if ( params.length === inputs.length ) {
  19383. let score = 0;
  19384. for ( let i = 0; i < params.length; i ++ ) {
  19385. const param = params[ i ];
  19386. const input = inputs[ i ];
  19387. if ( param.getNodeType( builder ) === input.type ) {
  19388. score ++;
  19389. } else {
  19390. score = 0;
  19391. }
  19392. }
  19393. if ( score > candidateScore ) {
  19394. candidateFn = functionNode;
  19395. candidateScore = score;
  19396. }
  19397. }
  19398. }
  19399. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  19400. }
  19401. return candidateFnCall;
  19402. }
  19403. }
  19404. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  19405. /**
  19406. * TSL function for creating a function overloading node.
  19407. *
  19408. * @function
  19409. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19410. * @returns {FunctionOverloadingNode}
  19411. */
  19412. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  19413. /** @module Timer **/
  19414. /**
  19415. * Represents the elapsed time in seconds.
  19416. *
  19417. * @type {UniformNode<float>}
  19418. */
  19419. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  19420. /**
  19421. * Represents the delta time in seconds.
  19422. *
  19423. * @type {UniformNode<float>}
  19424. */
  19425. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  19426. /**
  19427. * Represents the current frame ID.
  19428. *
  19429. * @type {UniformNode<uint>}
  19430. */
  19431. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  19432. // Deprecated
  19433. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  19434. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  19435. return time.mul( timeScale );
  19436. };
  19437. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  19438. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  19439. return time.mul( timeScale );
  19440. };
  19441. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  19442. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  19443. return deltaTime.mul( timeScale );
  19444. };
  19445. /** @module Oscillators **/
  19446. /**
  19447. * Generates a sine wave oscillation based on a timer.
  19448. *
  19449. * @method
  19450. * @param {Node<float>} t - The timer to generate the oscillation with.
  19451. * @return {Node<float>} The oscillation node.
  19452. */
  19453. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  19454. /**
  19455. * Generates a square wave oscillation based on a timer.
  19456. *
  19457. * @method
  19458. * @param {Node<float>} t - The timer to generate the oscillation with.
  19459. * @return {Node<float>} The oscillation node.
  19460. */
  19461. const oscSquare = ( t = time ) => t.fract().round();
  19462. /**
  19463. * Generates a triangle wave oscillation based on a timer.
  19464. *
  19465. * @method
  19466. * @param {Node<float>} t - The timer to generate the oscillation with.
  19467. * @return {Node<float>} The oscillation node.
  19468. */
  19469. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  19470. /**
  19471. * Generates a sawtooth wave oscillation based on a timer.
  19472. *
  19473. * @method
  19474. * @param {Node<float>} t - The timer to generate the oscillation with.
  19475. * @return {Node<float>} The oscillation node.
  19476. */
  19477. const oscSawtooth = ( t = time ) => t.fract();
  19478. /** @module UVUtils **/
  19479. /**
  19480. * Rotates the given uv coordinates around a center point
  19481. *
  19482. * @method
  19483. * @param {Node<vec2>} uv - The uv coordinates.
  19484. * @param {Node<float>} rotation - The rotation defined in radians.
  19485. * @param {Node<vec2>} center - The center of rotation
  19486. * @return {Node<vec2>} The rotated uv coordinates.
  19487. */
  19488. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  19489. return rotate( uv.sub( center ), rotation ).add( center );
  19490. } );
  19491. /**
  19492. * Applies a spherical warping effect to the given uv coordinates.
  19493. *
  19494. * @method
  19495. * @param {Node<vec2>} uv - The uv coordinates.
  19496. * @param {Node<float>} strength - The strength of the effect.
  19497. * @param {Node<vec2>} center - The center point
  19498. * @return {Node<vec2>} The updated uv coordinates.
  19499. */
  19500. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  19501. const delta = uv.sub( center );
  19502. const delta2 = delta.dot( delta );
  19503. const delta4 = delta2.mul( delta2 );
  19504. const deltaOffset = delta4.mul( strength );
  19505. return uv.add( delta.mul( deltaOffset ) );
  19506. } );
  19507. /** @module SpriteUtils **/
  19508. /**
  19509. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  19510. * oriented always towards the camera.
  19511. *
  19512. * ```js
  19513. * material.vertexNode = billboarding();
  19514. * ```
  19515. *
  19516. * @method
  19517. * @param {Object} config - The configuration object.
  19518. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  19519. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  19520. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  19521. * @return {Node<vec3>} The updated vertex position in clip space.
  19522. */
  19523. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  19524. let worldMatrix;
  19525. if ( position !== null ) {
  19526. worldMatrix = modelWorldMatrix.toVar();
  19527. worldMatrix[ 3 ][ 0 ] = position.x;
  19528. worldMatrix[ 3 ][ 1 ] = position.y;
  19529. worldMatrix[ 3 ][ 2 ] = position.z;
  19530. } else {
  19531. worldMatrix = modelWorldMatrix;
  19532. }
  19533. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  19534. if ( defined( horizontal ) ) {
  19535. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  19536. modelViewMatrix[ 0 ][ 1 ] = 0;
  19537. modelViewMatrix[ 0 ][ 2 ] = 0;
  19538. }
  19539. if ( defined( vertical ) ) {
  19540. modelViewMatrix[ 1 ][ 0 ] = 0;
  19541. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  19542. modelViewMatrix[ 1 ][ 2 ] = 0;
  19543. }
  19544. modelViewMatrix[ 2 ][ 0 ] = 0;
  19545. modelViewMatrix[ 2 ][ 1 ] = 0;
  19546. modelViewMatrix[ 2 ][ 2 ] = 1;
  19547. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  19548. } );
  19549. /** @module ViewportUtils **/
  19550. /**
  19551. * A special version of a screen uv function that involves a depth comparison
  19552. * when computing the final uvs. The function mitigates visual errors when
  19553. * using viewport texture nodes for refraction purposes. Without this function
  19554. * objects in front of a refractive surface might appear on the refractive surface
  19555. * which is incorrect.
  19556. *
  19557. * @method
  19558. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  19559. * @return {Node<vec2>} The update uv coordinates.
  19560. */
  19561. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  19562. const depth = linearDepth();
  19563. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  19564. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  19565. return finalUV;
  19566. } );
  19567. /** @module SpriteSheetUVNode **/
  19568. /**
  19569. * Can be used to compute texture coordinates for animated sprite sheets.
  19570. *
  19571. * ```js
  19572. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  19573. *
  19574. * material.colorNode = texture( spriteSheet, uvNode );
  19575. * ```
  19576. *
  19577. * @augments Node
  19578. */
  19579. class SpriteSheetUVNode extends Node {
  19580. static get type() {
  19581. return 'SpriteSheetUVNode';
  19582. }
  19583. /**
  19584. * Constructs a new sprite sheet uv node.
  19585. *
  19586. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19587. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19588. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19589. */
  19590. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  19591. super( 'vec2' );
  19592. /**
  19593. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19594. *
  19595. * @type {Node<vec2>}
  19596. */
  19597. this.countNode = countNode;
  19598. /**
  19599. * The uv node.
  19600. *
  19601. * @type {Node<vec2>}
  19602. */
  19603. this.uvNode = uvNode;
  19604. /**
  19605. * The node that defines the current frame/sprite.
  19606. *
  19607. * @type {Node<float>}
  19608. */
  19609. this.frameNode = frameNode;
  19610. }
  19611. setup() {
  19612. const { frameNode, uvNode, countNode } = this;
  19613. const { width, height } = countNode;
  19614. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  19615. const column = frameNum.mod( width );
  19616. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  19617. const scale = countNode.reciprocal();
  19618. const uvFrameOffset = vec2( column, row );
  19619. return uvNode.add( uvFrameOffset ).mul( scale );
  19620. }
  19621. }
  19622. /**
  19623. * TSL function for creating a sprite sheet uv node.
  19624. *
  19625. * @function
  19626. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19627. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19628. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19629. * @returns {SpriteSheetUVNode}
  19630. */
  19631. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  19632. /** @module TriplanarTexturesNode **/
  19633. /**
  19634. * Can be used for triplanar texture mapping.
  19635. *
  19636. * ```js
  19637. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  19638. * ```
  19639. *
  19640. * @augments Node
  19641. */
  19642. class TriplanarTexturesNode extends Node {
  19643. static get type() {
  19644. return 'TriplanarTexturesNode';
  19645. }
  19646. /**
  19647. * Constructs a new triplanar textures node.
  19648. *
  19649. * @param {Node} textureXNode - First texture node.
  19650. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19651. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19652. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19653. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19654. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19655. */
  19656. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  19657. super( 'vec4' );
  19658. /**
  19659. * First texture node.
  19660. *
  19661. * @type {Node}
  19662. */
  19663. this.textureXNode = textureXNode;
  19664. /**
  19665. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19666. *
  19667. * @type {Node}
  19668. * @default null
  19669. */
  19670. this.textureYNode = textureYNode;
  19671. /**
  19672. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19673. *
  19674. * @type {Node}
  19675. * @default null
  19676. */
  19677. this.textureZNode = textureZNode;
  19678. /**
  19679. * The scale node.
  19680. *
  19681. * @type {Node<float>}
  19682. * @default float(1)
  19683. */
  19684. this.scaleNode = scaleNode;
  19685. /**
  19686. * Vertex positions in local space.
  19687. *
  19688. * @type {Node<vec3>}
  19689. * @default positionLocal
  19690. */
  19691. this.positionNode = positionNode;
  19692. /**
  19693. * Normals in local space.
  19694. *
  19695. * @type {Node<vec3>}
  19696. * @default normalLocal
  19697. */
  19698. this.normalNode = normalNode;
  19699. }
  19700. setup() {
  19701. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  19702. // Ref: https://github.com/keijiro/StandardTriplanar
  19703. // Blending factor of triplanar mapping
  19704. let bf = normalNode.abs().normalize();
  19705. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  19706. // Triplanar mapping
  19707. const tx = positionNode.yz.mul( scaleNode );
  19708. const ty = positionNode.zx.mul( scaleNode );
  19709. const tz = positionNode.xy.mul( scaleNode );
  19710. // Base color
  19711. const textureX = textureXNode.value;
  19712. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  19713. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  19714. const cx = texture( textureX, tx ).mul( bf.x );
  19715. const cy = texture( textureY, ty ).mul( bf.y );
  19716. const cz = texture( textureZ, tz ).mul( bf.z );
  19717. return add( cx, cy, cz );
  19718. }
  19719. }
  19720. /**
  19721. * TSL function for creating a triplanar textures node.
  19722. *
  19723. * @function
  19724. * @param {Node} textureXNode - First texture node.
  19725. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19726. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19727. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19728. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19729. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19730. * @returns {TriplanarTexturesNode}
  19731. */
  19732. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  19733. /**
  19734. * TSL function for creating a triplanar textures node.
  19735. *
  19736. * @function
  19737. * @param {Node} textureXNode - First texture node.
  19738. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19739. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19740. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19741. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19742. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19743. * @returns {TriplanarTexturesNode}
  19744. */
  19745. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  19746. /** @module ReflectorNode **/
  19747. const _reflectorPlane = new Plane();
  19748. const _normal = new Vector3();
  19749. const _reflectorWorldPosition = new Vector3();
  19750. const _cameraWorldPosition = new Vector3();
  19751. const _rotationMatrix = new Matrix4();
  19752. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  19753. const clipPlane = new Vector4();
  19754. const _view = new Vector3();
  19755. const _target = new Vector3();
  19756. const _q = new Vector4();
  19757. const _size$2 = new Vector2();
  19758. const _defaultRT = new RenderTarget();
  19759. const _defaultUV = screenUV.flipX();
  19760. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  19761. let _inReflector = false;
  19762. /**
  19763. * This node can be used to implement mirror-like flat reflective surfaces.
  19764. *
  19765. * ```js
  19766. * const groundReflector = reflector();
  19767. * material.colorNode = groundReflector;
  19768. *
  19769. * const plane = new Mesh( geometry, material );
  19770. * plane.add( groundReflector.target );
  19771. * ```
  19772. *
  19773. * @augments module:TextureNode~TextureNode
  19774. */
  19775. class ReflectorNode extends TextureNode {
  19776. static get type() {
  19777. return 'ReflectorNode';
  19778. }
  19779. /**
  19780. * Constructs a new reflector node.
  19781. *
  19782. * @param {Object} [parameters={}] - An object holding configuration parameters.
  19783. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  19784. * @param {Number} [parameters.resolution=1] - The resolution scale.
  19785. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  19786. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  19787. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  19788. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  19789. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  19790. */
  19791. constructor( parameters = {} ) {
  19792. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  19793. /**
  19794. * A reference to the internal reflector base node which holds the actual implementation.
  19795. *
  19796. * @private
  19797. * @type {ReflectorBaseNode?}
  19798. * @default null
  19799. */
  19800. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  19801. /**
  19802. * A reference to the internal depth node.
  19803. *
  19804. * @private
  19805. * @type {Node?}
  19806. * @default null
  19807. */
  19808. this._depthNode = null;
  19809. this.setUpdateMatrix( false );
  19810. }
  19811. /**
  19812. * A reference to the internal reflector node.
  19813. *
  19814. * @type {ReflectorBaseNode}
  19815. */
  19816. get reflector() {
  19817. return this._reflectorBaseNode;
  19818. }
  19819. /**
  19820. * A reference to 3D object the reflector is linked to.
  19821. *
  19822. * @type {Object3D}
  19823. */
  19824. get target() {
  19825. return this._reflectorBaseNode.target;
  19826. }
  19827. /**
  19828. * Returns a node representing the mirror's depth. That can be used
  19829. * to implement more advanced reflection effects like distance attenuation.
  19830. *
  19831. * @return {Node} The depth node.
  19832. */
  19833. getDepthNode() {
  19834. if ( this._depthNode === null ) {
  19835. if ( this._reflectorBaseNode.depth !== true ) {
  19836. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  19837. }
  19838. this._depthNode = nodeObject( new ReflectorNode( {
  19839. defaultTexture: _defaultRT.depthTexture,
  19840. reflector: this._reflectorBaseNode
  19841. } ) );
  19842. }
  19843. return this._depthNode;
  19844. }
  19845. setup( builder ) {
  19846. // ignore if used in post-processing
  19847. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  19848. return super.setup( builder );
  19849. }
  19850. clone() {
  19851. const texture = new this.constructor( this.reflectorNode );
  19852. texture._reflectorBaseNode = this._reflectorBaseNode;
  19853. return texture;
  19854. }
  19855. }
  19856. /**
  19857. * Holds the actual implementation of the reflector.
  19858. *
  19859. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  19860. * in `ReflectorNode`, see #29619.
  19861. *
  19862. * @private
  19863. * @augments Node
  19864. */
  19865. class ReflectorBaseNode extends Node {
  19866. static get type() {
  19867. return 'ReflectorBaseNode';
  19868. }
  19869. /**
  19870. * Constructs a new reflector base node.
  19871. *
  19872. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  19873. * @param {Object} [parameters={}] - An object holding configuration parameters.
  19874. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  19875. * @param {Number} [parameters.resolution=1] - The resolution scale.
  19876. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  19877. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  19878. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  19879. */
  19880. constructor( textureNode, parameters = {} ) {
  19881. super();
  19882. const {
  19883. target = new Object3D(),
  19884. resolution = 1,
  19885. generateMipmaps = false,
  19886. bounces = true,
  19887. depth = false
  19888. } = parameters;
  19889. /**
  19890. * Represents the rendered reflections as a texture node.
  19891. *
  19892. * @type {TextureNode}
  19893. */
  19894. this.textureNode = textureNode;
  19895. /**
  19896. * The 3D object the reflector is linked to.
  19897. *
  19898. * @type {Object3D}
  19899. * @default {new Object3D()}
  19900. */
  19901. this.target = target;
  19902. /**
  19903. * The resolution scale.
  19904. *
  19905. * @type {Number}
  19906. * @default {1}
  19907. */
  19908. this.resolution = resolution;
  19909. /**
  19910. * Whether mipmaps should be generated or not.
  19911. *
  19912. * @type {Boolean}
  19913. * @default {false}
  19914. */
  19915. this.generateMipmaps = generateMipmaps;
  19916. /**
  19917. * Whether reflectors can render other reflector nodes or not.
  19918. *
  19919. * @type {Boolean}
  19920. * @default {true}
  19921. */
  19922. this.bounces = bounces;
  19923. /**
  19924. * Whether depth data should be generated or not.
  19925. *
  19926. * @type {Boolean}
  19927. * @default {false}
  19928. */
  19929. this.depth = depth;
  19930. /**
  19931. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  19932. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  19933. *
  19934. * @type {String}
  19935. * @default 'render'
  19936. */
  19937. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  19938. /**
  19939. * Weak map for managing virtual cameras.
  19940. *
  19941. * @type {WeakMap<Camera, Camera>}
  19942. */
  19943. this.virtualCameras = new WeakMap();
  19944. /**
  19945. * Weak map for managing render targets.
  19946. *
  19947. * @type {WeakMap<Camera, RenderTarget>}
  19948. */
  19949. this.renderTargets = new WeakMap();
  19950. }
  19951. /**
  19952. * Updates the resolution of the internal render target.
  19953. *
  19954. * @private
  19955. * @param {RenderTarget} renderTarget - The render target to resize.
  19956. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  19957. */
  19958. _updateResolution( renderTarget, renderer ) {
  19959. const resolution = this.resolution;
  19960. renderer.getDrawingBufferSize( _size$2 );
  19961. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  19962. }
  19963. setup( builder ) {
  19964. this._updateResolution( _defaultRT, builder.renderer );
  19965. return super.setup( builder );
  19966. }
  19967. /**
  19968. * Returns a virtual camera for the given camera. The virtual camera is used to
  19969. * render the scene from the reflector's view so correct reflections can be produced.
  19970. *
  19971. * @param {Camera} camera - The scene's camera.
  19972. * @return {Camera} The corresponding virtual camera.
  19973. */
  19974. getVirtualCamera( camera ) {
  19975. let virtualCamera = this.virtualCameras.get( camera );
  19976. if ( virtualCamera === undefined ) {
  19977. virtualCamera = camera.clone();
  19978. this.virtualCameras.set( camera, virtualCamera );
  19979. }
  19980. return virtualCamera;
  19981. }
  19982. /**
  19983. * Returns a render target for the given camera. The reflections are rendered
  19984. * into this render target.
  19985. *
  19986. * @param {Camera} camera - The scene's camera.
  19987. * @return {RenderTarget} The render target.
  19988. */
  19989. getRenderTarget( camera ) {
  19990. let renderTarget = this.renderTargets.get( camera );
  19991. if ( renderTarget === undefined ) {
  19992. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  19993. if ( this.generateMipmaps === true ) {
  19994. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  19995. renderTarget.texture.generateMipmaps = true;
  19996. }
  19997. if ( this.depth === true ) {
  19998. renderTarget.depthTexture = new DepthTexture();
  19999. }
  20000. this.renderTargets.set( camera, renderTarget );
  20001. }
  20002. return renderTarget;
  20003. }
  20004. updateBefore( frame ) {
  20005. if ( this.bounces === false && _inReflector ) return false;
  20006. _inReflector = true;
  20007. const { scene, camera, renderer, material } = frame;
  20008. const { target } = this;
  20009. const virtualCamera = this.getVirtualCamera( camera );
  20010. const renderTarget = this.getRenderTarget( virtualCamera );
  20011. renderer.getDrawingBufferSize( _size$2 );
  20012. this._updateResolution( renderTarget, renderer );
  20013. //
  20014. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  20015. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  20016. _rotationMatrix.extractRotation( target.matrixWorld );
  20017. _normal.set( 0, 0, 1 );
  20018. _normal.applyMatrix4( _rotationMatrix );
  20019. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  20020. // Avoid rendering when reflector is facing away
  20021. if ( _view.dot( _normal ) > 0 ) return;
  20022. _view.reflect( _normal ).negate();
  20023. _view.add( _reflectorWorldPosition );
  20024. _rotationMatrix.extractRotation( camera.matrixWorld );
  20025. _lookAtPosition.set( 0, 0, - 1 );
  20026. _lookAtPosition.applyMatrix4( _rotationMatrix );
  20027. _lookAtPosition.add( _cameraWorldPosition );
  20028. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  20029. _target.reflect( _normal ).negate();
  20030. _target.add( _reflectorWorldPosition );
  20031. //
  20032. virtualCamera.coordinateSystem = camera.coordinateSystem;
  20033. virtualCamera.position.copy( _view );
  20034. virtualCamera.up.set( 0, 1, 0 );
  20035. virtualCamera.up.applyMatrix4( _rotationMatrix );
  20036. virtualCamera.up.reflect( _normal );
  20037. virtualCamera.lookAt( _target );
  20038. virtualCamera.near = camera.near;
  20039. virtualCamera.far = camera.far;
  20040. virtualCamera.updateMatrixWorld();
  20041. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  20042. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  20043. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  20044. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  20045. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  20046. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  20047. const projectionMatrix = virtualCamera.projectionMatrix;
  20048. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  20049. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  20050. _q.z = - 1.0;
  20051. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  20052. // Calculate the scaled plane vector
  20053. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  20054. const clipBias = 0;
  20055. // Replacing the third row of the projection matrix
  20056. projectionMatrix.elements[ 2 ] = clipPlane.x;
  20057. projectionMatrix.elements[ 6 ] = clipPlane.y;
  20058. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  20059. projectionMatrix.elements[ 14 ] = clipPlane.w;
  20060. //
  20061. this.textureNode.value = renderTarget.texture;
  20062. if ( this.depth === true ) {
  20063. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  20064. }
  20065. material.visible = false;
  20066. const currentRenderTarget = renderer.getRenderTarget();
  20067. const currentMRT = renderer.getMRT();
  20068. const currentAutoClear = renderer.autoClear;
  20069. renderer.setMRT( null );
  20070. renderer.setRenderTarget( renderTarget );
  20071. renderer.autoClear = true;
  20072. renderer.render( scene, virtualCamera );
  20073. renderer.setMRT( currentMRT );
  20074. renderer.setRenderTarget( currentRenderTarget );
  20075. renderer.autoClear = currentAutoClear;
  20076. material.visible = true;
  20077. _inReflector = false;
  20078. }
  20079. }
  20080. /**
  20081. * TSL function for creating a reflector node.
  20082. *
  20083. * @function
  20084. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20085. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20086. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20087. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20088. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20089. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20090. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20091. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20092. * @returns {ReflectorNode}
  20093. */
  20094. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  20095. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  20096. /**
  20097. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  20098. *
  20099. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  20100. *
  20101. * @private
  20102. * @augments BufferGeometry
  20103. */
  20104. class QuadGeometry extends BufferGeometry {
  20105. /**
  20106. * Constructs a new quad geometry.
  20107. *
  20108. * @param {Boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  20109. */
  20110. constructor( flipY = false ) {
  20111. super();
  20112. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  20113. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  20114. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  20115. }
  20116. }
  20117. const _geometry = /*@__PURE__*/ new QuadGeometry();
  20118. /**
  20119. * This module is a helper for passes which need to render a full
  20120. * screen effect which is quite common in context of post processing.
  20121. *
  20122. * The intended usage is to reuse a single quad mesh for rendering
  20123. * subsequent passes by just reassigning the `material` reference.
  20124. *
  20125. * @augments BufferGeometry
  20126. */
  20127. class QuadMesh extends Mesh {
  20128. /**
  20129. * Constructs a new quad mesh.
  20130. *
  20131. * @param {Material?} [material=null] - The material to render the quad mesh with.
  20132. */
  20133. constructor( material = null ) {
  20134. super( _geometry, material );
  20135. /**
  20136. * The camera to render the quad mesh with.
  20137. *
  20138. * @type {OrthographicCamera}
  20139. * @readonly
  20140. */
  20141. this.camera = _camera;
  20142. /**
  20143. * This flag can be used for type testing.
  20144. *
  20145. * @type {Boolean}
  20146. * @readonly
  20147. * @default true
  20148. */
  20149. this.isQuadMesh = true;
  20150. }
  20151. /**
  20152. * Async version of `render()`.
  20153. *
  20154. * @async
  20155. * @param {Renderer} renderer - The renderer.
  20156. * @return {Promise} A Promise that resolves when the render has been finished.
  20157. */
  20158. async renderAsync( renderer ) {
  20159. return renderer.renderAsync( this, _camera );
  20160. }
  20161. /**
  20162. * Renders the quad mesh
  20163. *
  20164. * @param {Renderer} renderer - The renderer.
  20165. */
  20166. render( renderer ) {
  20167. renderer.render( this, _camera );
  20168. }
  20169. }
  20170. /** @module RTTNode **/
  20171. const _size$1 = /*@__PURE__*/ new Vector2();
  20172. /**
  20173. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  20174. * This module is especially relevant in context of post processing where certain nodes require
  20175. * texture input for their effects. With the helper function `convertToTexture()` which is based
  20176. * on this module, the node system can automatically ensure texture input if required.
  20177. *
  20178. * @augments module:TextureNode~TextureNode
  20179. */
  20180. class RTTNode extends TextureNode {
  20181. static get type() {
  20182. return 'RTTNode';
  20183. }
  20184. /**
  20185. * Constructs a new RTT node.
  20186. *
  20187. * @param {Node} node - The node to render a texture with.
  20188. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20189. * @param {Number?} [height=null] - The height of the internal render target.
  20190. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20191. */
  20192. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  20193. const renderTarget = new RenderTarget( width, height, options );
  20194. super( renderTarget.texture, uv() );
  20195. /**
  20196. * The node to render a texture with.
  20197. *
  20198. * @type {Node}
  20199. */
  20200. this.node = node;
  20201. /**
  20202. * The width of the internal render target.
  20203. * If not width is applied, the render target is automatically resized.
  20204. *
  20205. * @type {Number?}
  20206. * @default null
  20207. */
  20208. this.width = width;
  20209. /**
  20210. * The height of the internal render target.
  20211. *
  20212. * @type {Number?}
  20213. * @default null
  20214. */
  20215. this.height = height;
  20216. /**
  20217. * The pixel ratio
  20218. *
  20219. * @type {Number}
  20220. * @default 1
  20221. */
  20222. this.pixelRatio = 1;
  20223. /**
  20224. * The render target
  20225. *
  20226. * @type {RenderTarget}
  20227. */
  20228. this.renderTarget = renderTarget;
  20229. /**
  20230. * Whether the texture requires an update or not.
  20231. *
  20232. * @type {Boolean}
  20233. * @default true
  20234. */
  20235. this.textureNeedsUpdate = true;
  20236. /**
  20237. * Whether the texture should automatically be updated or not.
  20238. *
  20239. * @type {Boolean}
  20240. * @default true
  20241. */
  20242. this.autoUpdate = true;
  20243. /**
  20244. * The node which is used with the quad mesh for RTT.
  20245. *
  20246. * @private
  20247. * @type {Node}
  20248. * @default null
  20249. */
  20250. this._rttNode = null;
  20251. /**
  20252. * The internal quad mesh for RTT.
  20253. *
  20254. * @private
  20255. * @type {QuadMesh}
  20256. */
  20257. this._quadMesh = new QuadMesh( new NodeMaterial() );
  20258. /**
  20259. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  20260. * the texture once per render in its {@link RTTNode#updateBefore} method.
  20261. *
  20262. * @type {String}
  20263. * @default 'render'
  20264. */
  20265. this.updateBeforeType = NodeUpdateType.RENDER;
  20266. }
  20267. /**
  20268. * Whether the internal render target should automatically be resized or not.
  20269. *
  20270. * @type {Boolean}
  20271. * @readonly
  20272. * @default true
  20273. */
  20274. get autoSize() {
  20275. return this.width === null;
  20276. }
  20277. setup( builder ) {
  20278. this._rttNode = this.node.context( builder.getSharedContext() );
  20279. this._quadMesh.material.name = 'RTT';
  20280. this._quadMesh.material.needsUpdate = true;
  20281. return super.setup( builder );
  20282. }
  20283. /**
  20284. * Sets the size of the internal render target
  20285. *
  20286. * @param {Number} width - The width to set.
  20287. * @param {Number} height - The width to set.
  20288. */
  20289. setSize( width, height ) {
  20290. this.width = width;
  20291. this.height = height;
  20292. const effectiveWidth = width * this.pixelRatio;
  20293. const effectiveHeight = height * this.pixelRatio;
  20294. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  20295. this.textureNeedsUpdate = true;
  20296. }
  20297. /**
  20298. * Sets the pixel ratio. This will also resize the render target.
  20299. *
  20300. * @param {Number} pixelRatio - The pixel ratio to set.
  20301. */
  20302. setPixelRatio( pixelRatio ) {
  20303. this.pixelRatio = pixelRatio;
  20304. this.setSize( this.width, this.height );
  20305. }
  20306. updateBefore( { renderer } ) {
  20307. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  20308. this.textureNeedsUpdate = false;
  20309. //
  20310. if ( this.autoSize === true ) {
  20311. this.pixelRatio = renderer.getPixelRatio();
  20312. const size = renderer.getSize( _size$1 );
  20313. this.setSize( size.width, size.height );
  20314. }
  20315. //
  20316. this._quadMesh.material.fragmentNode = this._rttNode;
  20317. //
  20318. const currentRenderTarget = renderer.getRenderTarget();
  20319. renderer.setRenderTarget( this.renderTarget );
  20320. this._quadMesh.render( renderer );
  20321. renderer.setRenderTarget( currentRenderTarget );
  20322. }
  20323. clone() {
  20324. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  20325. newNode.sampler = this.sampler;
  20326. newNode.referenceNode = this;
  20327. return newNode;
  20328. }
  20329. }
  20330. /**
  20331. * TSL function for creating a RTT node.
  20332. *
  20333. * @function
  20334. * @param {Node} node - The node to render a texture with.
  20335. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20336. * @param {Number?} [height=null] - The height of the internal render target.
  20337. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20338. * @returns {RTTNode}
  20339. */
  20340. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  20341. /**
  20342. * TSL function for converting nodes to textures nodes.
  20343. *
  20344. * @function
  20345. * @param {Node} node - The node to render a texture with.
  20346. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20347. * @param {Number?} [height=null] - The height of the internal render target.
  20348. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20349. * @returns {RTTNode}
  20350. */
  20351. const convertToTexture = ( node, ...params ) => {
  20352. if ( node.isTextureNode ) return node;
  20353. if ( node.isPassNode ) return node.getTextureNode();
  20354. return rtt( node, ...params );
  20355. };
  20356. /** @module PostProcessingUtils **/
  20357. /**
  20358. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  20359. * depth value and the camera's inverse projection matrix.
  20360. *
  20361. * @method
  20362. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  20363. * @param {Node<float>} depth - The fragment's depth value.
  20364. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20365. * @return {Node<vec3>} The fragments position in view space.
  20366. */
  20367. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  20368. let clipSpacePosition;
  20369. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  20370. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  20371. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  20372. } else {
  20373. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  20374. }
  20375. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  20376. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  20377. } );
  20378. /**
  20379. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  20380. * and the camera's projection matrix
  20381. *
  20382. * @method
  20383. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  20384. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  20385. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  20386. */
  20387. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  20388. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  20389. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  20390. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  20391. } );
  20392. /**
  20393. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  20394. * target is available or if flat surface normals are required.
  20395. *
  20396. * @method
  20397. * @param {Node<vec2>} uv - The texture coordinate.
  20398. * @param {DepthTexture} depthTexture - The depth texture.
  20399. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20400. * @return {Node<vec3>} The computed normal vector.
  20401. */
  20402. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  20403. const size = textureSize( textureLoad( depthTexture ) );
  20404. const p = ivec2( uv.mul( size ) ).toVar();
  20405. const c0 = textureLoad( depthTexture, p ).toVar();
  20406. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  20407. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  20408. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  20409. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  20410. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  20411. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  20412. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  20413. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  20414. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  20415. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  20416. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  20417. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  20418. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  20419. const dpdx = dl.lessThan( dr ).select( ce.sub( getViewPosition( uv.sub( vec2( float( 1 ).div( size.x ), 0 ) ), l1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.add( vec2( float( 1 ).div( size.x ), 0 ) ), r1, projectionMatrixInverse ) ) );
  20420. const dpdy = db.lessThan( dt ).select( ce.sub( getViewPosition( uv.add( vec2( 0, float( 1 ).div( size.y ) ) ), b1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.sub( vec2( 0, float( 1 ).div( size.y ) ) ), t1, projectionMatrixInverse ) ) );
  20421. return normalize( cross( dpdx, dpdy ) );
  20422. } );
  20423. /**
  20424. * This special type of instanced buffer attribute is intended for compute shaders.
  20425. * In earlier three.js versions it was only possible to update attribute data
  20426. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20427. * new material system and renderer it is now possible to use compute shaders
  20428. * to compute the data for an attribute more efficiently on the GPU.
  20429. *
  20430. * The idea is to create an instance of this class and provide it as an input
  20431. * to {@link module:StorageBufferNode}.
  20432. *
  20433. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20434. *
  20435. * @augments InstancedBufferAttribute
  20436. */
  20437. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  20438. /**
  20439. * Constructs a new storage instanced buffer attribute.
  20440. *
  20441. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20442. * The subsequent parameters are then obsolete.
  20443. * @param {Number} itemSize - The item size.
  20444. * @param {TypedArray.contructor} [typeClass=Float32Array] - A typed array constructor.
  20445. */
  20446. constructor( count, itemSize, typeClass = Float32Array ) {
  20447. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20448. super( array, itemSize );
  20449. /**
  20450. * This flag can be used for type testing.
  20451. *
  20452. * @type {Boolean}
  20453. * @readonly
  20454. * @default true
  20455. */
  20456. this.isStorageInstancedBufferAttribute = true;
  20457. }
  20458. }
  20459. /**
  20460. * This special type of buffer attribute is intended for compute shaders.
  20461. * In earlier three.js versions it was only possible to update attribute data
  20462. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20463. * new material system and renderer it is now possible to use compute shaders
  20464. * to compute the data for an attribute more efficiently on the GPU.
  20465. *
  20466. * The idea is to create an instance of this class and provide it as an input
  20467. * to {@link module:StorageBufferNode}.
  20468. *
  20469. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20470. *
  20471. * @augments BufferAttribute
  20472. */
  20473. class StorageBufferAttribute extends BufferAttribute {
  20474. /**
  20475. * Constructs a new storage buffer attribute.
  20476. *
  20477. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20478. * The subsequent parameters are then obsolete.
  20479. * @param {Number} itemSize - The item size.
  20480. * @param {TypedArray.contructor} [typeClass=Float32Array] - A typed array constructor.
  20481. */
  20482. constructor( count, itemSize, typeClass = Float32Array ) {
  20483. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20484. super( array, itemSize );
  20485. /**
  20486. * This flag can be used for type testing.
  20487. *
  20488. * @type {Boolean}
  20489. * @readonly
  20490. * @default true
  20491. */
  20492. this.isStorageBufferAttribute = true;
  20493. }
  20494. }
  20495. /** @module StorageArrayElementNode **/
  20496. /**
  20497. * This class enables element access on instances of {@link StorageBufferNode}.
  20498. * In most cases, it is indirectly used when accessing elements with the
  20499. * {@link StorageBufferNode#element} method.
  20500. *
  20501. * ```js
  20502. * const position = positionStorage.element( instanceIndex );
  20503. * ```
  20504. *
  20505. * @augments ArrayElementNode
  20506. */
  20507. class StorageArrayElementNode extends ArrayElementNode {
  20508. static get type() {
  20509. return 'StorageArrayElementNode';
  20510. }
  20511. /**
  20512. * Constructs storage buffer element node.
  20513. *
  20514. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20515. * @param {Node} indexNode - The index node that defines the element access.
  20516. */
  20517. constructor( storageBufferNode, indexNode ) {
  20518. super( storageBufferNode, indexNode );
  20519. /**
  20520. * This flag can be used for type testing.
  20521. *
  20522. * @type {Boolean}
  20523. * @readonly
  20524. * @default true
  20525. */
  20526. this.isStorageArrayElementNode = true;
  20527. }
  20528. /**
  20529. * The storage buffer node.
  20530. *
  20531. * @param {Node} value
  20532. * @type {StorageBufferNode}
  20533. */
  20534. set storageBufferNode( value ) {
  20535. this.node = value;
  20536. }
  20537. get storageBufferNode() {
  20538. return this.node;
  20539. }
  20540. setup( builder ) {
  20541. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20542. if ( this.node.isPBO === true ) {
  20543. builder.setupPBO( this.node );
  20544. }
  20545. }
  20546. return super.setup( builder );
  20547. }
  20548. generate( builder, output ) {
  20549. let snippet;
  20550. const isAssignContext = builder.context.assign;
  20551. //
  20552. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20553. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  20554. snippet = builder.generatePBO( this );
  20555. } else {
  20556. snippet = this.node.build( builder );
  20557. }
  20558. } else {
  20559. snippet = super.generate( builder );
  20560. }
  20561. if ( isAssignContext !== true ) {
  20562. const type = this.getNodeType( builder );
  20563. snippet = builder.format( snippet, type, output );
  20564. }
  20565. return snippet;
  20566. }
  20567. }
  20568. /**
  20569. * TSL function for creating a storage element node.
  20570. *
  20571. * @function
  20572. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20573. * @param {Node} indexNode - The index node that defines the element access.
  20574. * @returns {StorageArrayElementNode}
  20575. */
  20576. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  20577. /** @module StorageBufferNode **/
  20578. /**
  20579. * This node is used in context of compute shaders and allows to define a
  20580. * storage buffer for data. A typical workflow is to create instances of
  20581. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  20582. * setup up a compute shader that writes into the buffers and then convert
  20583. * the storage buffers to attribute nodes for rendering.
  20584. *
  20585. * ```js
  20586. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  20587. *
  20588. * const computeInit = Fn( () => { // the compute shader
  20589. *
  20590. * const position = positionBuffer.element( instanceIndex );
  20591. *
  20592. * // compute position data
  20593. *
  20594. * position.x = 1;
  20595. * position.y = 1;
  20596. * position.z = 1;
  20597. *
  20598. * } )().compute( particleCount );
  20599. *
  20600. * const particleMaterial = new THREE.SpriteNodeMaterial();
  20601. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20602. *
  20603. * renderer.computeAsync( computeInit );
  20604. *
  20605. * ```
  20606. *
  20607. * @augments BufferNode
  20608. */
  20609. class StorageBufferNode extends BufferNode {
  20610. static get type() {
  20611. return 'StorageBufferNode';
  20612. }
  20613. /**
  20614. * Constructs a new storage buffer node.
  20615. *
  20616. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20617. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  20618. * @param {Number} [bufferCount=0] - The buffer count.
  20619. */
  20620. constructor( value, bufferType = null, bufferCount = 0 ) {
  20621. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  20622. bufferType = getTypeFromLength( value.itemSize );
  20623. bufferCount = value.count;
  20624. }
  20625. super( value, bufferType, bufferCount );
  20626. /**
  20627. * This flag can be used for type testing.
  20628. *
  20629. * @type {Boolean}
  20630. * @readonly
  20631. * @default true
  20632. */
  20633. this.isStorageBufferNode = true;
  20634. /**
  20635. * The access type of the texture node.
  20636. *
  20637. * @type {String}
  20638. * @default 'readWrite'
  20639. */
  20640. this.access = NodeAccess.READ_WRITE;
  20641. /**
  20642. * Whether the node is atomic or not.
  20643. *
  20644. * @type {Boolean}
  20645. * @default false
  20646. */
  20647. this.isAtomic = false;
  20648. /**
  20649. * Whether the node represents a PBO or not.
  20650. * Only relevant for WebGL.
  20651. *
  20652. * @type {Boolean}
  20653. * @default false
  20654. */
  20655. this.isPBO = false;
  20656. /**
  20657. * A reference to the internal buffer attribute node.
  20658. *
  20659. * @type {BufferAttributeNode?}
  20660. * @default null
  20661. */
  20662. this._attribute = null;
  20663. /**
  20664. * A reference to the internal varying node.
  20665. *
  20666. * @type {VaryingNode?}
  20667. * @default null
  20668. */
  20669. this._varying = null;
  20670. /**
  20671. * `StorageBufferNode` sets this property to `true` by default.
  20672. *
  20673. * @type {Boolean}
  20674. * @default true
  20675. */
  20676. this.global = true;
  20677. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  20678. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  20679. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  20680. else value.isStorageBufferAttribute = true;
  20681. }
  20682. }
  20683. /**
  20684. * This method is overwritten since the buffer data might be shared
  20685. * and thus the hash should be shared as well.
  20686. *
  20687. * @param {NodeBuilder} builder - The current node builder.
  20688. * @return {String} The hash.
  20689. */
  20690. getHash( builder ) {
  20691. if ( this.bufferCount === 0 ) {
  20692. let bufferData = builder.globalCache.getData( this.value );
  20693. if ( bufferData === undefined ) {
  20694. bufferData = {
  20695. node: this
  20696. };
  20697. builder.globalCache.setData( this.value, bufferData );
  20698. }
  20699. return bufferData.node.uuid;
  20700. }
  20701. return this.uuid;
  20702. }
  20703. /**
  20704. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  20705. *
  20706. * @param {NodeBuilder} builder - The current node builder.
  20707. * @return {String} The input type.
  20708. */
  20709. getInputType( /*builder*/ ) {
  20710. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  20711. }
  20712. /**
  20713. * Enables element access with the given index node.
  20714. *
  20715. * @param {IndexNode} indexNode - The index node.
  20716. * @return {StorageArrayElementNode} A node representing the element access.
  20717. */
  20718. element( indexNode ) {
  20719. return storageElement( this, indexNode );
  20720. }
  20721. /**
  20722. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  20723. *
  20724. * @param {Boolean} value - The value so set.
  20725. * @return {StorageBufferNode} A reference to this node.
  20726. */
  20727. setPBO( value ) {
  20728. this.isPBO = value;
  20729. return this;
  20730. }
  20731. /**
  20732. * Returns the `isPBO` value.
  20733. *
  20734. * @return {Boolean} Whether the node represents a PBO or not.
  20735. */
  20736. getPBO() {
  20737. return this.isPBO;
  20738. }
  20739. /**
  20740. * Defines the node access.
  20741. *
  20742. * @param {String} value - The node access.
  20743. * @return {StorageBufferNode} A reference to this node.
  20744. */
  20745. setAccess( value ) {
  20746. this.access = value;
  20747. return this;
  20748. }
  20749. /**
  20750. * Convenience method for configuring a read-only node access.
  20751. *
  20752. * @return {StorageBufferNode} A reference to this node.
  20753. */
  20754. toReadOnly() {
  20755. return this.setAccess( NodeAccess.READ_ONLY );
  20756. }
  20757. /**
  20758. * Defines whether the node is atomic or not.
  20759. *
  20760. * @param {Boolean} value - The atomic flag.
  20761. * @return {StorageBufferNode} A reference to this node.
  20762. */
  20763. setAtomic( value ) {
  20764. this.isAtomic = value;
  20765. return this;
  20766. }
  20767. /**
  20768. * Convenience method for making this node atomic.
  20769. *
  20770. * @return {StorageBufferNode} A reference to this node.
  20771. */
  20772. toAtomic() {
  20773. return this.setAtomic( true );
  20774. }
  20775. /**
  20776. * Returns attribute data for this storage buffer node.
  20777. *
  20778. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  20779. */
  20780. getAttributeData() {
  20781. if ( this._attribute === null ) {
  20782. this._attribute = bufferAttribute( this.value );
  20783. this._varying = varying( this._attribute );
  20784. }
  20785. return {
  20786. attribute: this._attribute,
  20787. varying: this._varying
  20788. };
  20789. }
  20790. /**
  20791. * This method is overwritten since the node type from the availability of storage buffers
  20792. * and the attribute data.
  20793. *
  20794. * @param {NodeBuilder} builder - The current node builder.
  20795. * @return {String} The node type.
  20796. */
  20797. getNodeType( builder ) {
  20798. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  20799. return super.getNodeType( builder );
  20800. }
  20801. const { attribute } = this.getAttributeData();
  20802. return attribute.getNodeType( builder );
  20803. }
  20804. /**
  20805. * Generates the code snippet of the storage buffer node.
  20806. *
  20807. * @param {NodeBuilder} builder - The current node builder.
  20808. * @return {String} The generated code snippet.
  20809. */
  20810. generate( builder ) {
  20811. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  20812. return super.generate( builder );
  20813. }
  20814. const { attribute, varying } = this.getAttributeData();
  20815. const output = varying.build( builder );
  20816. builder.registerTransform( output, attribute );
  20817. return output;
  20818. }
  20819. }
  20820. /**
  20821. * TSL function for creating a storage buffer node.
  20822. *
  20823. * @function
  20824. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20825. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  20826. * @param {Number} [count=0] - The buffer count.
  20827. * @returns {StorageBufferNode}
  20828. */
  20829. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  20830. const storageObject = ( value, type, count ) => { // @deprecated, r171
  20831. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  20832. return storage( value, type, count ).setPBO( true );
  20833. };
  20834. /** @module Arrays **/
  20835. /**
  20836. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  20837. *
  20838. * @function
  20839. * @param {Number} count - The data count.
  20840. * @param {String} [type='float'] - The data type.
  20841. * @returns {StorageBufferNode}
  20842. */
  20843. const attributeArray = ( count, type = 'float' ) => {
  20844. const itemSize = getLengthFromType( type );
  20845. const typedArray = getTypedArrayFromType( type );
  20846. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  20847. const node = storage( buffer, type, count );
  20848. return node;
  20849. };
  20850. /**
  20851. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  20852. *
  20853. * @function
  20854. * @param {Number} count - The data count.
  20855. * @param {String} [type='float'] - The data type.
  20856. * @returns {StorageBufferNode}
  20857. */
  20858. const instancedArray = ( count, type = 'float' ) => {
  20859. const itemSize = getLengthFromType( type );
  20860. const typedArray = getTypedArrayFromType( type );
  20861. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  20862. const node = storage( buffer, type, count );
  20863. return node;
  20864. };
  20865. /** @module VertexColorNode **/
  20866. /**
  20867. * An attribute node for representing vertex colors.
  20868. *
  20869. * @augments module:AttributeNode~AttributeNode
  20870. */
  20871. class VertexColorNode extends AttributeNode {
  20872. static get type() {
  20873. return 'VertexColorNode';
  20874. }
  20875. /**
  20876. * Constructs a new vertex color node.
  20877. *
  20878. * @param {Number} [index=0] - The attribute index.
  20879. */
  20880. constructor( index = 0 ) {
  20881. super( null, 'vec4' );
  20882. /**
  20883. * This flag can be used for type testing.
  20884. *
  20885. * @type {Boolean}
  20886. * @readonly
  20887. * @default true
  20888. */
  20889. this.isVertexColorNode = true;
  20890. /**
  20891. * The attribute index to enable more than one sets of vertex colors.
  20892. *
  20893. * @type {Number}
  20894. * @default 0
  20895. */
  20896. this.index = index;
  20897. }
  20898. /**
  20899. * Overwrites the default implementation by honoring the attribute index.
  20900. *
  20901. * @param {NodeBuilder} builder - The current node builder.
  20902. * @return {String} The attribute name.
  20903. */
  20904. getAttributeName( /*builder*/ ) {
  20905. const index = this.index;
  20906. return 'color' + ( index > 0 ? index : '' );
  20907. }
  20908. generate( builder ) {
  20909. const attributeName = this.getAttributeName( builder );
  20910. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  20911. let result;
  20912. if ( geometryAttribute === true ) {
  20913. result = super.generate( builder );
  20914. } else {
  20915. // Vertex color fallback should be white
  20916. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  20917. }
  20918. return result;
  20919. }
  20920. serialize( data ) {
  20921. super.serialize( data );
  20922. data.index = this.index;
  20923. }
  20924. deserialize( data ) {
  20925. super.deserialize( data );
  20926. this.index = data.index;
  20927. }
  20928. }
  20929. /**
  20930. * TSL function for creating a reference node.
  20931. *
  20932. * @function
  20933. * @param {Number} index - The attribute index.
  20934. * @returns {VertexColorNode}
  20935. */
  20936. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  20937. /** @module PointUVNode **/
  20938. /**
  20939. * A node for representing the uv coordinates of points.
  20940. *
  20941. * Can only be used with a WebGL backend. In WebGPU, point
  20942. * primitives always have the size of one pixel and can thus
  20943. * can't be used as sprite-like objects that display textures.
  20944. *
  20945. * @augments Node
  20946. */
  20947. class PointUVNode extends Node {
  20948. static get type() {
  20949. return 'PointUVNode';
  20950. }
  20951. /**
  20952. * Constructs a new point uv node.
  20953. */
  20954. constructor() {
  20955. super( 'vec2' );
  20956. /**
  20957. * This flag can be used for type testing.
  20958. *
  20959. * @type {Boolean}
  20960. * @readonly
  20961. * @default true
  20962. */
  20963. this.isPointUVNode = true;
  20964. }
  20965. generate( /*builder*/ ) {
  20966. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  20967. }
  20968. }
  20969. /**
  20970. * TSL object that represents the uv coordinates of points.
  20971. *
  20972. * @type {PointUVNode}
  20973. */
  20974. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  20975. const _e1 = /*@__PURE__*/ new Euler();
  20976. const _m1 = /*@__PURE__*/ new Matrix4();
  20977. /** @module SceneNode **/
  20978. /**
  20979. * This module allows access to a collection of scene properties. The following predefined TSL objects
  20980. * are available for easier use:
  20981. *
  20982. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  20983. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  20984. * - `backgroundRotation`: A node that represents the scene's background rotation.
  20985. *
  20986. * @augments Node
  20987. */
  20988. class SceneNode extends Node {
  20989. static get type() {
  20990. return 'SceneNode';
  20991. }
  20992. /**
  20993. * Constructs a new scene node.
  20994. *
  20995. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  20996. * @param {Scene?} [scene=null] - A reference to the scene.
  20997. */
  20998. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  20999. super();
  21000. /**
  21001. * The scope defines the type of scene property that is accessed.
  21002. *
  21003. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  21004. */
  21005. this.scope = scope;
  21006. /**
  21007. * A reference to the scene that is going to be accessed.
  21008. *
  21009. * @type {Scene?}
  21010. * @default null
  21011. */
  21012. this.scene = scene;
  21013. }
  21014. /**
  21015. * Depending on the scope, the method returns a different type of node that represents
  21016. * the respective scene property.
  21017. *
  21018. * @param {NodeBuilder} builder - The current node builder.
  21019. * @return {Node} The output node.
  21020. */
  21021. setup( builder ) {
  21022. const scope = this.scope;
  21023. const scene = this.scene !== null ? this.scene : builder.scene;
  21024. let output;
  21025. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  21026. output = reference( 'backgroundBlurriness', 'float', scene );
  21027. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  21028. output = reference( 'backgroundIntensity', 'float', scene );
  21029. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  21030. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  21031. const background = scene.background;
  21032. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  21033. _e1.copy( scene.backgroundRotation );
  21034. // accommodate left-handed frame
  21035. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  21036. _m1.makeRotationFromEuler( _e1 );
  21037. } else {
  21038. _m1.identity();
  21039. }
  21040. return _m1;
  21041. } );
  21042. } else {
  21043. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  21044. }
  21045. return output;
  21046. }
  21047. }
  21048. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  21049. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  21050. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  21051. /**
  21052. * TSL object that represents the scene's background blurriness.
  21053. *
  21054. * @type {SceneNode}
  21055. */
  21056. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  21057. /**
  21058. * TSL object that represents the scene's background intensity.
  21059. *
  21060. * @type {SceneNode}
  21061. */
  21062. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  21063. /**
  21064. * TSL object that represents the scene's background rotation.
  21065. *
  21066. * @type {SceneNode}
  21067. */
  21068. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  21069. /** @module StorageTextureNode **/
  21070. /**
  21071. * This special version of a texture node can be used to
  21072. * write data into a storage texture with a compute shader.
  21073. *
  21074. * ```js
  21075. * const storageTexture = new THREE.StorageTexture( width, height );
  21076. *
  21077. * const computeTexture = Fn( ( { storageTexture } ) => {
  21078. *
  21079. * const posX = instanceIndex.modInt( width );
  21080. * const posY = instanceIndex.div( width );
  21081. * const indexUV = uvec2( posX, posY );
  21082. *
  21083. * // generate RGB values
  21084. *
  21085. * const r = 1;
  21086. * const g = 1;
  21087. * const b = 1;
  21088. *
  21089. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  21090. *
  21091. * } );
  21092. *
  21093. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  21094. * renderer.computeAsync( computeNode );
  21095. * ```
  21096. *
  21097. * This node can only be used with a WebGPU backend.
  21098. *
  21099. * @augments module:TextureNode~TextureNode
  21100. */
  21101. class StorageTextureNode extends TextureNode {
  21102. static get type() {
  21103. return 'StorageTextureNode';
  21104. }
  21105. /**
  21106. * Constructs a new storage texture node.
  21107. *
  21108. * @param {StorageTexture} value - The storage texture.
  21109. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21110. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21111. */
  21112. constructor( value, uvNode, storeNode = null ) {
  21113. super( value, uvNode );
  21114. /**
  21115. * The value node that should be stored in the texture.
  21116. *
  21117. * @type {Node?}
  21118. * @default null
  21119. */
  21120. this.storeNode = storeNode;
  21121. /**
  21122. * This flag can be used for type testing.
  21123. *
  21124. * @type {Boolean}
  21125. * @readonly
  21126. * @default true
  21127. */
  21128. this.isStorageTextureNode = true;
  21129. /**
  21130. * The access type of the texture node.
  21131. *
  21132. * @type {String}
  21133. * @default 'writeOnly'
  21134. */
  21135. this.access = NodeAccess.WRITE_ONLY;
  21136. }
  21137. /**
  21138. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  21139. *
  21140. * @param {NodeBuilder} builder - The current node builder.
  21141. * @return {String} The input type.
  21142. */
  21143. getInputType( /*builder*/ ) {
  21144. return 'storageTexture';
  21145. }
  21146. setup( builder ) {
  21147. super.setup( builder );
  21148. const properties = builder.getNodeProperties( this );
  21149. properties.storeNode = this.storeNode;
  21150. }
  21151. /**
  21152. * Defines the node access.
  21153. *
  21154. * @param {String} value - The node access.
  21155. * @return {StorageTextureNode} A reference to this node.
  21156. */
  21157. setAccess( value ) {
  21158. this.access = value;
  21159. return this;
  21160. }
  21161. /**
  21162. * Generates the code snippet of the stroge node. If no `storeNode`
  21163. * is defined, the texture node is generated as normal texture.
  21164. *
  21165. * @param {NodeBuilder} builder - The current node builder.
  21166. * @param {String} output - The current output.
  21167. * @return {String} The generated code snippet.
  21168. */
  21169. generate( builder, output ) {
  21170. let snippet;
  21171. if ( this.storeNode !== null ) {
  21172. snippet = this.generateStore( builder );
  21173. } else {
  21174. snippet = super.generate( builder, output );
  21175. }
  21176. return snippet;
  21177. }
  21178. /**
  21179. * Convenience method for configuring a read/write node access.
  21180. *
  21181. * @return {StorageTextureNode} A reference to this node.
  21182. */
  21183. toReadWrite() {
  21184. return this.setAccess( NodeAccess.READ_WRITE );
  21185. }
  21186. /**
  21187. * Convenience method for configuring a read-only node access.
  21188. *
  21189. * @return {StorageTextureNode} A reference to this node.
  21190. */
  21191. toReadOnly() {
  21192. return this.setAccess( NodeAccess.READ_ONLY );
  21193. }
  21194. /**
  21195. * Convenience method for configuring a write-only node access.
  21196. *
  21197. * @return {StorageTextureNode} A reference to this node.
  21198. */
  21199. toWriteOnly() {
  21200. return this.setAccess( NodeAccess.WRITE_ONLY );
  21201. }
  21202. /**
  21203. * Generates the code snippet of the storage texture node.
  21204. *
  21205. * @param {NodeBuilder} builder - The current node builder.
  21206. */
  21207. generateStore( builder ) {
  21208. const properties = builder.getNodeProperties( this );
  21209. const { uvNode, storeNode } = properties;
  21210. const textureProperty = super.generate( builder, 'property' );
  21211. const uvSnippet = uvNode.build( builder, 'uvec2' );
  21212. const storeSnippet = storeNode.build( builder, 'vec4' );
  21213. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  21214. builder.addLineFlowCode( snippet, this );
  21215. }
  21216. }
  21217. /**
  21218. * TSL function for creating a storage texture node.
  21219. *
  21220. * @function
  21221. * @param {StorageTexture} value - The storage texture.
  21222. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21223. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21224. * @returns {StorageTextureNode}
  21225. */
  21226. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  21227. /**
  21228. * TODO: Explain difference to `storageTexture()`.
  21229. *
  21230. * @function
  21231. * @param {StorageTexture} value - The storage texture.
  21232. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21233. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21234. * @returns {StorageTextureNode}
  21235. */
  21236. const textureStore = ( value, uvNode, storeNode ) => {
  21237. const node = storageTexture( value, uvNode, storeNode );
  21238. if ( storeNode !== null ) node.append();
  21239. return node;
  21240. };
  21241. /** @module UserDataNode **/
  21242. /**
  21243. * A special type of reference node that allows to link values in
  21244. * `userData` fields to node objects.
  21245. * ```js
  21246. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  21247. *
  21248. * const material = new THREE.SpriteNodeMaterial();
  21249. * material.rotationNode = userData( 'rotation', 'float' );
  21250. * ```
  21251. * Since `UserDataNode` is extended from {@link module:ReferenceNode~ReferenceNode}, the node value
  21252. * will automatically be updated when the `rotation` user data field changes.
  21253. *
  21254. * @augments module:ReferenceNode~ReferenceNode
  21255. */
  21256. class UserDataNode extends ReferenceNode {
  21257. static get type() {
  21258. return 'UserDataNode';
  21259. }
  21260. /**
  21261. * Constructs a new user data node.
  21262. *
  21263. * @param {String} property - The property name that should be referenced by the node.
  21264. * @param {String} inputType - The node data type of the reference.
  21265. * @param {Object?} [userData=null] - A reference to the `userData` object. If not provided, the `userData` property of the 3D object that uses the node material is evaluated.
  21266. */
  21267. constructor( property, inputType, userData = null ) {
  21268. super( property, inputType, userData );
  21269. /**
  21270. * A reference to the `userData` object. If not provided, the `userData`
  21271. * property of the 3D object that uses the node material is evaluated.
  21272. *
  21273. * @type {Object?}
  21274. * @default null
  21275. */
  21276. this.userData = userData;
  21277. }
  21278. /**
  21279. * Overwritten to make sure {@link module:ReferenceNode~ReferenceNode#reference} points to the correct
  21280. * `userData` field.
  21281. *
  21282. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  21283. * @return {Object} A reference to the `userData` field.
  21284. */
  21285. updateReference( state ) {
  21286. this.reference = this.userData !== null ? this.userData : state.object.userData;
  21287. return this.reference;
  21288. }
  21289. }
  21290. /**
  21291. * TSL function for creating a user data node.
  21292. *
  21293. * @function
  21294. * @param {String} name - The property name that should be referenced by the node.
  21295. * @param {String} inputType - The node data type of the reference.
  21296. * @param {Object?} userData - A reference to the `userData` object. If not provided, the `userData` property of the 3D object that uses the node material is evaluated.
  21297. * @returns {UserDataNode}
  21298. */
  21299. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  21300. const _objectData = new WeakMap();
  21301. /** @module VelocityNode **/
  21302. /**
  21303. * A node for representing motion or velocity vectors. Foundation
  21304. * for advanced post processing effects like motion blur or TRAA.
  21305. *
  21306. * The node keeps track of the model, view and projection matrices
  21307. * of the previous frame and uses them to compute offsets in NDC space.
  21308. * These offsets represent the final velocity.
  21309. *
  21310. * @augments TempNode
  21311. */
  21312. class VelocityNode extends TempNode {
  21313. static get type() {
  21314. return 'VelocityNode';
  21315. }
  21316. /**
  21317. * Constructs a new vertex color node.
  21318. *
  21319. * @param {Number} [index=0] - The attribute index.
  21320. */
  21321. constructor() {
  21322. super( 'vec2' );
  21323. /**
  21324. * The current projection matrix.
  21325. *
  21326. * @type {Matrix4?}
  21327. * @default null
  21328. */
  21329. this.projectionMatrix = null;
  21330. /**
  21331. * Overwritten since velocity nodes are updated per object.
  21332. *
  21333. * @type {String}
  21334. * @default 'object'
  21335. */
  21336. this.updateType = NodeUpdateType.OBJECT;
  21337. /**
  21338. * Overwritten since velocity nodes save data after the update.
  21339. *
  21340. * @type {String}
  21341. * @default 'object'
  21342. */
  21343. this.updateAfterType = NodeUpdateType.OBJECT;
  21344. /**
  21345. * Uniform node representing the previous model matrix in world space.
  21346. *
  21347. * @type {UniformNode<mat4>}
  21348. * @default null
  21349. */
  21350. this.previousModelWorldMatrix = uniform( new Matrix4() );
  21351. /**
  21352. * Uniform node representing the previous projection matrix.
  21353. *
  21354. * @type {UniformNode<mat4>}
  21355. * @default null
  21356. */
  21357. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  21358. /**
  21359. * Uniform node representing the previous view matrix.
  21360. *
  21361. * @type {UniformNode<mat4>}
  21362. * @default null
  21363. */
  21364. this.previousCameraViewMatrix = uniform( new Matrix4() );
  21365. }
  21366. /**
  21367. * Sets the given projection matrix.
  21368. *
  21369. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  21370. */
  21371. setProjectionMatrix( projectionMatrix ) {
  21372. this.projectionMatrix = projectionMatrix;
  21373. }
  21374. /**
  21375. * Updates velocity specific uniforms.
  21376. *
  21377. * @param {NodeFrame} frame - A reference to the current node frame.
  21378. */
  21379. update( { frameId, camera, object } ) {
  21380. const previousModelMatrix = getPreviousMatrix( object );
  21381. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  21382. //
  21383. const cameraData = getData( camera );
  21384. if ( cameraData.frameId !== frameId ) {
  21385. cameraData.frameId = frameId;
  21386. if ( cameraData.previousProjectionMatrix === undefined ) {
  21387. cameraData.previousProjectionMatrix = new Matrix4();
  21388. cameraData.previousCameraViewMatrix = new Matrix4();
  21389. cameraData.currentProjectionMatrix = new Matrix4();
  21390. cameraData.currentCameraViewMatrix = new Matrix4();
  21391. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21392. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  21393. } else {
  21394. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  21395. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  21396. }
  21397. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21398. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  21399. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  21400. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  21401. }
  21402. }
  21403. /**
  21404. * Overwritten to updated velocity specific uniforms.
  21405. *
  21406. * @param {NodeFrame} frame - A reference to the current node frame.
  21407. */
  21408. updateAfter( { object } ) {
  21409. getPreviousMatrix( object ).copy( object.matrixWorld );
  21410. }
  21411. /**
  21412. * Implements the velocity computation based on the previous and current vertex data.
  21413. *
  21414. * @param {NodeBuilder} builder - A reference to the current node builder.
  21415. * @return {Node<vec2>} The motion vector.
  21416. */
  21417. setup( /*builder*/ ) {
  21418. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  21419. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  21420. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  21421. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  21422. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  21423. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  21424. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  21425. return velocity;
  21426. }
  21427. }
  21428. function getData( object ) {
  21429. let objectData = _objectData.get( object );
  21430. if ( objectData === undefined ) {
  21431. objectData = {};
  21432. _objectData.set( object, objectData );
  21433. }
  21434. return objectData;
  21435. }
  21436. function getPreviousMatrix( object, index = 0 ) {
  21437. const objectData = getData( object );
  21438. let matrix = objectData[ index ];
  21439. if ( matrix === undefined ) {
  21440. objectData[ index ] = matrix = new Matrix4();
  21441. }
  21442. return matrix;
  21443. }
  21444. /**
  21445. * TSL object that represents the velocity of a render pass.
  21446. *
  21447. * @type {VelocityNode}
  21448. */
  21449. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  21450. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21451. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  21452. } ).setLayout( {
  21453. name: 'blendBurn',
  21454. type: 'vec3',
  21455. inputs: [
  21456. { name: 'base', type: 'vec3' },
  21457. { name: 'blend', type: 'vec3' }
  21458. ]
  21459. } );
  21460. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21461. return min$1( base.div( blend.oneMinus() ), 1.0 );
  21462. } ).setLayout( {
  21463. name: 'blendDodge',
  21464. type: 'vec3',
  21465. inputs: [
  21466. { name: 'base', type: 'vec3' },
  21467. { name: 'blend', type: 'vec3' }
  21468. ]
  21469. } );
  21470. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21471. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  21472. } ).setLayout( {
  21473. name: 'blendScreen',
  21474. type: 'vec3',
  21475. inputs: [
  21476. { name: 'base', type: 'vec3' },
  21477. { name: 'blend', type: 'vec3' }
  21478. ]
  21479. } );
  21480. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21481. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  21482. } ).setLayout( {
  21483. name: 'blendOverlay',
  21484. type: 'vec3',
  21485. inputs: [
  21486. { name: 'base', type: 'vec3' },
  21487. { name: 'blend', type: 'vec3' }
  21488. ]
  21489. } );
  21490. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21491. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  21492. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  21493. } ).setLayout( {
  21494. name: 'blendColor',
  21495. type: 'vec4',
  21496. inputs: [
  21497. { name: 'base', type: 'vec4' },
  21498. { name: 'blend', type: 'vec4' }
  21499. ]
  21500. } );
  21501. // deprecated
  21502. const burn = ( ...params ) => { // @deprecated, r171
  21503. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  21504. return blendBurn( params );
  21505. };
  21506. const dodge = ( ...params ) => { // @deprecated, r171
  21507. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  21508. return blendDodge( params );
  21509. };
  21510. const screen = ( ...params ) => { // @deprecated, r171
  21511. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  21512. return blendScreen( params );
  21513. };
  21514. const overlay = ( ...params ) => { // @deprecated, r171
  21515. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  21516. return blendOverlay( params );
  21517. };
  21518. /** @module ColorAdjustment **/
  21519. /**
  21520. * Computes a grayscale value for the given RGB color value.
  21521. *
  21522. * @method
  21523. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  21524. * @return {Node<vec3>} The grayscale color.
  21525. */
  21526. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  21527. return luminance( color.rgb );
  21528. } );
  21529. /**
  21530. * Super-saturates or desaturates the given RGB color.
  21531. *
  21532. * @method
  21533. * @param {Node<vec3>} color - The input color.
  21534. * @param {Node<float>} [adjustment=1] - Specifies the amount of the conversion. A value under `1` desaturates the color, a value over `1` super-saturates it.
  21535. * @return {Node<vec3>} The saturated color.
  21536. */
  21537. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21538. return adjustment.mix( luminance( color.rgb ), color.rgb );
  21539. } );
  21540. /**
  21541. * Selectively enhance the intensity of less saturated RGB colors. Can result
  21542. * in a more natural and visually appealing image with enhanced color depth
  21543. * compared to {@link ColorAdjustment#saturation}.
  21544. *
  21545. * @method
  21546. * @param {Node<vec3>} color - The input color.
  21547. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  21548. * @return {Node<vec3>} The updated color.
  21549. */
  21550. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21551. const average = add( color.r, color.g, color.b ).div( 3.0 );
  21552. const mx = color.r.max( color.g.max( color.b ) );
  21553. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  21554. return mix( color.rgb, mx, amt );
  21555. } );
  21556. /**
  21557. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  21558. *
  21559. * @method
  21560. * @param {Node<vec3>} color - The input color.
  21561. * @param {Node<float>} [adjustment=1] - Defines the degree of hue rotation in radians. A positive value rotates the hue clockwise, while a negative value rotates it counterclockwise.
  21562. * @return {Node<vec3>} The updated color.
  21563. */
  21564. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21565. const k = vec3( 0.57735, 0.57735, 0.57735 );
  21566. const cosAngle = adjustment.cos();
  21567. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  21568. } );
  21569. /**
  21570. * Computes the luminance for the given RGB color value.
  21571. *
  21572. * @method
  21573. * @param {Node<vec3>} color - The color value to compute the luminance for.
  21574. * @param {Node<vec3>?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  21575. * @return {Node<vec3>} The luminance.
  21576. */
  21577. const luminance = (
  21578. color,
  21579. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  21580. ) => dot( color, luminanceCoefficients );
  21581. /**
  21582. * Color Decision List (CDL) v1.2
  21583. *
  21584. * Compact representation of color grading information, defined by slope, offset, power, and
  21585. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  21586. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  21587. *
  21588. * @method
  21589. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  21590. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  21591. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  21592. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  21593. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  21594. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  21595. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  21596. *
  21597. * References:
  21598. * - ASC CDL v1.2
  21599. * - {@link https://blender.stackexchange.com/a/55239/43930}
  21600. * - {@link https://docs.acescentral.com/specifications/acescc/}
  21601. */
  21602. const cdl = /*@__PURE__*/ Fn( ( [
  21603. color,
  21604. slope = vec3( 1 ),
  21605. offset = vec3( 0 ),
  21606. power = vec3( 1 ),
  21607. saturation = float( 1 ),
  21608. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  21609. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  21610. ] ) => {
  21611. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  21612. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  21613. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  21614. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  21615. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  21616. const pv = v.pow( power ).toVar();
  21617. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  21618. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  21619. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  21620. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  21621. return vec4( v.rgb, color.a );
  21622. } );
  21623. /** @module PosterizeNode **/
  21624. /**
  21625. * Represents a posterize effect which reduces the number of colors
  21626. * in an image, resulting in a more blocky and stylized appearance.
  21627. *
  21628. * @augments TempNode
  21629. */
  21630. class PosterizeNode extends TempNode {
  21631. static get type() {
  21632. return 'PosterizeNode';
  21633. }
  21634. /**
  21635. * Constructs a new posterize node.
  21636. *
  21637. * @param {Node} sourceNode - The input color.
  21638. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21639. */
  21640. constructor( sourceNode, stepsNode ) {
  21641. super();
  21642. /**
  21643. * The input color.
  21644. *
  21645. * @type {Node}
  21646. */
  21647. this.sourceNode = sourceNode;
  21648. /**
  21649. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21650. *
  21651. * @type {Node}
  21652. */
  21653. this.stepsNode = stepsNode;
  21654. }
  21655. setup() {
  21656. const { sourceNode, stepsNode } = this;
  21657. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  21658. }
  21659. }
  21660. /**
  21661. * TSL function for creating a posterize node.
  21662. *
  21663. * @function
  21664. * @param {Node} sourceNode - The input color.
  21665. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21666. * @returns {PosterizeNode}
  21667. */
  21668. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  21669. /** @module PassNode **/
  21670. const _size = /*@__PURE__*/ new Vector2();
  21671. /**
  21672. * Represents the texture of a pass node.
  21673. *
  21674. * @augments module:TextureNode~TextureNode
  21675. */
  21676. class PassTextureNode extends TextureNode {
  21677. static get type() {
  21678. return 'PassTextureNode';
  21679. }
  21680. /**
  21681. * Constructs a new pass texture node.
  21682. *
  21683. * @param {PassNode} passNode - The pass node.
  21684. * @param {Texture} texture - The output texture.
  21685. */
  21686. constructor( passNode, texture ) {
  21687. super( texture );
  21688. /**
  21689. * A reference to the pass node.
  21690. *
  21691. * @type {PassNode}
  21692. */
  21693. this.passNode = passNode;
  21694. this.setUpdateMatrix( false );
  21695. }
  21696. setup( builder ) {
  21697. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  21698. return super.setup( builder );
  21699. }
  21700. clone() {
  21701. return new this.constructor( this.passNode, this.value );
  21702. }
  21703. }
  21704. /**
  21705. * An extension of `PassTextureNode` which allows to manage more than one
  21706. * internal texture. Relevant for the `getPreviousTexture()` related API.
  21707. *
  21708. * @augments module:PassTextureNode~PassTextureNode
  21709. */
  21710. class PassMultipleTextureNode extends PassTextureNode {
  21711. static get type() {
  21712. return 'PassMultipleTextureNode';
  21713. }
  21714. /**
  21715. * Constructs a new pass texture node.
  21716. *
  21717. * @param {PassNode} passNode - The pass node.
  21718. * @param {String} textureName - The output texture name.
  21719. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  21720. */
  21721. constructor( passNode, textureName, previousTexture = false ) {
  21722. // null is passed to the super call since this class does not
  21723. // use an external texture for rendering pass data into. Instead
  21724. // the texture is managed by the pass node itself
  21725. super( passNode, null );
  21726. /**
  21727. * The output texture name.
  21728. *
  21729. * @type {String}
  21730. */
  21731. this.textureName = textureName;
  21732. /**
  21733. * Whether previous frame data should be used or not.
  21734. *
  21735. * @type {Boolean}
  21736. */
  21737. this.previousTexture = previousTexture;
  21738. }
  21739. /**
  21740. * Updates the texture reference of this node.
  21741. */
  21742. updateTexture() {
  21743. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  21744. }
  21745. setup( builder ) {
  21746. this.updateTexture();
  21747. return super.setup( builder );
  21748. }
  21749. clone() {
  21750. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  21751. }
  21752. }
  21753. /**
  21754. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  21755. * This pass produces a render for the given scene and camera and can provide multiple outputs
  21756. * via MRT for further processing.
  21757. *
  21758. * ```js
  21759. * const postProcessing = new PostProcessing( renderer );
  21760. *
  21761. * const scenePass = pass( scene, camera );
  21762. *
  21763. * postProcessing.outputNode = scenePass;
  21764. * ```
  21765. *
  21766. * @augments TempNode
  21767. */
  21768. class PassNode extends TempNode {
  21769. static get type() {
  21770. return 'PassNode';
  21771. }
  21772. /**
  21773. * Constructs a new pass node.
  21774. *
  21775. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  21776. * @param {Scene} scene - A reference to the scene.
  21777. * @param {Camera} camera - A reference to the camera.
  21778. * @param {Object} options - Options for the internal render target.
  21779. */
  21780. constructor( scope, scene, camera, options = {} ) {
  21781. super( 'vec4' );
  21782. /**
  21783. * The scope of the pass. The scope determines whether the node outputs color or depth.
  21784. *
  21785. * @type {('color'|'depth')}
  21786. */
  21787. this.scope = scope;
  21788. /**
  21789. * A reference to the scene.
  21790. *
  21791. * @type {Scene}
  21792. */
  21793. this.scene = scene;
  21794. /**
  21795. * A reference to the camera.
  21796. *
  21797. * @type {Camera}
  21798. */
  21799. this.camera = camera;
  21800. /**
  21801. * Options for the internal render target.
  21802. *
  21803. * @type {Object}
  21804. */
  21805. this.options = options;
  21806. /**
  21807. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  21808. *
  21809. * @private
  21810. * @type {Number}
  21811. * @default 1
  21812. */
  21813. this._pixelRatio = 1;
  21814. /**
  21815. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  21816. * @private
  21817. * @type {Number}
  21818. * @default 1
  21819. */
  21820. this._width = 1;
  21821. /**
  21822. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  21823. * @private
  21824. * @type {Number}
  21825. * @default 1
  21826. */
  21827. this._height = 1;
  21828. const depthTexture = new DepthTexture();
  21829. depthTexture.isRenderTargetTexture = true;
  21830. //depthTexture.type = FloatType;
  21831. depthTexture.name = 'depth';
  21832. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  21833. renderTarget.texture.name = 'output';
  21834. renderTarget.depthTexture = depthTexture;
  21835. /**
  21836. * The pass's render target.
  21837. *
  21838. * @type {RenderTarget}
  21839. */
  21840. this.renderTarget = renderTarget;
  21841. /**
  21842. * A dictionary holding the internal result textures.
  21843. *
  21844. * @private
  21845. * @type {Object<String, Texture>}
  21846. */
  21847. this._textures = {
  21848. output: renderTarget.texture,
  21849. depth: depthTexture
  21850. };
  21851. /**
  21852. * A dictionary holding the internal texture nodes.
  21853. *
  21854. * @private
  21855. * @type {Object<String, TextureNode>}
  21856. */
  21857. this._textureNodes = {};
  21858. /**
  21859. * A dictionary holding the internal depth nodes.
  21860. *
  21861. * @private
  21862. * @type {Object}
  21863. */
  21864. this._linearDepthNodes = {};
  21865. /**
  21866. * A dictionary holding the internal viewZ nodes.
  21867. *
  21868. * @private
  21869. * @type {Object}
  21870. */
  21871. this._viewZNodes = {};
  21872. /**
  21873. * A dictionary holding the texture data of the previous frame.
  21874. * Used for computing velocity/motion vectors.
  21875. *
  21876. * @private
  21877. * @type {Object<String, Texture>}
  21878. */
  21879. this._previousTextures = {};
  21880. /**
  21881. * A dictionary holding the texture nodes of the previous frame.
  21882. * Used for computing velocity/motion vectors.
  21883. *
  21884. * @private
  21885. * @type {Object<String, TextureNode>}
  21886. */
  21887. this._previousTextureNodes = {};
  21888. /**
  21889. * The `near` property of the camera as a uniform.
  21890. *
  21891. * @private
  21892. * @type {UniformNode}
  21893. */
  21894. this._cameraNear = uniform( 0 );
  21895. /**
  21896. * The `far` property of the camera as a uniform.
  21897. *
  21898. * @private
  21899. * @type {UniformNode}
  21900. */
  21901. this._cameraFar = uniform( 0 );
  21902. /**
  21903. * A MRT node configuring the MRT settings.
  21904. *
  21905. * @private
  21906. * @type {MRTNode?}
  21907. * @default null
  21908. */
  21909. this._mrt = null;
  21910. /**
  21911. * This flag can be used for type testing.
  21912. *
  21913. * @type {Boolean}
  21914. * @readonly
  21915. * @default true
  21916. */
  21917. this.isPassNode = true;
  21918. /**
  21919. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  21920. * scene once per frame in its {@link PassNode#updateBefore} method.
  21921. *
  21922. * @type {String}
  21923. * @default 'frame'
  21924. */
  21925. this.updateBeforeType = NodeUpdateType.FRAME;
  21926. }
  21927. /**
  21928. * Sets the given MRT node to setup MRT for this pass.
  21929. *
  21930. * @param {MRTNode} mrt - The MRT object.
  21931. * @return {PassNode} A reference to this pass.
  21932. */
  21933. setMRT( mrt ) {
  21934. this._mrt = mrt;
  21935. return this;
  21936. }
  21937. /**
  21938. * Returns the current MRT node.
  21939. *
  21940. * @return {MRTNode} The current MRT node.
  21941. */
  21942. getMRT() {
  21943. return this._mrt;
  21944. }
  21945. /**
  21946. * The method is overwritten so it always returns `true`.
  21947. *
  21948. * @return {Boolean} Whether this node is global or not.
  21949. */
  21950. isGlobal() {
  21951. return true;
  21952. }
  21953. /**
  21954. * Returns the texture for the given output name.
  21955. *
  21956. * @param {String} name - The output name to get the texture for.
  21957. * @return {Texture} The texture.
  21958. */
  21959. getTexture( name ) {
  21960. let texture = this._textures[ name ];
  21961. if ( texture === undefined ) {
  21962. const refTexture = this.renderTarget.texture;
  21963. texture = refTexture.clone();
  21964. texture.name = name;
  21965. this._textures[ name ] = texture;
  21966. this.renderTarget.textures.push( texture );
  21967. }
  21968. return texture;
  21969. }
  21970. /**
  21971. * Returns the texture holding the data of the previous frame for the given output name.
  21972. *
  21973. * @param {String} name - The output name to get the texture for.
  21974. * @return {Texture} The texture holding the data of the previous frame.
  21975. */
  21976. getPreviousTexture( name ) {
  21977. let texture = this._previousTextures[ name ];
  21978. if ( texture === undefined ) {
  21979. texture = this.getTexture( name ).clone();
  21980. this._previousTextures[ name ] = texture;
  21981. }
  21982. return texture;
  21983. }
  21984. /**
  21985. * Switches current and previous textures for the given output name.
  21986. *
  21987. * @param {String} name - The output name.
  21988. */
  21989. toggleTexture( name ) {
  21990. const prevTexture = this._previousTextures[ name ];
  21991. if ( prevTexture !== undefined ) {
  21992. const texture = this._textures[ name ];
  21993. const index = this.renderTarget.textures.indexOf( texture );
  21994. this.renderTarget.textures[ index ] = prevTexture;
  21995. this._textures[ name ] = prevTexture;
  21996. this._previousTextures[ name ] = texture;
  21997. this._textureNodes[ name ].updateTexture();
  21998. this._previousTextureNodes[ name ].updateTexture();
  21999. }
  22000. }
  22001. /**
  22002. * Returns the texture node for the given output name.
  22003. *
  22004. * @param {String} [name='output'] - The output name to get the texture node for.
  22005. * @return {TextureNode} The texture node.
  22006. */
  22007. getTextureNode( name = 'output' ) {
  22008. let textureNode = this._textureNodes[ name ];
  22009. if ( textureNode === undefined ) {
  22010. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  22011. textureNode.updateTexture();
  22012. this._textureNodes[ name ] = textureNode;
  22013. }
  22014. return textureNode;
  22015. }
  22016. /**
  22017. * Returns the previous texture node for the given output name.
  22018. *
  22019. * @param {String} [name='output'] - The output name to get the previous texture node for.
  22020. * @return {TextureNode} The previous texture node.
  22021. */
  22022. getPreviousTextureNode( name = 'output' ) {
  22023. let textureNode = this._previousTextureNodes[ name ];
  22024. if ( textureNode === undefined ) {
  22025. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  22026. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  22027. textureNode.updateTexture();
  22028. this._previousTextureNodes[ name ] = textureNode;
  22029. }
  22030. return textureNode;
  22031. }
  22032. /**
  22033. * Returns a viewZ node of this pass.
  22034. *
  22035. * @param {String} [name='depth'] - The output name to get the viewZ node for. In most cases the default `'depth'` can be used however the parameter exists for custom depth outputs.
  22036. * @return {Node} The viewZ node.
  22037. */
  22038. getViewZNode( name = 'depth' ) {
  22039. let viewZNode = this._viewZNodes[ name ];
  22040. if ( viewZNode === undefined ) {
  22041. const cameraNear = this._cameraNear;
  22042. const cameraFar = this._cameraFar;
  22043. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  22044. }
  22045. return viewZNode;
  22046. }
  22047. /**
  22048. * Returns a linear depth node of this pass.
  22049. *
  22050. * @param {String} [name='depth'] - The output name to get the linear depth node for. In most cases the default `'depth'` can be used however the parameter exists for custom depth outputs.
  22051. * @return {Node} The linear depth node.
  22052. */
  22053. getLinearDepthNode( name = 'depth' ) {
  22054. let linearDepthNode = this._linearDepthNodes[ name ];
  22055. if ( linearDepthNode === undefined ) {
  22056. const cameraNear = this._cameraNear;
  22057. const cameraFar = this._cameraFar;
  22058. const viewZNode = this.getViewZNode( name );
  22059. // TODO: just if ( builder.camera.isPerspectiveCamera )
  22060. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  22061. }
  22062. return linearDepthNode;
  22063. }
  22064. setup( { renderer } ) {
  22065. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  22066. // Disable MSAA for WebGL backend for now
  22067. if ( renderer.backend.isWebGLBackend === true ) {
  22068. this.renderTarget.samples = 0;
  22069. }
  22070. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  22071. }
  22072. updateBefore( frame ) {
  22073. const { renderer } = frame;
  22074. const { scene, camera } = this;
  22075. this._pixelRatio = renderer.getPixelRatio();
  22076. const size = renderer.getSize( _size );
  22077. this.setSize( size.width, size.height );
  22078. const currentRenderTarget = renderer.getRenderTarget();
  22079. const currentMRT = renderer.getMRT();
  22080. this._cameraNear.value = camera.near;
  22081. this._cameraFar.value = camera.far;
  22082. for ( const name in this._previousTextures ) {
  22083. this.toggleTexture( name );
  22084. }
  22085. renderer.setRenderTarget( this.renderTarget );
  22086. renderer.setMRT( this._mrt );
  22087. renderer.render( scene, camera );
  22088. renderer.setRenderTarget( currentRenderTarget );
  22089. renderer.setMRT( currentMRT );
  22090. }
  22091. /**
  22092. * Sets the size of the pass's render target. Honors the pixel ratio.
  22093. *
  22094. * @param {Number} width - The width to set.
  22095. * @param {Number} height - The height to set.
  22096. */
  22097. setSize( width, height ) {
  22098. this._width = width;
  22099. this._height = height;
  22100. const effectiveWidth = this._width * this._pixelRatio;
  22101. const effectiveHeight = this._height * this._pixelRatio;
  22102. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  22103. }
  22104. /**
  22105. * Sets the pixel ratio the pass's render target and updates the size.
  22106. *
  22107. * @param {Number} pixelRatio - The pixel ratio to set.
  22108. */
  22109. setPixelRatio( pixelRatio ) {
  22110. this._pixelRatio = pixelRatio;
  22111. this.setSize( this._width, this._height );
  22112. }
  22113. /**
  22114. * Frees internal resources. Should be called when the node is no longer in use.
  22115. */
  22116. dispose() {
  22117. this.renderTarget.dispose();
  22118. }
  22119. }
  22120. PassNode.COLOR = 'color';
  22121. PassNode.DEPTH = 'depth';
  22122. /**
  22123. * TSL function for creating a pass node.
  22124. *
  22125. * @function
  22126. * @param {Scene} scene - A reference to the scene.
  22127. * @param {Camera} camera - A reference to the camera.
  22128. * @param {Object} options - Options for the internal render target.
  22129. * @returns {PassNode}
  22130. */
  22131. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  22132. /**
  22133. * TSL function for creating a pass texture node.
  22134. *
  22135. * @function
  22136. * @param {PassNode} pass - The pass node.
  22137. * @param {Texture} texture - The output texture.
  22138. * @returns {PassTextureNode}
  22139. */
  22140. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  22141. /**
  22142. * TSL function for creating a depth pass node.
  22143. *
  22144. * @function
  22145. * @param {Scene} scene - A reference to the scene.
  22146. * @param {Camera} camera - A reference to the camera.
  22147. * @param {Object} options - Options for the internal render target.
  22148. * @returns {PassNode}
  22149. */
  22150. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  22151. /** @module ToonOutlinePassNode **/
  22152. /**
  22153. * Represents a render pass for producing a toon outline effect on compatible objects.
  22154. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  22155. * will receive the outline.
  22156. *
  22157. * ```js
  22158. * const postProcessing = new PostProcessing( renderer );
  22159. *
  22160. * const scenePass = toonOutlinePass( scene, camera );
  22161. *
  22162. * postProcessing.outputNode = scenePass;
  22163. * ```
  22164. * @augments PassNode
  22165. */
  22166. class ToonOutlinePassNode extends PassNode {
  22167. static get type() {
  22168. return 'ToonOutlinePassNode';
  22169. }
  22170. /**
  22171. * Constructs a new outline pass node.
  22172. *
  22173. * @param {Scene} scene - A reference to the scene.
  22174. * @param {Camera} camera - A reference to the camera.
  22175. * @param {Node} colorNode - Defines the outline's color.
  22176. * @param {Node} thicknessNode - Defines the outline's thickness.
  22177. * @param {Node} alphaNode - Defines the outline's alpha.
  22178. */
  22179. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  22180. super( PassNode.COLOR, scene, camera );
  22181. /**
  22182. * Defines the outline's color.
  22183. *
  22184. * @type {Node}
  22185. */
  22186. this.colorNode = colorNode;
  22187. /**
  22188. * Defines the outline's thickness.
  22189. *
  22190. * @type {Node}
  22191. */
  22192. this.thicknessNode = thicknessNode;
  22193. /**
  22194. * Defines the outline's alpha.
  22195. *
  22196. * @type {Node}
  22197. */
  22198. this.alphaNode = alphaNode;
  22199. /**
  22200. * An internal material cache.
  22201. *
  22202. * @private
  22203. * @type {WeakMap<Material, NodeMaterial>}
  22204. */
  22205. this._materialCache = new WeakMap();
  22206. }
  22207. updateBefore( frame ) {
  22208. const { renderer } = frame;
  22209. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  22210. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  22211. // only render outline for supported materials
  22212. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  22213. if ( material.wireframe === false ) {
  22214. const outlineMaterial = this._getOutlineMaterial( material );
  22215. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  22216. }
  22217. }
  22218. // default
  22219. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  22220. } );
  22221. super.updateBefore( frame );
  22222. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  22223. }
  22224. /**
  22225. * Creates the material used for outline rendering.
  22226. *
  22227. * @private
  22228. * @return {NodeMaterial} The outline material.
  22229. */
  22230. _createMaterial() {
  22231. const material = new NodeMaterial();
  22232. material.isMeshToonOutlineMaterial = true;
  22233. material.name = 'Toon_Outline';
  22234. material.side = BackSide;
  22235. // vertex node
  22236. const outlineNormal = normalLocal.negate();
  22237. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  22238. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  22239. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  22240. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  22241. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  22242. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  22243. // color node
  22244. material.colorNode = vec4( this.colorNode, this.alphaNode );
  22245. return material;
  22246. }
  22247. /**
  22248. * For the given toon material, this method returns a corresponding
  22249. * outline material.
  22250. *
  22251. * @private
  22252. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  22253. * @return {NodeMaterial} The outline material.
  22254. */
  22255. _getOutlineMaterial( originalMaterial ) {
  22256. let outlineMaterial = this._materialCache.get( originalMaterial );
  22257. if ( outlineMaterial === undefined ) {
  22258. outlineMaterial = this._createMaterial();
  22259. this._materialCache.set( originalMaterial, outlineMaterial );
  22260. }
  22261. return outlineMaterial;
  22262. }
  22263. }
  22264. /**
  22265. * TSL function for creating a toon outline pass node.
  22266. *
  22267. * @function
  22268. * @param {Scene} scene - A reference to the scene.
  22269. * @param {Camera} camera - A reference to the camera.
  22270. * @param {Color} color - Defines the outline's color.
  22271. * @param {Number} [thickness=0.003] - Defines the outline's thickness.
  22272. * @param {Number} [alpha=1] - Defines the outline's alpha.
  22273. * @returns {ToonOutlinePassNode}
  22274. */
  22275. const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) );
  22276. /** @module ToneMappingFunctions **/
  22277. /**
  22278. * Linear tone mapping, exposure only.
  22279. *
  22280. * @method
  22281. * @param {Node<vec3>} color - The color that should be tone mapped.
  22282. * @param {Node<float>} exposure - The exposure.
  22283. * @return {Node<vec3>} The tone mapped color.
  22284. */
  22285. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22286. return color.mul( exposure ).clamp();
  22287. } ).setLayout( {
  22288. name: 'linearToneMapping',
  22289. type: 'vec3',
  22290. inputs: [
  22291. { name: 'color', type: 'vec3' },
  22292. { name: 'exposure', type: 'float' }
  22293. ]
  22294. } );
  22295. /**
  22296. * Reinhard tone mapping.
  22297. *
  22298. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  22299. *
  22300. * @method
  22301. * @param {Node<vec3>} color - The color that should be tone mapped.
  22302. * @param {Node<float>} exposure - The exposure.
  22303. * @return {Node<vec3>} The tone mapped color.
  22304. */
  22305. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22306. color = color.mul( exposure );
  22307. return color.div( color.add( 1.0 ) ).clamp();
  22308. } ).setLayout( {
  22309. name: 'reinhardToneMapping',
  22310. type: 'vec3',
  22311. inputs: [
  22312. { name: 'color', type: 'vec3' },
  22313. { name: 'exposure', type: 'float' }
  22314. ]
  22315. } );
  22316. /**
  22317. * Cineon tone mapping.
  22318. *
  22319. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  22320. *
  22321. * @method
  22322. * @param {Node<vec3>} color - The color that should be tone mapped.
  22323. * @param {Node<float>} exposure - The exposure.
  22324. * @return {Node<vec3>} The tone mapped color.
  22325. */
  22326. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22327. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  22328. color = color.mul( exposure );
  22329. color = color.sub( 0.004 ).max( 0.0 );
  22330. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  22331. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  22332. return a.div( b ).pow( 2.2 );
  22333. } ).setLayout( {
  22334. name: 'cineonToneMapping',
  22335. type: 'vec3',
  22336. inputs: [
  22337. { name: 'color', type: 'vec3' },
  22338. { name: 'exposure', type: 'float' }
  22339. ]
  22340. } );
  22341. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  22342. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  22343. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  22344. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  22345. return a.div( b );
  22346. } );
  22347. /**
  22348. * ACESFilmic tone mapping.
  22349. *
  22350. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  22351. *
  22352. * @method
  22353. * @param {Node<vec3>} color - The color that should be tone mapped.
  22354. * @param {Node<float>} exposure - The exposure.
  22355. * @return {Node<vec3>} The tone mapped color.
  22356. */
  22357. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22358. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  22359. const ACESInputMat = mat3(
  22360. 0.59719, 0.35458, 0.04823,
  22361. 0.07600, 0.90834, 0.01566,
  22362. 0.02840, 0.13383, 0.83777
  22363. );
  22364. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  22365. const ACESOutputMat = mat3(
  22366. 1.60475, - 0.53108, - 0.07367,
  22367. - 0.10208, 1.10813, - 0.00605,
  22368. - 0.00327, - 0.07276, 1.07602
  22369. );
  22370. color = color.mul( exposure ).div( 0.6 );
  22371. color = ACESInputMat.mul( color );
  22372. // Apply RRT and ODT
  22373. color = RRTAndODTFit( color );
  22374. color = ACESOutputMat.mul( color );
  22375. // Clamp to [0, 1]
  22376. return color.clamp();
  22377. } ).setLayout( {
  22378. name: 'acesFilmicToneMapping',
  22379. type: 'vec3',
  22380. inputs: [
  22381. { name: 'color', type: 'vec3' },
  22382. { name: 'exposure', type: 'float' }
  22383. ]
  22384. } );
  22385. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) );
  22386. const LINEAR_SRGB_TO_LINEAR_REC2020 = /*@__PURE__*/ mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) );
  22387. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  22388. const x = vec3( x_immutable ).toVar();
  22389. const x2 = vec3( x.mul( x ) ).toVar();
  22390. const x4 = vec3( x2.mul( x2 ) ).toVar();
  22391. return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) );
  22392. } );
  22393. /**
  22394. * AgX tone mapping.
  22395. *
  22396. * @method
  22397. * @param {Node<vec3>} color - The color that should be tone mapped.
  22398. * @param {Node<float>} exposure - The exposure.
  22399. * @return {Node<vec3>} The tone mapped color.
  22400. */
  22401. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22402. const colortone = vec3( color ).toVar();
  22403. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  22404. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  22405. const AgxMinEv = float( - 12.47393 );
  22406. const AgxMaxEv = float( 4.026069 );
  22407. colortone.mulAssign( exposure );
  22408. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  22409. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  22410. colortone.assign( max$1( colortone, 1e-10 ) );
  22411. colortone.assign( log2( colortone ) );
  22412. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  22413. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22414. colortone.assign( agxDefaultContrastApprox( colortone ) );
  22415. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  22416. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  22417. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  22418. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22419. return colortone;
  22420. } ).setLayout( {
  22421. name: 'agxToneMapping',
  22422. type: 'vec3',
  22423. inputs: [
  22424. { name: 'color', type: 'vec3' },
  22425. { name: 'exposure', type: 'float' }
  22426. ]
  22427. } );
  22428. /**
  22429. * Neutral tone mapping.
  22430. *
  22431. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  22432. *
  22433. * @method
  22434. * @param {Node<vec3>} color - The color that should be tone mapped.
  22435. * @param {Node<float>} exposure - The exposure.
  22436. * @return {Node<vec3>} The tone mapped color.
  22437. */
  22438. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22439. const StartCompression = float( 0.8 - 0.04 );
  22440. const Desaturation = float( 0.15 );
  22441. color = color.mul( exposure );
  22442. const x = min$1( color.r, min$1( color.g, color.b ) );
  22443. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  22444. color.subAssign( offset );
  22445. const peak = max$1( color.r, max$1( color.g, color.b ) );
  22446. If( peak.lessThan( StartCompression ), () => {
  22447. return color;
  22448. } );
  22449. const d = sub( 1, StartCompression );
  22450. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  22451. color.mulAssign( newPeak.div( peak ) );
  22452. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  22453. return mix( color, vec3( newPeak ), g );
  22454. } ).setLayout( {
  22455. name: 'neutralToneMapping',
  22456. type: 'vec3',
  22457. inputs: [
  22458. { name: 'color', type: 'vec3' },
  22459. { name: 'exposure', type: 'float' }
  22460. ]
  22461. } );
  22462. /** @module CodeNode **/
  22463. /**
  22464. * This class represents native code sections. It is the base
  22465. * class for modules like {@link FunctionNode} which allows to implement
  22466. * functions with native shader languages.
  22467. *
  22468. * @augments Node
  22469. */
  22470. class CodeNode extends Node {
  22471. static get type() {
  22472. return 'CodeNode';
  22473. }
  22474. /**
  22475. * Constructs a new code node.
  22476. *
  22477. * @param {String} [code=''] - The native code.
  22478. * @param {Array<Node>} [includes=[]] - An array of includes.
  22479. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22480. */
  22481. constructor( code = '', includes = [], language = '' ) {
  22482. super( 'code' );
  22483. /**
  22484. * This flag can be used for type testing.
  22485. *
  22486. * @type {Boolean}
  22487. * @readonly
  22488. * @default true
  22489. */
  22490. this.isCodeNode = true;
  22491. /**
  22492. * The native code.
  22493. *
  22494. * @type {String}
  22495. * @default ''
  22496. */
  22497. this.code = code;
  22498. /**
  22499. * An array of includes
  22500. *
  22501. * @type {Array<Node>}
  22502. * @default []
  22503. */
  22504. this.includes = includes;
  22505. /**
  22506. * The used language.
  22507. *
  22508. * @type {('js'|'wgsl'|'glsl')}
  22509. * @default ''
  22510. */
  22511. this.language = language;
  22512. }
  22513. /**
  22514. * The method is overwritten so it always returns `true`.
  22515. *
  22516. * @return {Boolean} Whether this node is global or not.
  22517. */
  22518. isGlobal() {
  22519. return true;
  22520. }
  22521. /**
  22522. * Sets the includes of this code node.
  22523. *
  22524. * @param {Array<Node>} includes - The includes to set.
  22525. * @return {CodeNode} A reference to this node.
  22526. */
  22527. setIncludes( includes ) {
  22528. this.includes = includes;
  22529. return this;
  22530. }
  22531. /**
  22532. * Returns the includes of this code node.
  22533. *
  22534. * @param {NodeBuilder} builder - The current node builder.
  22535. * @return {Array<Node>} The includes.
  22536. */
  22537. getIncludes( /*builder*/ ) {
  22538. return this.includes;
  22539. }
  22540. generate( builder ) {
  22541. const includes = this.getIncludes( builder );
  22542. for ( const include of includes ) {
  22543. include.build( builder );
  22544. }
  22545. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  22546. nodeCode.code = this.code;
  22547. return nodeCode.code;
  22548. }
  22549. serialize( data ) {
  22550. super.serialize( data );
  22551. data.code = this.code;
  22552. data.language = this.language;
  22553. }
  22554. deserialize( data ) {
  22555. super.deserialize( data );
  22556. this.code = data.code;
  22557. this.language = data.language;
  22558. }
  22559. }
  22560. /**
  22561. * TSL function for creating a code node.
  22562. *
  22563. * @function
  22564. * @param {String} [code=''] - The native code.
  22565. * @param {Array<Node>} [includes=[]] - An array of includes.
  22566. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22567. * @returns {CodeNode}
  22568. */
  22569. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  22570. /**
  22571. * TSL function for creating a JS code node.
  22572. *
  22573. * @function
  22574. * @param {String} src - The native code.
  22575. * @param {Array<Node>} includes - An array of includes.
  22576. * @returns {CodeNode}
  22577. */
  22578. const js = ( src, includes ) => code( src, includes, 'js' );
  22579. /**
  22580. * TSL function for creating a WGSL code node.
  22581. *
  22582. * @function
  22583. * @param {String} src - The native code.
  22584. * @param {Array<Node>} includes - An array of includes.
  22585. * @returns {CodeNode}
  22586. */
  22587. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  22588. /**
  22589. * TSL function for creating a GLSL code node.
  22590. *
  22591. * @function
  22592. * @param {String} src - The native code.
  22593. * @param {Array<Node>} includes - An array of includes.
  22594. * @returns {CodeNode}
  22595. */
  22596. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  22597. /**
  22598. * This class represents a native shader function. It can be used to implement
  22599. * certain aspects of a node material with native shader code. There are two predefined
  22600. * TSL functions for easier usage.
  22601. *
  22602. * - `wgslFn`: Creates a WGSL function node.
  22603. * - `glslFn`: Creates a GLSL function node.
  22604. *
  22605. * A basic example with one include looks like so:
  22606. *
  22607. * ```js
  22608. * const desaturateWGSLFn = wgslFn( `
  22609. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  22610. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  22611. * return vec3<f32>( dot( lum, color ) );
  22612. * }`
  22613. *);
  22614. * const someWGSLFn = wgslFn( `
  22615. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  22616. * return desaturate( color );
  22617. * }
  22618. * `, [ desaturateWGSLFn ] );
  22619. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  22620. *```
  22621. * @augments CodeNode
  22622. */
  22623. class FunctionNode extends CodeNode {
  22624. static get type() {
  22625. return 'FunctionNode';
  22626. }
  22627. /**
  22628. * Constructs a new function node.
  22629. *
  22630. * @param {String} [code=''] - The native code.
  22631. * @param {Array<Node>} [includes=[]] - An array of includes.
  22632. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22633. */
  22634. constructor( code = '', includes = [], language = '' ) {
  22635. super( code, includes, language );
  22636. }
  22637. getNodeType( builder ) {
  22638. return this.getNodeFunction( builder ).type;
  22639. }
  22640. /**
  22641. * Returns the inputs of this function node.
  22642. *
  22643. * @param {NodeBuilder} builder - The current node builder.
  22644. * @return {Array<NodeFunctionInput>} The inputs.
  22645. */
  22646. getInputs( builder ) {
  22647. return this.getNodeFunction( builder ).inputs;
  22648. }
  22649. /**
  22650. * Returns the node function for this function node.
  22651. *
  22652. * @param {NodeBuilder} builder - The current node builder.
  22653. * @return {NodeFunction} The node function.
  22654. */
  22655. getNodeFunction( builder ) {
  22656. const nodeData = builder.getDataFromNode( this );
  22657. let nodeFunction = nodeData.nodeFunction;
  22658. if ( nodeFunction === undefined ) {
  22659. nodeFunction = builder.parser.parseFunction( this.code );
  22660. nodeData.nodeFunction = nodeFunction;
  22661. }
  22662. return nodeFunction;
  22663. }
  22664. generate( builder, output ) {
  22665. super.generate( builder );
  22666. const nodeFunction = this.getNodeFunction( builder );
  22667. const name = nodeFunction.name;
  22668. const type = nodeFunction.type;
  22669. const nodeCode = builder.getCodeFromNode( this, type );
  22670. if ( name !== '' ) {
  22671. // use a custom property name
  22672. nodeCode.name = name;
  22673. }
  22674. const propertyName = builder.getPropertyName( nodeCode );
  22675. const code = this.getNodeFunction( builder ).getCode( propertyName );
  22676. nodeCode.code = code + '\n';
  22677. if ( output === 'property' ) {
  22678. return propertyName;
  22679. } else {
  22680. return builder.format( `${ propertyName }()`, type, output );
  22681. }
  22682. }
  22683. }
  22684. const nativeFn = ( code, includes = [], language = '' ) => {
  22685. for ( let i = 0; i < includes.length; i ++ ) {
  22686. const include = includes[ i ];
  22687. // TSL Function: glslFn, wgslFn
  22688. if ( typeof include === 'function' ) {
  22689. includes[ i ] = include.functionNode;
  22690. }
  22691. }
  22692. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  22693. const fn = ( ...params ) => functionNode.call( ...params );
  22694. fn.functionNode = functionNode;
  22695. return fn;
  22696. };
  22697. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  22698. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  22699. /** @module ScriptableValueNode **/
  22700. /**
  22701. * `ScriptableNode` uses this class to manage script inputs and outputs.
  22702. *
  22703. * @augments Node
  22704. */
  22705. class ScriptableValueNode extends Node {
  22706. static get type() {
  22707. return 'ScriptableValueNode';
  22708. }
  22709. /**
  22710. * Constructs a new scriptable node.
  22711. *
  22712. * @param {Any} [value=null] - The value.
  22713. */
  22714. constructor( value = null ) {
  22715. super();
  22716. /**
  22717. * A reference to the value.
  22718. *
  22719. * @private
  22720. * @default null
  22721. */
  22722. this._value = value;
  22723. /**
  22724. * Depending on the type of `_value`, this property might cache parsed data.
  22725. *
  22726. * @private
  22727. * @default null
  22728. */
  22729. this._cache = null;
  22730. /**
  22731. * If this node represents an input, this property represents the input type.
  22732. *
  22733. * @type {String?}
  22734. * @default null
  22735. */
  22736. this.inputType = null;
  22737. /**
  22738. * If this node represents an output, this property represents the output type.
  22739. *
  22740. * @type {String?}
  22741. * @default null
  22742. */
  22743. this.outputType = null;
  22744. /**
  22745. * An event dispatcher for managing events.
  22746. *
  22747. * @type {EventDispatcher}
  22748. */
  22749. this.events = new EventDispatcher();
  22750. /**
  22751. * This flag can be used for type testing.
  22752. *
  22753. * @type {Boolean}
  22754. * @readonly
  22755. * @default true
  22756. */
  22757. this.isScriptableValueNode = true;
  22758. }
  22759. /**
  22760. * Whether this node represents an output or not.
  22761. *
  22762. * @type {Boolean}
  22763. * @readonly
  22764. * @default true
  22765. */
  22766. get isScriptableOutputNode() {
  22767. return this.outputType !== null;
  22768. }
  22769. set value( val ) {
  22770. if ( this._value === val ) return;
  22771. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  22772. URL.revokeObjectURL( this._cache );
  22773. this._cache = null;
  22774. }
  22775. this._value = val;
  22776. this.events.dispatchEvent( { type: 'change' } );
  22777. this.refresh();
  22778. }
  22779. /**
  22780. * The node's value.
  22781. *
  22782. * @type {Any}
  22783. */
  22784. get value() {
  22785. return this._value;
  22786. }
  22787. /**
  22788. * Dispatches the `refresh` event.
  22789. */
  22790. refresh() {
  22791. this.events.dispatchEvent( { type: 'refresh' } );
  22792. }
  22793. /**
  22794. * The `value` property usually represents a node or even binary data in form of array buffers.
  22795. * In this case, this method tries to return the actual value behind the complex type.
  22796. *
  22797. * @return {Any} The value.
  22798. */
  22799. getValue() {
  22800. const value = this.value;
  22801. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  22802. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  22803. } else if ( value && value.value !== null && value.value !== undefined && (
  22804. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  22805. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  22806. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  22807. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  22808. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  22809. ( this.inputType === 'Color' && value.value.isColor ) ||
  22810. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  22811. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  22812. ) ) {
  22813. return value.value;
  22814. }
  22815. return this._cache || value;
  22816. }
  22817. /**
  22818. * Overwritten since the node type is inferred from the value.
  22819. *
  22820. * @param {NodeBuilder} builder - The current node builder.
  22821. * @return {String} The node type.
  22822. */
  22823. getNodeType( builder ) {
  22824. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  22825. }
  22826. setup() {
  22827. return this.value && this.value.isNode ? this.value : float();
  22828. }
  22829. serialize( data ) {
  22830. super.serialize( data );
  22831. if ( this.value !== null ) {
  22832. if ( this.inputType === 'ArrayBuffer' ) {
  22833. data.value = arrayBufferToBase64( this.value );
  22834. } else {
  22835. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  22836. }
  22837. } else {
  22838. data.value = null;
  22839. }
  22840. data.inputType = this.inputType;
  22841. data.outputType = this.outputType;
  22842. }
  22843. deserialize( data ) {
  22844. super.deserialize( data );
  22845. let value = null;
  22846. if ( data.value !== null ) {
  22847. if ( data.inputType === 'ArrayBuffer' ) {
  22848. value = base64ToArrayBuffer( data.value );
  22849. } else if ( data.inputType === 'Texture' ) {
  22850. value = data.meta.textures[ data.value ];
  22851. } else {
  22852. value = data.meta.nodes[ data.value ] || null;
  22853. }
  22854. }
  22855. this.value = value;
  22856. this.inputType = data.inputType;
  22857. this.outputType = data.outputType;
  22858. }
  22859. }
  22860. /**
  22861. * TSL function for creating a scriptable value node.
  22862. *
  22863. * @function
  22864. * @param {Any} [value=null] - The value.
  22865. * @returns {ScriptableValueNode}
  22866. */
  22867. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  22868. /** @module ScriptableNode **/
  22869. /**
  22870. * A Map-like data structure for managing resources of scriptable nodes.
  22871. *
  22872. * @augments Map
  22873. */
  22874. class Resources extends Map {
  22875. get( key, callback = null, ...params ) {
  22876. if ( this.has( key ) ) return super.get( key );
  22877. if ( callback !== null ) {
  22878. const value = callback( ...params );
  22879. this.set( key, value );
  22880. return value;
  22881. }
  22882. }
  22883. }
  22884. class Parameters {
  22885. constructor( scriptableNode ) {
  22886. this.scriptableNode = scriptableNode;
  22887. }
  22888. get parameters() {
  22889. return this.scriptableNode.parameters;
  22890. }
  22891. get layout() {
  22892. return this.scriptableNode.getLayout();
  22893. }
  22894. getInputLayout( id ) {
  22895. return this.scriptableNode.getInputLayout( id );
  22896. }
  22897. get( name ) {
  22898. const param = this.parameters[ name ];
  22899. const value = param ? param.getValue() : null;
  22900. return value;
  22901. }
  22902. }
  22903. /**
  22904. * Defines the resouces (e.g. namespaces) of scriptable nodes.
  22905. *
  22906. * @type {Resources}
  22907. */
  22908. const ScriptableNodeResources = new Resources();
  22909. /**
  22910. * This type of node allows to implement nodes with custom scripts. The script
  22911. * section is represented as an instance of `CodeNode` written with JavaScript.
  22912. * The script itself must adhere to a specific structure.
  22913. *
  22914. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  22915. * - layout: The layout object defines the script's interface (inputs and outputs).
  22916. *
  22917. * ```js
  22918. * ScriptableNodeResources.set( 'TSL', TSL );
  22919. *
  22920. * const scriptableNode = scriptable( js( `
  22921. * layout = {
  22922. * outputType: 'node',
  22923. * elements: [
  22924. * { name: 'source', inputType: 'node' },
  22925. * ]
  22926. * };
  22927. *
  22928. * const { mul, oscSine } = TSL;
  22929. *
  22930. * function main() {
  22931. * const source = parameters.get( 'source' ) || float();
  22932. * return mul( source, oscSine() ) );
  22933. * }
  22934. *
  22935. * ` ) );
  22936. *
  22937. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  22938. *
  22939. * const material = new THREE.MeshBasicNodeMaterial();
  22940. * material.colorNode = scriptableNode;
  22941. * ```
  22942. *
  22943. * @augments Node
  22944. */
  22945. class ScriptableNode extends Node {
  22946. static get type() {
  22947. return 'ScriptableNode';
  22948. }
  22949. /**
  22950. * Constructs a new scriptable node.
  22951. *
  22952. * @param {CodeNode?} [codeNode=null] - The code node.
  22953. * @param {Object} [parameters={}] - The parameters definition.
  22954. */
  22955. constructor( codeNode = null, parameters = {} ) {
  22956. super();
  22957. /**
  22958. * The code node.
  22959. *
  22960. * @type {CodeNode?}
  22961. * @default null
  22962. */
  22963. this.codeNode = codeNode;
  22964. /**
  22965. * The parameters definition.
  22966. *
  22967. * @type {Object}
  22968. * @default {}
  22969. */
  22970. this.parameters = parameters;
  22971. this._local = new Resources();
  22972. this._output = scriptableValue();
  22973. this._outputs = {};
  22974. this._source = this.source;
  22975. this._method = null;
  22976. this._object = null;
  22977. this._value = null;
  22978. this._needsOutputUpdate = true;
  22979. this.onRefresh = this.onRefresh.bind( this );
  22980. /**
  22981. * This flag can be used for type testing.
  22982. *
  22983. * @type {Boolean}
  22984. * @readonly
  22985. * @default true
  22986. */
  22987. this.isScriptableNode = true;
  22988. }
  22989. /**
  22990. * The source code of the scriptable node.
  22991. *
  22992. * @type {String}
  22993. */
  22994. get source() {
  22995. return this.codeNode ? this.codeNode.code : '';
  22996. }
  22997. /**
  22998. * Sets the reference of a local script variable.
  22999. *
  23000. * @param {String} name - The variable name.
  23001. * @param {Object} value - The reference to set.
  23002. * @return {Resources} The resource map
  23003. */
  23004. setLocal( name, value ) {
  23005. return this._local.set( name, value );
  23006. }
  23007. /**
  23008. * Gets the value of a local script variable.
  23009. *
  23010. * @param {String} name - The variable name.
  23011. * @return {Object} The value.
  23012. */
  23013. getLocal( name ) {
  23014. return this._local.get( name );
  23015. }
  23016. /**
  23017. * Event listener for the `refresh` event.
  23018. */
  23019. onRefresh() {
  23020. this._refresh();
  23021. }
  23022. /**
  23023. * Returns an input from the layout with the given id/name.
  23024. *
  23025. * @param {String} id - The id/name of the input.
  23026. * @return {Object} The element entry.
  23027. */
  23028. getInputLayout( id ) {
  23029. for ( const element of this.getLayout() ) {
  23030. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  23031. return element;
  23032. }
  23033. }
  23034. }
  23035. /**
  23036. * Returns an output from the layout with the given id/name.
  23037. *
  23038. * @param {String} id - The id/name of the output.
  23039. * @return {Object} The element entry.
  23040. */
  23041. getOutputLayout( id ) {
  23042. for ( const element of this.getLayout() ) {
  23043. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  23044. return element;
  23045. }
  23046. }
  23047. }
  23048. /**
  23049. * Defines a script output for the given name and value.
  23050. *
  23051. * @param {String} name - The name of the output.
  23052. * @param {Node} value - The node value.
  23053. * @return {ScriptableNode} A reference to this node.
  23054. */
  23055. setOutput( name, value ) {
  23056. const outputs = this._outputs;
  23057. if ( outputs[ name ] === undefined ) {
  23058. outputs[ name ] = scriptableValue( value );
  23059. } else {
  23060. outputs[ name ].value = value;
  23061. }
  23062. return this;
  23063. }
  23064. /**
  23065. * Returns a script output for the given name.
  23066. *
  23067. * @param {String} name - The name of the output.
  23068. * @return {ScriptableValueNode} The node value.
  23069. */
  23070. getOutput( name ) {
  23071. return this._outputs[ name ];
  23072. }
  23073. /**
  23074. * Returns a paramater for the given name
  23075. *
  23076. * @param {String} name - The name of the parameter.
  23077. * @return {ScriptableValueNode} The node value.
  23078. */
  23079. getParameter( name ) {
  23080. return this.parameters[ name ];
  23081. }
  23082. /**
  23083. * Sets a value for the given parameter name.
  23084. *
  23085. * @param {String} name - The parameter name.
  23086. * @param {Any} value - The parameter value.
  23087. * @return {ScriptableNode} A reference to this node.
  23088. */
  23089. setParameter( name, value ) {
  23090. const parameters = this.parameters;
  23091. if ( value && value.isScriptableNode ) {
  23092. this.deleteParameter( name );
  23093. parameters[ name ] = value;
  23094. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  23095. } else if ( value && value.isScriptableValueNode ) {
  23096. this.deleteParameter( name );
  23097. parameters[ name ] = value;
  23098. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23099. } else if ( parameters[ name ] === undefined ) {
  23100. parameters[ name ] = scriptableValue( value );
  23101. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23102. } else {
  23103. parameters[ name ].value = value;
  23104. }
  23105. return this;
  23106. }
  23107. /**
  23108. * Returns the value of this node which is the value of
  23109. * the default output.
  23110. *
  23111. * @return {Node} The value.
  23112. */
  23113. getValue() {
  23114. return this.getDefaultOutput().getValue();
  23115. }
  23116. /**
  23117. * Deletes a parameter from the script.
  23118. *
  23119. * @param {String} name - The parameter to remove.
  23120. * @return {ScriptableNode} A reference to this node.
  23121. */
  23122. deleteParameter( name ) {
  23123. let valueNode = this.parameters[ name ];
  23124. if ( valueNode ) {
  23125. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23126. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  23127. }
  23128. return this;
  23129. }
  23130. /**
  23131. * Deletes all parameters from the script.
  23132. *
  23133. * @return {ScriptableNode} A reference to this node.
  23134. */
  23135. clearParameters() {
  23136. for ( const name of Object.keys( this.parameters ) ) {
  23137. this.deleteParameter( name );
  23138. }
  23139. this.needsUpdate = true;
  23140. return this;
  23141. }
  23142. /**
  23143. * Calls a function from the script.
  23144. *
  23145. * @param {String} name - The function name.
  23146. * @param {...Any} params - A list of parameters.
  23147. * @return {Any} The result of the function call.
  23148. */
  23149. call( name, ...params ) {
  23150. const object = this.getObject();
  23151. const method = object[ name ];
  23152. if ( typeof method === 'function' ) {
  23153. return method( ...params );
  23154. }
  23155. }
  23156. /**
  23157. * Asynchronously calls a function from the script.
  23158. *
  23159. * @param {String} name - The function name.
  23160. * @param {...Any} params - A list of parameters.
  23161. * @return {Any} The result of the function call.
  23162. */
  23163. async callAsync( name, ...params ) {
  23164. const object = this.getObject();
  23165. const method = object[ name ];
  23166. if ( typeof method === 'function' ) {
  23167. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  23168. }
  23169. }
  23170. /**
  23171. * Overwritten since the node types is inferred from the script's output.
  23172. *
  23173. * @param {NodeBuilder} builder - The current node builder
  23174. * @return {String} The node type.
  23175. */
  23176. getNodeType( builder ) {
  23177. return this.getDefaultOutputNode().getNodeType( builder );
  23178. }
  23179. /**
  23180. * Refreshes the script node.
  23181. *
  23182. * @param {String?} [output=null] - An optional output.
  23183. */
  23184. refresh( output = null ) {
  23185. if ( output !== null ) {
  23186. this.getOutput( output ).refresh();
  23187. } else {
  23188. this._refresh();
  23189. }
  23190. }
  23191. /**
  23192. * Returns an object representation of the script.
  23193. *
  23194. * @return {Object} The result object.
  23195. */
  23196. getObject() {
  23197. if ( this.needsUpdate ) this.dispose();
  23198. if ( this._object !== null ) return this._object;
  23199. //
  23200. const refresh = () => this.refresh();
  23201. const setOutput = ( id, value ) => this.setOutput( id, value );
  23202. const parameters = new Parameters( this );
  23203. const THREE = ScriptableNodeResources.get( 'THREE' );
  23204. const TSL = ScriptableNodeResources.get( 'TSL' );
  23205. const method = this.getMethod();
  23206. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  23207. this._object = method( ...params );
  23208. const layout = this._object.layout;
  23209. if ( layout ) {
  23210. if ( layout.cache === false ) {
  23211. this._local.clear();
  23212. }
  23213. // default output
  23214. this._output.outputType = layout.outputType || null;
  23215. if ( Array.isArray( layout.elements ) ) {
  23216. for ( const element of layout.elements ) {
  23217. const id = element.id || element.name;
  23218. if ( element.inputType ) {
  23219. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  23220. this.getParameter( id ).inputType = element.inputType;
  23221. }
  23222. if ( element.outputType ) {
  23223. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  23224. this.getOutput( id ).outputType = element.outputType;
  23225. }
  23226. }
  23227. }
  23228. }
  23229. return this._object;
  23230. }
  23231. deserialize( data ) {
  23232. super.deserialize( data );
  23233. for ( const name in this.parameters ) {
  23234. let valueNode = this.parameters[ name ];
  23235. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23236. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  23237. }
  23238. }
  23239. /**
  23240. * Returns the layout of the script.
  23241. *
  23242. * @return {Object} The script's layout.
  23243. */
  23244. getLayout() {
  23245. return this.getObject().layout;
  23246. }
  23247. /**
  23248. * Returns default node output of the script.
  23249. *
  23250. * @return {Node} The default node output.
  23251. */
  23252. getDefaultOutputNode() {
  23253. const output = this.getDefaultOutput().value;
  23254. if ( output && output.isNode ) {
  23255. return output;
  23256. }
  23257. return float();
  23258. }
  23259. /**
  23260. * Returns default output of the script.
  23261. *
  23262. * @return {ScriptableValueNode} The default output.
  23263. */
  23264. getDefaultOutput() {
  23265. return this._exec()._output;
  23266. }
  23267. /**
  23268. * Returns a function created from the node's script.
  23269. *
  23270. * @return {Function} The function representing the node's code.
  23271. */
  23272. getMethod() {
  23273. if ( this.needsUpdate ) this.dispose();
  23274. if ( this._method !== null ) return this._method;
  23275. //
  23276. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  23277. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  23278. const properties = interfaceProps.join( ', ' );
  23279. const declarations = 'var ' + properties + '; var output = {};\n';
  23280. const returns = '\nreturn { ...output, ' + properties + ' };';
  23281. const code = declarations + this.codeNode.code + returns;
  23282. //
  23283. this._method = new Function( ...parametersProps, code );
  23284. return this._method;
  23285. }
  23286. /**
  23287. * Frees all internal resources.
  23288. */
  23289. dispose() {
  23290. if ( this._method === null ) return;
  23291. if ( this._object && typeof this._object.dispose === 'function' ) {
  23292. this._object.dispose();
  23293. }
  23294. this._method = null;
  23295. this._object = null;
  23296. this._source = null;
  23297. this._value = null;
  23298. this._needsOutputUpdate = true;
  23299. this._output.value = null;
  23300. this._outputs = {};
  23301. }
  23302. setup() {
  23303. return this.getDefaultOutputNode();
  23304. }
  23305. getCacheKey( force ) {
  23306. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  23307. for ( const param in this.parameters ) {
  23308. values.push( this.parameters[ param ].getCacheKey( force ) );
  23309. }
  23310. return hashArray( values );
  23311. }
  23312. set needsUpdate( value ) {
  23313. if ( value === true ) this.dispose();
  23314. }
  23315. get needsUpdate() {
  23316. return this.source !== this._source;
  23317. }
  23318. /**
  23319. * Executes the `main` function of the script.
  23320. *
  23321. * @private
  23322. * @return {ScriptableNode} A reference to this node.
  23323. */
  23324. _exec() {
  23325. if ( this.codeNode === null ) return this;
  23326. if ( this._needsOutputUpdate === true ) {
  23327. this._value = this.call( 'main' );
  23328. this._needsOutputUpdate = false;
  23329. }
  23330. this._output.value = this._value;
  23331. return this;
  23332. }
  23333. /**
  23334. * Executes the refresh.
  23335. *
  23336. * @private
  23337. */
  23338. _refresh() {
  23339. this.needsUpdate = true;
  23340. this._exec();
  23341. this._output.refresh();
  23342. }
  23343. }
  23344. /**
  23345. * TSL function for creating a scriptable node.
  23346. *
  23347. * @function
  23348. * @param {CodeNode?} [codeNode=null] - The code node.
  23349. * @param {Object} [parameters={}] - The parameters definition.
  23350. * @returns {ScriptableNode}
  23351. */
  23352. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  23353. /** @module Fog **/
  23354. /**
  23355. * Returns a node that represents the `z` coordinate in view space
  23356. * for the current fragment. It's a different representation of the
  23357. * default depth value.
  23358. *
  23359. * This value can be part of a computation that defines how the fog
  23360. * density increases when moving away from the camera.
  23361. *
  23362. * @param {NodeBuilder} builder - The current node builder.
  23363. * @return {Node} The viewZ node.
  23364. */
  23365. function getViewZNode( builder ) {
  23366. let viewZ;
  23367. const getViewZ = builder.context.getViewZ;
  23368. if ( getViewZ !== undefined ) {
  23369. viewZ = getViewZ( this );
  23370. }
  23371. return ( viewZ || positionView.z ).negate();
  23372. }
  23373. /**
  23374. * Constructs a new range factor node.
  23375. *
  23376. * @function
  23377. * @param {Node} near - Defines the near value.
  23378. * @param {Node} far - Defines the far value.
  23379. */
  23380. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  23381. const viewZ = getViewZNode( builder );
  23382. return smoothstep( near, far, viewZ );
  23383. } );
  23384. /**
  23385. * Represents an exponential squared fog. This type of fog gives
  23386. * a clear view near the camera and a faster than exponentially
  23387. * densening fog farther from the camera.
  23388. *
  23389. * @function
  23390. * @param {Node} density - Defines the fog density.
  23391. */
  23392. const densityFogFactor = Fn( ( [ density ], builder ) => {
  23393. const viewZ = getViewZNode( builder );
  23394. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  23395. } );
  23396. /**
  23397. * This class can be used to configure a fog for the scene.
  23398. * Nodes of this type are assigned to `Scene.fogNode`.
  23399. *
  23400. * @function
  23401. * @param {Node} color - Defines the color of the fog.
  23402. * @param {Node} factor - Defines how the fog is factored in the scene.
  23403. */
  23404. const fog = Fn( ( [ color, factor ] ) => {
  23405. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  23406. } );
  23407. // Deprecated
  23408. function rangeFog( color, near, far ) { // @deprecated, r171
  23409. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  23410. return fog( color, rangeFogFactor( near, far ) );
  23411. }
  23412. function densityFog( color, density ) { // @deprecated, r171
  23413. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  23414. return fog( color, densityFogFactor( density ) );
  23415. }
  23416. /** @module RangeNode **/
  23417. let min = null;
  23418. let max = null;
  23419. /**
  23420. * `RangeNode` generates random instanced attribute data in a defined range.
  23421. * An exemplary use case for this utility node is to generate random per-instance
  23422. * colors:
  23423. * ```js
  23424. * const material = new MeshBasicNodeMaterial();
  23425. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  23426. * const mesh = new InstancedMesh( geometry, material, count );
  23427. * ```
  23428. * @augments Node
  23429. */
  23430. class RangeNode extends Node {
  23431. static get type() {
  23432. return 'RangeNode';
  23433. }
  23434. /**
  23435. * Constructs a new range node.
  23436. *
  23437. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23438. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23439. */
  23440. constructor( minNode = float(), maxNode = float() ) {
  23441. super();
  23442. /**
  23443. * A node defining the lower bound of the range.
  23444. *
  23445. * @type {Node<any>}
  23446. * @default float()
  23447. */
  23448. this.minNode = minNode;
  23449. /**
  23450. * A node defining the upper bound of the range.
  23451. *
  23452. * @type {Node<any>}
  23453. * @default float()
  23454. */
  23455. this.maxNode = maxNode;
  23456. }
  23457. /**
  23458. * Returns the vector length which is computed based on the range definition.
  23459. *
  23460. * @param {NodeBuilder} builder - The current node builder.
  23461. * @return {Number} The vector length.
  23462. */
  23463. getVectorLength( builder ) {
  23464. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  23465. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  23466. return minLength > maxLength ? minLength : maxLength;
  23467. }
  23468. /**
  23469. * This method is overwritten since the node type is inferred from range definition.
  23470. *
  23471. * @param {NodeBuilder} builder - The current node builder.
  23472. * @return {String} The node type.
  23473. */
  23474. getNodeType( builder ) {
  23475. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  23476. }
  23477. setup( builder ) {
  23478. const object = builder.object;
  23479. let output = null;
  23480. if ( object.count > 1 ) {
  23481. const minValue = this.minNode.value;
  23482. const maxValue = this.maxNode.value;
  23483. const minLength = builder.getTypeLength( getValueType( minValue ) );
  23484. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  23485. min = min || new Vector4();
  23486. max = max || new Vector4();
  23487. min.setScalar( 0 );
  23488. max.setScalar( 0 );
  23489. if ( minLength === 1 ) min.setScalar( minValue );
  23490. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  23491. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  23492. if ( maxLength === 1 ) max.setScalar( maxValue );
  23493. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  23494. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  23495. const stride = 4;
  23496. const length = stride * object.count;
  23497. const array = new Float32Array( length );
  23498. for ( let i = 0; i < length; i ++ ) {
  23499. const index = i % stride;
  23500. const minElementValue = min.getComponent( index );
  23501. const maxElementValue = max.getComponent( index );
  23502. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  23503. }
  23504. const nodeType = this.getNodeType( builder );
  23505. if ( object.count <= 4096 ) {
  23506. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  23507. } else {
  23508. // TODO: Improve anonymous buffer attribute creation removing this part
  23509. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  23510. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  23511. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  23512. }
  23513. } else {
  23514. output = float( 0 );
  23515. }
  23516. return output;
  23517. }
  23518. }
  23519. /**
  23520. * TSL function for creating a range node.
  23521. *
  23522. * @function
  23523. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23524. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23525. * @returns {RangeNode}
  23526. */
  23527. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  23528. /** @module ComputeBuiltinNode **/
  23529. /**
  23530. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  23531. * about the currently running dispatch and/or the device it is running on.
  23532. *
  23533. * This node can only be used with a WebGPU backend.
  23534. *
  23535. * @augments Node
  23536. */
  23537. class ComputeBuiltinNode extends Node {
  23538. static get type() {
  23539. return 'ComputeBuiltinNode';
  23540. }
  23541. /**
  23542. * Constructs a new compute builtin node.
  23543. *
  23544. * @param {String} builtinName - The built-in name.
  23545. * @param {String} nodeType - The node type.
  23546. */
  23547. constructor( builtinName, nodeType ) {
  23548. super( nodeType );
  23549. /**
  23550. * The built-in name.
  23551. *
  23552. * @private
  23553. * @type {String}
  23554. */
  23555. this._builtinName = builtinName;
  23556. }
  23557. /**
  23558. * This method is overwritten since hash is derived from the built-in name.
  23559. *
  23560. * @param {NodeBuilder} builder - The current node builder.
  23561. * @return {String} The hash.
  23562. */
  23563. getHash( builder ) {
  23564. return this.getBuiltinName( builder );
  23565. }
  23566. /**
  23567. * This method is overwritten since the node type is simply derived from `nodeType`..
  23568. *
  23569. * @param {NodeBuilder} builder - The current node builder.
  23570. * @return {String} The node type.
  23571. */
  23572. getNodeType( /*builder*/ ) {
  23573. return this.nodeType;
  23574. }
  23575. /**
  23576. * Sets the builtin name.
  23577. *
  23578. * @param {String} builtinName - The built-in name.
  23579. * @return {ComputeBuiltinNode} A reference to this node.
  23580. */
  23581. setBuiltinName( builtinName ) {
  23582. this._builtinName = builtinName;
  23583. return this;
  23584. }
  23585. /**
  23586. * Returns the builtin name.
  23587. *
  23588. * @param {NodeBuilder} builder - The current node builder.
  23589. * @return {String} The builtin name.
  23590. */
  23591. getBuiltinName( /*builder*/ ) {
  23592. return this._builtinName;
  23593. }
  23594. /**
  23595. * Whether the current node builder has the builtin or not.
  23596. *
  23597. * @param {NodeBuilder} builder - The current node builder.
  23598. */
  23599. hasBuiltin( builder ) {
  23600. builder.hasBuiltin( this._builtinName );
  23601. }
  23602. generate( builder, output ) {
  23603. const builtinName = this.getBuiltinName( builder );
  23604. const nodeType = this.getNodeType( builder );
  23605. if ( builder.shaderStage === 'compute' ) {
  23606. return builder.format( builtinName, nodeType, output );
  23607. } else {
  23608. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  23609. return builder.generateConst( nodeType );
  23610. }
  23611. }
  23612. serialize( data ) {
  23613. super.serialize( data );
  23614. data.global = this.global;
  23615. data._builtinName = this._builtinName;
  23616. }
  23617. deserialize( data ) {
  23618. super.deserialize( data );
  23619. this.global = data.global;
  23620. this._builtinName = data._builtinName;
  23621. }
  23622. }
  23623. /**
  23624. * TSL function for creating a compute builtin node.
  23625. *
  23626. * @function
  23627. * @param {String} name - The built-in name.
  23628. * @param {String} nodeType - The node type.
  23629. * @returns {ComputeBuiltinNode}
  23630. */
  23631. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  23632. /**
  23633. * TSL function for creating a `numWorkgroups` builtin node.
  23634. * Represents the number of workgroups dispatched by the compute shader.
  23635. * ```js
  23636. * // Run 512 invocations/threads with a workgroup size of 128.
  23637. * const computeFn = Fn(() => {
  23638. *
  23639. * // numWorkgroups.x = 4
  23640. * storageBuffer.element(0).assign(numWorkgroups.x)
  23641. *
  23642. * })().compute(512, [128]);
  23643. *
  23644. * // Run 512 invocations/threads with the default workgroup size of 64.
  23645. * const computeFn = Fn(() => {
  23646. *
  23647. * // numWorkgroups.x = 8
  23648. * storageBuffer.element(0).assign(numWorkgroups.x)
  23649. *
  23650. * })().compute(512);
  23651. * ```
  23652. *
  23653. * @function
  23654. * @returns {ComputeBuiltinNode<uvec3>}
  23655. */
  23656. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  23657. /**
  23658. * TSL function for creating a `workgroupId` builtin node.
  23659. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  23660. * ```js
  23661. * // Execute 12 compute threads with a workgroup size of 3.
  23662. * const computeFn = Fn( () => {
  23663. *
  23664. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  23665. *
  23666. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  23667. *
  23668. * } ).Else( () => {
  23669. *
  23670. * storageBuffer.element( instanceIndex ).assign( 0 );
  23671. *
  23672. * } );
  23673. *
  23674. * } )().compute( 12, [ 3 ] );
  23675. *
  23676. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  23677. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  23678. * ```
  23679. *
  23680. * @function
  23681. * @returns {ComputeBuiltinNode<uvec3>}
  23682. */
  23683. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  23684. /**
  23685. * TSL function for creating a `localId` builtin node. A non-linearized 3-dimensional
  23686. * representation of the current invocation's position within a 3D workgroup grid.
  23687. *
  23688. * @function
  23689. * @returns {ComputeBuiltinNode<uvec3>}
  23690. */
  23691. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  23692. /**
  23693. * TSL function for creating a `subgroupSize` builtin node. A device dependent variable
  23694. * that exposes the size of the current invocation's subgroup.
  23695. *
  23696. * @function
  23697. * @returns {ComputeBuiltinNode<uint>}
  23698. */
  23699. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  23700. /** @module BarrierNode **/
  23701. /**
  23702. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  23703. *
  23704. * This node can only be used with a WebGPU backend.
  23705. *
  23706. * @augments Node
  23707. */
  23708. class BarrierNode extends Node {
  23709. /**
  23710. * Constructs a new barrier node.
  23711. *
  23712. * @param {String} scope - The scope defines the behavior of the node.
  23713. */
  23714. constructor( scope ) {
  23715. super();
  23716. this.scope = scope;
  23717. }
  23718. generate( builder ) {
  23719. const { scope } = this;
  23720. const { renderer } = builder;
  23721. if ( renderer.backend.isWebGLBackend === true ) {
  23722. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  23723. } else {
  23724. builder.addLineFlowCode( `${scope}Barrier()`, this );
  23725. }
  23726. }
  23727. }
  23728. /**
  23729. * TSL function for creating a barrier node.
  23730. *
  23731. * @function
  23732. * @param {String} scope - The scope defines the behavior of the node..
  23733. * @returns {BarrierNode}
  23734. */
  23735. const barrier = nodeProxy( BarrierNode );
  23736. /**
  23737. * TSL function for creating a workgroup barrier. All compute shader
  23738. * invocations must wait for each invocation within a workgroup to
  23739. * complete before the barrier can be surpassed.
  23740. *
  23741. * @function
  23742. * @returns {BarrierNode}
  23743. */
  23744. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  23745. /**
  23746. * TSL function for creating a storage barrier. All invocations must
  23747. * wait for each access to variables within the 'storage' address space
  23748. * to complete before the barrier can be passed.
  23749. *
  23750. * @function
  23751. * @returns {BarrierNode}
  23752. */
  23753. const storageBarrier = () => barrier( 'storage' ).append();
  23754. /**
  23755. * TSL function for creating a texture barrier. All invocations must
  23756. * wait for each access to variables within the 'texture' address space
  23757. * to complete before the barrier can be passed.
  23758. *
  23759. * @function
  23760. * @returns {BarrierNode}
  23761. */
  23762. const textureBarrier = () => barrier( 'texture' ).append();
  23763. /** @module WorkgroupInfoNode **/
  23764. /**
  23765. * Represents an element of a 'workgroup' scoped buffer.
  23766. *
  23767. * @augments ArrayElementNode
  23768. */
  23769. class WorkgroupInfoElementNode extends ArrayElementNode {
  23770. /**
  23771. * Constructs a new workgroup info element node.
  23772. *
  23773. * @param {Node} workgroupInfoNode - The workgroup info node.
  23774. * @param {Node} indexNode - The index node that defines the element access.
  23775. */
  23776. constructor( workgroupInfoNode, indexNode ) {
  23777. super( workgroupInfoNode, indexNode );
  23778. /**
  23779. * This flag can be used for type testing.
  23780. *
  23781. * @type {Boolean}
  23782. * @readonly
  23783. * @default true
  23784. */
  23785. this.isWorkgroupInfoElementNode = true;
  23786. }
  23787. generate( builder, output ) {
  23788. let snippet;
  23789. const isAssignContext = builder.context.assign;
  23790. snippet = super.generate( builder );
  23791. if ( isAssignContext !== true ) {
  23792. const type = this.getNodeType( builder );
  23793. snippet = builder.format( snippet, type, output );
  23794. }
  23795. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  23796. return snippet;
  23797. }
  23798. }
  23799. /**
  23800. * A node allowing the user to create a 'workgroup' scoped buffer within the
  23801. * context of a compute shader. Typically, workgroup scoped buffers are
  23802. * created to hold data that is transfered from a global storage scope into
  23803. * a local workgroup scope. For invocations within a workgroup, data
  23804. * access speeds on 'workgroup' scoped buffers can be significantly faster
  23805. * than similar access operations on globally accessible storage buffers.
  23806. *
  23807. * This node can only be used with a WebGPU backend.
  23808. *
  23809. * @augments Node
  23810. */
  23811. class WorkgroupInfoNode extends Node {
  23812. /**
  23813. * Constructs a new buffer scoped to type scope.
  23814. *
  23815. * @param {String} scope - TODO.
  23816. * @param {String} bufferType - The data type of a 'workgroup' scoped buffer element.
  23817. * @param {Number} [bufferCount=0] - The number of elements in the buffer.
  23818. */
  23819. constructor( scope, bufferType, bufferCount = 0 ) {
  23820. super( bufferType );
  23821. /**
  23822. * The buffer type.
  23823. *
  23824. * @type {String}
  23825. */
  23826. this.bufferType = bufferType;
  23827. /**
  23828. * The buffer count.
  23829. *
  23830. * @type {Number}
  23831. * @default 0
  23832. */
  23833. this.bufferCount = bufferCount;
  23834. /**
  23835. * This flag can be used for type testing.
  23836. *
  23837. * @type {Boolean}
  23838. * @readonly
  23839. * @default true
  23840. */
  23841. this.isWorkgroupInfoNode = true;
  23842. /**
  23843. * The data type of the array buffer.
  23844. *
  23845. * @type {String}
  23846. */
  23847. this.elementType = bufferType;
  23848. /**
  23849. * TODO.
  23850. *
  23851. * @type {String}
  23852. */
  23853. this.scope = scope;
  23854. }
  23855. /**
  23856. * Sets the name/label of this node.
  23857. *
  23858. * @param {String} name - The name to set.
  23859. * @return {WorkgroupInfoNode} A reference to this node.
  23860. */
  23861. label( name ) {
  23862. this.name = name;
  23863. return this;
  23864. }
  23865. /**
  23866. * Sets the scope of this node.
  23867. *
  23868. * @param {String} scope - The scope to set.
  23869. * @return {WorkgroupInfoNode} A reference to this node.
  23870. */
  23871. setScope( scope ) {
  23872. this.scope = scope;
  23873. return this;
  23874. }
  23875. /**
  23876. * The data type of the array buffer.
  23877. *
  23878. * @return {String} The element type.
  23879. */
  23880. getElementType() {
  23881. return this.elementType;
  23882. }
  23883. /**
  23884. * Overwrites the default implementation since the input type
  23885. * is inferred from the scope.
  23886. *
  23887. * @param {NodeBuilder} builder - The current node builder.
  23888. * @return {String} The input type.
  23889. */
  23890. getInputType( /*builder*/ ) {
  23891. return `${this.scope}Array`;
  23892. }
  23893. /**
  23894. * This method can be used to access elements via an index node.
  23895. *
  23896. * @param {IndexNode} indexNode - indexNode.
  23897. * @return {WorkgroupInfoElementNode} A reference to an element.
  23898. */
  23899. element( indexNode ) {
  23900. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  23901. }
  23902. generate( builder ) {
  23903. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  23904. }
  23905. }
  23906. /**
  23907. * TSL function for creating a workgroup info node.
  23908. * Creates a new 'workgroup' scoped array buffer.
  23909. *
  23910. * @function
  23911. * @param {String} type - The data type of a 'workgroup' scoped buffer element.
  23912. * @param {Number} [count=0] - The number of elements in the buffer.
  23913. * @returns {WorkgroupInfoNode}
  23914. */
  23915. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  23916. /** @module AtomicFunctionNode **/
  23917. /**
  23918. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  23919. * within a shader. In an atomic function, any modifiation to an atomic variable will
  23920. * occur as an indivisble step with a defined order relative to other modifications.
  23921. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  23922. * atomic operations will not interfer with each other.
  23923. *
  23924. * This node can only be used with a WebGPU backend.
  23925. *
  23926. * @augments TempNode
  23927. */
  23928. class AtomicFunctionNode extends TempNode {
  23929. static get type() {
  23930. return 'AtomicFunctionNode';
  23931. }
  23932. /**
  23933. * Constructs a new atomic function node.
  23934. *
  23935. * @param {String} method - The signature of the atomic function to construct.
  23936. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  23937. * @param {Node} valueNode - The value that mutates the atomic variable.
  23938. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  23939. */
  23940. constructor( method, pointerNode, valueNode, storeNode = null ) {
  23941. super( 'uint' );
  23942. /**
  23943. * The signature of the atomic function to construct.
  23944. *
  23945. * @type {String}
  23946. */
  23947. this.method = method;
  23948. /**
  23949. * An atomic variable or element of an atomic buffer.
  23950. *
  23951. * @type {Node}
  23952. */
  23953. this.pointerNode = pointerNode;
  23954. /**
  23955. * A value that modifies the atomic variable.
  23956. *
  23957. * @type {Node}
  23958. */
  23959. this.valueNode = valueNode;
  23960. /**
  23961. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  23962. *
  23963. * @type {Node?}
  23964. * @default null
  23965. */
  23966. this.storeNode = storeNode;
  23967. }
  23968. /**
  23969. * Overwrites the default implementation to return the type of
  23970. * the pointer node.
  23971. *
  23972. * @param {NodeBuilder} builder - The current node builder.
  23973. * @return {String} The input type.
  23974. */
  23975. getInputType( builder ) {
  23976. return this.pointerNode.getNodeType( builder );
  23977. }
  23978. /**
  23979. * Overwritten since the node type is inferred from the input type.
  23980. *
  23981. * @param {NodeBuilder} builder - The current node builder.
  23982. * @return {String} The node type.
  23983. */
  23984. getNodeType( builder ) {
  23985. return this.getInputType( builder );
  23986. }
  23987. generate( builder ) {
  23988. const method = this.method;
  23989. const type = this.getNodeType( builder );
  23990. const inputType = this.getInputType( builder );
  23991. const a = this.pointerNode;
  23992. const b = this.valueNode;
  23993. const params = [];
  23994. params.push( `&${ a.build( builder, inputType ) }` );
  23995. params.push( b.build( builder, inputType ) );
  23996. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  23997. if ( this.storeNode !== null ) {
  23998. const varSnippet = this.storeNode.build( builder, inputType );
  23999. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  24000. } else {
  24001. builder.addLineFlowCode( methodSnippet, this );
  24002. }
  24003. }
  24004. }
  24005. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  24006. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  24007. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  24008. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  24009. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  24010. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  24011. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  24012. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  24013. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  24014. /**
  24015. * TSL function for creating an atomic function node.
  24016. *
  24017. * @function
  24018. * @param {String} method - The signature of the atomic function to construct.
  24019. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24020. * @param {Node} valueNode - The value that mutates the atomic variable.
  24021. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24022. * @returns {AtomicFunctionNode}
  24023. */
  24024. const atomicNode = nodeProxy( AtomicFunctionNode );
  24025. /**
  24026. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  24027. *
  24028. * @function
  24029. * @param {String} method - The signature of the atomic function to construct.
  24030. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24031. * @param {Node} valueNode - The value that mutates the atomic variable.
  24032. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24033. * @returns {AtomicFunctionNode}
  24034. */
  24035. const atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  24036. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  24037. node.append();
  24038. return node;
  24039. };
  24040. /**
  24041. * Stores a value in the atomic variable.
  24042. *
  24043. * @function
  24044. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24045. * @param {Node} valueNode - The value that mutates the atomic variable.
  24046. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24047. * @returns {AtomicFunctionNode}
  24048. */
  24049. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  24050. /**
  24051. * Increments the value stored in the atomic variable.
  24052. *
  24053. * @function
  24054. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24055. * @param {Node} valueNode - The value that mutates the atomic variable.
  24056. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24057. * @returns {AtomicFunctionNode}
  24058. */
  24059. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  24060. /**
  24061. * Decrements the value stored in the atomic variable.
  24062. *
  24063. * @function
  24064. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24065. * @param {Node} valueNode - The value that mutates the atomic variable.
  24066. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24067. * @returns {AtomicFunctionNode}
  24068. */
  24069. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  24070. /**
  24071. * Stores in an atomic variable the maximum between its current value and a parameter.
  24072. *
  24073. * @function
  24074. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24075. * @param {Node} valueNode - The value that mutates the atomic variable.
  24076. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24077. * @returns {AtomicFunctionNode}
  24078. */
  24079. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  24080. /**
  24081. * Stores in an atomic variable the minimum between its current value and a parameter.
  24082. *
  24083. * @function
  24084. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24085. * @param {Node} valueNode - The value that mutates the atomic variable.
  24086. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24087. * @returns {AtomicFunctionNode}
  24088. */
  24089. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  24090. /**
  24091. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  24092. *
  24093. * @function
  24094. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24095. * @param {Node} valueNode - The value that mutates the atomic variable.
  24096. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24097. * @returns {AtomicFunctionNode}
  24098. */
  24099. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  24100. /**
  24101. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  24102. *
  24103. * @function
  24104. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24105. * @param {Node} valueNode - The value that mutates the atomic variable.
  24106. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24107. * @returns {AtomicFunctionNode}
  24108. */
  24109. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  24110. /**
  24111. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  24112. *
  24113. * @function
  24114. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24115. * @param {Node} valueNode - The value that mutates the atomic variable.
  24116. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24117. * @returns {AtomicFunctionNode}
  24118. */
  24119. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  24120. /** @module Lights **/
  24121. let uniformsLib;
  24122. function getLightData( light ) {
  24123. uniformsLib = uniformsLib || new WeakMap();
  24124. let uniforms = uniformsLib.get( light );
  24125. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  24126. return uniforms;
  24127. }
  24128. /**
  24129. * TSL function for getting a shadow matrix uniform node for the given light.
  24130. *
  24131. * @function
  24132. * @param {Light} light -The light source.
  24133. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  24134. */
  24135. function lightShadowMatrix( light ) {
  24136. const data = getLightData( light );
  24137. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24138. if ( light.castShadow !== true ) {
  24139. light.shadow.updateMatrices( light );
  24140. }
  24141. return light.shadow.matrix;
  24142. } ) );
  24143. }
  24144. /**
  24145. * TSL function for getting projected uv coordinates for the given light.
  24146. * Relevant when using maps with spot lights.
  24147. *
  24148. * @function
  24149. * @param {Light} light -The light source.
  24150. * @returns {Node<vec3>} The projected uvs.
  24151. */
  24152. function lightProjectionUV( light ) {
  24153. const data = getLightData( light );
  24154. if ( data.projectionUV === undefined ) {
  24155. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  24156. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  24157. }
  24158. return data.projectionUV;
  24159. }
  24160. /**
  24161. * TSL function for getting the position in world space for the given light.
  24162. *
  24163. * @function
  24164. * @param {Light} light -The light source.
  24165. * @returns {UniformNode<vec3>} The light's position in world space.
  24166. */
  24167. function lightPosition( light ) {
  24168. const data = getLightData( light );
  24169. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  24170. }
  24171. /**
  24172. * TSL function for getting the light target position in world space for the given light.
  24173. *
  24174. * @function
  24175. * @param {Light} light -The light source.
  24176. * @returns {UniformNode<vec3>} The light target position in world space.
  24177. */
  24178. function lightTargetPosition( light ) {
  24179. const data = getLightData( light );
  24180. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  24181. }
  24182. /**
  24183. * TSL function for getting the position in view space for the given light.
  24184. *
  24185. * @function
  24186. * @param {Light} light -The light source.
  24187. * @returns {UniformNode<vec3>} The light's position in view space.
  24188. */
  24189. function lightViewPosition( light ) {
  24190. const data = getLightData( light );
  24191. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  24192. self.value = self.value || new Vector3();
  24193. self.value.setFromMatrixPosition( light.matrixWorld );
  24194. self.value.applyMatrix4( camera.matrixWorldInverse );
  24195. } ) );
  24196. }
  24197. /**
  24198. * TSL function for getting the light target direction for the given light.
  24199. *
  24200. * @function
  24201. * @param {Light} light -The light source.
  24202. * @returns {Node<vec3>} The light's target direction.
  24203. */
  24204. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  24205. /** @module LightsNode **/
  24206. const sortLights = ( lights ) => {
  24207. return lights.sort( ( a, b ) => a.id - b.id );
  24208. };
  24209. const getLightNodeById = ( id, lightNodes ) => {
  24210. for ( const lightNode of lightNodes ) {
  24211. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  24212. return lightNode;
  24213. }
  24214. }
  24215. return null;
  24216. };
  24217. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  24218. /**
  24219. * This node represents the scene's lighting and manages the lighting model's life cycle
  24220. * for the current build 3D object. It is responsible for computing the total outgoing
  24221. * light in a given lighting context.
  24222. *
  24223. * @augments Node
  24224. */
  24225. class LightsNode extends Node {
  24226. static get type() {
  24227. return 'LightsNode';
  24228. }
  24229. /**
  24230. * Constructs a new lights node.
  24231. */
  24232. constructor() {
  24233. super( 'vec3' );
  24234. /**
  24235. * A node representing the total diffuse light.
  24236. *
  24237. * @type {Node<vec3>}
  24238. */
  24239. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  24240. /**
  24241. * A node representing the total specular light.
  24242. *
  24243. * @type {Node<vec3>}
  24244. */
  24245. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  24246. /**
  24247. * A node representing the outgoing light.
  24248. *
  24249. * @type {Node<vec3>}
  24250. */
  24251. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  24252. /**
  24253. * An array representing the lights in the scene.
  24254. *
  24255. * @private
  24256. * @type {Array<Light>}
  24257. */
  24258. this._lights = [];
  24259. /**
  24260. * For each light in the scene, this node will create a
  24261. * corresponding light node.
  24262. *
  24263. * @private
  24264. * @type {Array<LightingNode>?}
  24265. * @default null
  24266. */
  24267. this._lightNodes = null;
  24268. /**
  24269. * A hash for identifying the current light nodes setup.
  24270. *
  24271. * @private
  24272. * @type {String?}
  24273. * @default null
  24274. */
  24275. this._lightNodesHash = null;
  24276. /**
  24277. * `LightsNode` sets this property to `true` by default.
  24278. *
  24279. * @type {Boolean}
  24280. * @default true
  24281. */
  24282. this.global = true;
  24283. }
  24284. /**
  24285. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  24286. * light IDs into the cache key.
  24287. *
  24288. * @return {Number} The custom cache key.
  24289. */
  24290. customCacheKey() {
  24291. const lightIDs = [];
  24292. const lights = this._lights;
  24293. for ( let i = 0; i < lights.length; i ++ ) {
  24294. lightIDs.push( lights[ i ].id );
  24295. }
  24296. return hashArray( lightIDs );
  24297. }
  24298. /**
  24299. * Computes a hash value for identifying the current light nodes setup.
  24300. *
  24301. * @param {NodeBuilder} builder - A reference to the current node builder.
  24302. * @return {String} The computed hash.
  24303. */
  24304. getHash( builder ) {
  24305. if ( this._lightNodesHash === null ) {
  24306. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24307. const hash = [];
  24308. for ( const lightNode of this._lightNodes ) {
  24309. hash.push( lightNode.getSelf().getHash() );
  24310. }
  24311. this._lightNodesHash = 'lights-' + hash.join( ',' );
  24312. }
  24313. return this._lightNodesHash;
  24314. }
  24315. analyze( builder ) {
  24316. const properties = builder.getDataFromNode( this );
  24317. for ( const node of properties.nodes ) {
  24318. node.build( builder );
  24319. }
  24320. }
  24321. /**
  24322. * Creates lighting nodes for each scene light. This makes it possible to further
  24323. * process lights in the node system.
  24324. *
  24325. * @param {NodeBuilder} builder - A reference to the current node builder.
  24326. */
  24327. setupLightsNode( builder ) {
  24328. const lightNodes = [];
  24329. const previousLightNodes = this._lightNodes;
  24330. const lights = sortLights( this._lights );
  24331. const nodeLibrary = builder.renderer.library;
  24332. for ( const light of lights ) {
  24333. if ( light.isNode ) {
  24334. lightNodes.push( nodeObject( light ) );
  24335. } else {
  24336. let lightNode = null;
  24337. if ( previousLightNodes !== null ) {
  24338. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  24339. }
  24340. if ( lightNode === null ) {
  24341. // find the corresponding node type for a given light
  24342. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  24343. if ( lightNodeClass === null ) {
  24344. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  24345. continue;
  24346. }
  24347. let lightNode = null;
  24348. if ( ! _lightsNodeRef.has( light ) ) {
  24349. lightNode = nodeObject( new lightNodeClass( light ) );
  24350. _lightsNodeRef.set( light, lightNode );
  24351. } else {
  24352. lightNode = _lightsNodeRef.get( light );
  24353. }
  24354. lightNodes.push( lightNode );
  24355. }
  24356. }
  24357. }
  24358. this._lightNodes = lightNodes;
  24359. }
  24360. /**
  24361. * Setups the internal lights by building all respective
  24362. * light nodes.
  24363. *
  24364. * @param {NodeBuilder} builder - A reference to the current node builder.
  24365. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  24366. */
  24367. setupLights( builder, lightNodes ) {
  24368. for ( const lightNode of lightNodes ) {
  24369. lightNode.build( builder );
  24370. }
  24371. }
  24372. /**
  24373. * The implementation makes sure that for each light in the scene
  24374. * there is a corresponding light node. By building the light nodes
  24375. * and evaluating the lighting model the outgoing light is computed.
  24376. *
  24377. * @param {NodeBuilder} builder - A reference to the current node builder.
  24378. * @return {Node<vec3>} A node representing the outgoing light.
  24379. */
  24380. setup( builder ) {
  24381. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24382. const context = builder.context;
  24383. const lightingModel = context.lightingModel;
  24384. let outgoingLightNode = this.outgoingLightNode;
  24385. if ( lightingModel ) {
  24386. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  24387. context.outgoingLight = outgoingLightNode;
  24388. const stack = builder.addStack();
  24389. //
  24390. const properties = builder.getDataFromNode( this );
  24391. properties.nodes = stack.nodes;
  24392. //
  24393. lightingModel.start( context, stack, builder );
  24394. // lights
  24395. this.setupLights( builder, _lightNodes );
  24396. //
  24397. lightingModel.indirect( context, stack, builder );
  24398. //
  24399. const { backdrop, backdropAlpha } = context;
  24400. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  24401. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  24402. if ( backdrop !== null ) {
  24403. if ( backdropAlpha !== null ) {
  24404. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  24405. } else {
  24406. totalDiffuse = vec3( backdrop );
  24407. }
  24408. context.material.transparent = true;
  24409. }
  24410. totalDiffuseNode.assign( totalDiffuse );
  24411. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  24412. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  24413. //
  24414. lightingModel.finish( context, stack, builder );
  24415. //
  24416. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  24417. }
  24418. return outgoingLightNode;
  24419. }
  24420. /**
  24421. * Configures this node with an array of lights.
  24422. *
  24423. * @param {Array<Light>} lights - An array of lights.
  24424. * @return {LightsNode} A reference to this node.
  24425. */
  24426. setLights( lights ) {
  24427. this._lights = lights;
  24428. this._lightNodes = null;
  24429. this._lightNodesHash = null;
  24430. return this;
  24431. }
  24432. /**
  24433. * Returns an array of the scene's lights.
  24434. *
  24435. * @return {Array<Light>} The scene's lights.
  24436. */
  24437. getLights() {
  24438. return this._lights;
  24439. }
  24440. /**
  24441. * Whether the scene has lights or not.
  24442. *
  24443. * @type {Boolean}
  24444. */
  24445. get hasLights() {
  24446. return this._lights.length > 0;
  24447. }
  24448. }
  24449. /**
  24450. * TSL function for creating an instance of `LightsNode` and configuring
  24451. * it with the given array of lights.
  24452. *
  24453. * @function
  24454. * @param {Array<Light>} lights - An array of lights.
  24455. * @return {LightsNode} The created lights node.
  24456. */
  24457. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  24458. /** @module ShadowBaseNode **/
  24459. /**
  24460. * Base class for all shadow nodes.
  24461. *
  24462. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  24463. * Lighting nodes might share the same shadow node type or use specific ones depending on
  24464. * their requirements.
  24465. *
  24466. * @augments Node
  24467. */
  24468. class ShadowBaseNode extends Node {
  24469. static get type() {
  24470. return 'ShadowBaseNode';
  24471. }
  24472. /**
  24473. * Constructs a new shadow base node.
  24474. *
  24475. * @param {Light} light - The shadow casting light.
  24476. */
  24477. constructor( light ) {
  24478. super();
  24479. /**
  24480. * The shadow casting light.
  24481. *
  24482. * @type {Light}
  24483. */
  24484. this.light = light;
  24485. /**
  24486. * Overwritten since shadows are updated by default per render.
  24487. *
  24488. * @type {String}
  24489. * @default 'render'
  24490. */
  24491. this.updateBeforeType = NodeUpdateType.RENDER;
  24492. /**
  24493. * This flag can be used for type testing.
  24494. *
  24495. * @type {Boolean}
  24496. * @readonly
  24497. * @default true
  24498. */
  24499. this.isShadowBaseNode = true;
  24500. }
  24501. /**
  24502. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  24503. *
  24504. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  24505. */
  24506. setupShadowPosition( { material } ) {
  24507. // Use assign inside an Fn()
  24508. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  24509. }
  24510. /**
  24511. * Can be called when the shadow isn't required anymore. That can happen when
  24512. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  24513. * to `false`.
  24514. */
  24515. dispose() {
  24516. this.updateBeforeType = NodeUpdateType.NONE;
  24517. }
  24518. }
  24519. /**
  24520. * TSL object that represents the vertex position in world space during the shadow pass.
  24521. *
  24522. * @type {Node<vec3>}
  24523. */
  24524. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  24525. /** @module RendererUtils **/
  24526. /**
  24527. * Saves the state of the given renderer and stores it into the given state object.
  24528. *
  24529. * If not state object is provided, the function creates one.
  24530. *
  24531. * @function
  24532. * @param {Renderer} renderer - The renderer.
  24533. * @param {Object} [state={}] - The state.
  24534. * @return {Object} The state.
  24535. */
  24536. function saveRendererState( renderer, state = {} ) {
  24537. state.toneMapping = renderer.toneMapping;
  24538. state.toneMappingExposure = renderer.toneMappingExposure;
  24539. state.outputColorSpace = renderer.outputColorSpace;
  24540. state.renderTarget = renderer.getRenderTarget();
  24541. state.activeCubeFace = renderer.getActiveCubeFace();
  24542. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  24543. state.renderObjectFunction = renderer.getRenderObjectFunction();
  24544. state.pixelRatio = renderer.getPixelRatio();
  24545. state.mrt = renderer.getMRT();
  24546. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  24547. state.clearAlpha = renderer.getClearAlpha();
  24548. state.autoClear = renderer.autoClear;
  24549. state.scissorTest = renderer.getScissorTest();
  24550. return state;
  24551. }
  24552. /**
  24553. * Saves the state of the given renderer and stores it into the given state object.
  24554. * Besides, the function also resets the state of the renderer to its default values.
  24555. *
  24556. * If not state object is provided, the function creates one.
  24557. *
  24558. * @function
  24559. * @param {Renderer} renderer - The renderer.
  24560. * @param {Object} [state={}] - The state.
  24561. * @return {Object} The state.
  24562. */
  24563. function resetRendererState( renderer, state ) {
  24564. state = saveRendererState( renderer, state );
  24565. renderer.setMRT( null );
  24566. renderer.setRenderObjectFunction( null );
  24567. renderer.setClearColor( 0x000000, 1 );
  24568. renderer.autoClear = true;
  24569. return state;
  24570. }
  24571. /**
  24572. * Restores the state of the given renderer from the given state object.
  24573. *
  24574. * @function
  24575. * @param {Renderer} renderer - The renderer.
  24576. * @param {Object} state - The state to restore.
  24577. */
  24578. function restoreRendererState( renderer, state ) {
  24579. renderer.toneMapping = state.toneMapping;
  24580. renderer.toneMappingExposure = state.toneMappingExposure;
  24581. renderer.outputColorSpace = state.outputColorSpace;
  24582. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  24583. renderer.setRenderObjectFunction( state.renderObjectFunction );
  24584. renderer.setPixelRatio( state.pixelRatio );
  24585. renderer.setMRT( state.mrt );
  24586. renderer.setClearColor( state.clearColor, state.clearAlpha );
  24587. renderer.autoClear = state.autoClear;
  24588. renderer.setScissorTest( state.scissorTest );
  24589. }
  24590. /**
  24591. * Saves the state of the given scene and stores it into the given state object.
  24592. *
  24593. * If not state object is provided, the function creates one.
  24594. *
  24595. * @function
  24596. * @param {Scene} scene - The scene.
  24597. * @param {Object} [state={}] - The state.
  24598. * @return {Object} The state.
  24599. */
  24600. function saveSceneState( scene, state = {} ) {
  24601. state.background = scene.background;
  24602. state.backgroundNode = scene.backgroundNode;
  24603. state.overrideMaterial = scene.overrideMaterial;
  24604. return state;
  24605. }
  24606. /**
  24607. * Saves the state of the given scene and stores it into the given state object.
  24608. * Besides, the function also resets the state of the scene to its default values.
  24609. *
  24610. * If not state object is provided, the function creates one.
  24611. *
  24612. * @function
  24613. * @param {Scene} scene - The scene.
  24614. * @param {Object} [state={}] - The state.
  24615. * @return {Object} The state.
  24616. */
  24617. function resetSceneState( scene, state ) {
  24618. state = saveSceneState( scene, state );
  24619. scene.background = null;
  24620. scene.backgroundNode = null;
  24621. scene.overrideMaterial = null;
  24622. return state;
  24623. }
  24624. /**
  24625. * Restores the state of the given scene from the given state object.
  24626. *
  24627. * @function
  24628. * @param {Scene} scene - The scene.
  24629. * @param {Object} state - The state to restore.
  24630. */
  24631. function restoreSceneState( scene, state ) {
  24632. scene.background = state.background;
  24633. scene.backgroundNode = state.backgroundNode;
  24634. scene.overrideMaterial = state.overrideMaterial;
  24635. }
  24636. /**
  24637. * Saves the state of the given renderer and scene and stores it into the given state object.
  24638. *
  24639. * If not state object is provided, the function creates one.
  24640. *
  24641. * @function
  24642. * @param {Renderer} renderer - The renderer.
  24643. * @param {Scene} scene - The scene.
  24644. * @param {Object} [state={}] - The state.
  24645. * @return {Object} The state.
  24646. */
  24647. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  24648. state = saveRendererState( renderer, state );
  24649. state = saveSceneState( scene, state );
  24650. return state;
  24651. }
  24652. /**
  24653. * Saves the state of the given renderer and scene and stores it into the given state object.
  24654. * Besides, the function also resets the state of the renderer and scene to its default values.
  24655. *
  24656. * If not state object is provided, the function creates one.
  24657. *
  24658. * @function
  24659. * @param {Renderer} renderer - The renderer.
  24660. * @param {Scene} scene - The scene.
  24661. * @param {Object} [state={}] - The state.
  24662. * @return {Object} The state.
  24663. */
  24664. function resetRendererAndSceneState( renderer, scene, state ) {
  24665. state = resetRendererState( renderer, state );
  24666. state = resetSceneState( scene, state );
  24667. return state;
  24668. }
  24669. /**
  24670. * Restores the state of the given renderer and scene from the given state object.
  24671. *
  24672. * @function
  24673. * @param {Renderer} renderer - The renderer.
  24674. * @param {Scene} scene - The scene.
  24675. * @param {Object} state - The state to restore.
  24676. */
  24677. function restoreRendererAndSceneState( renderer, scene, state ) {
  24678. restoreRendererState( renderer, state );
  24679. restoreSceneState( scene, state );
  24680. }
  24681. var RendererUtils = /*#__PURE__*/Object.freeze({
  24682. __proto__: null,
  24683. resetRendererAndSceneState: resetRendererAndSceneState,
  24684. resetRendererState: resetRendererState,
  24685. resetSceneState: resetSceneState,
  24686. restoreRendererAndSceneState: restoreRendererAndSceneState,
  24687. restoreRendererState: restoreRendererState,
  24688. restoreSceneState: restoreSceneState,
  24689. saveRendererAndSceneState: saveRendererAndSceneState,
  24690. saveRendererState: saveRendererState,
  24691. saveSceneState: saveSceneState
  24692. });
  24693. /** @module ShadowNode **/
  24694. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  24695. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  24696. let dist = positionWorld.sub( position ).length();
  24697. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  24698. dist = dist.saturate(); // clamp to [ 0, 1 ]
  24699. return dist;
  24700. } );
  24701. const linearShadowDistance = ( light ) => {
  24702. const camera = light.shadow.camera;
  24703. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  24704. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  24705. const referencePosition = objectPosition( light );
  24706. return linearDistance( referencePosition, nearDistance, farDistance );
  24707. };
  24708. const getShadowMaterial = ( light ) => {
  24709. let material = shadowMaterialLib.get( light );
  24710. if ( material === undefined ) {
  24711. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  24712. material = new NodeMaterial();
  24713. material.colorNode = vec4( 0, 0, 0, 1 );
  24714. material.depthNode = depthNode;
  24715. material.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  24716. material.name = 'ShadowMaterial';
  24717. material.fog = false;
  24718. shadowMaterialLib.set( light, material );
  24719. }
  24720. return material;
  24721. };
  24722. /**
  24723. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  24724. * with a binary `[0,1]` result.
  24725. *
  24726. * @method
  24727. * @param {Object} inputs - The input parameter object.
  24728. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24729. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24730. * @return {Node<float>} The filtering result.
  24731. */
  24732. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  24733. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  24734. } );
  24735. /**
  24736. * A shadow filtering function performing PCF filtering.
  24737. *
  24738. * @method
  24739. * @param {Object} inputs - The input parameter object.
  24740. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24741. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24742. * @param {LightShadow} inputs.shadow - The light shadow.
  24743. * @return {Node<float>} The filtering result.
  24744. */
  24745. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  24746. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  24747. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  24748. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  24749. const texelSize = vec2( 1 ).div( mapSize );
  24750. const dx0 = texelSize.x.negate().mul( radius );
  24751. const dy0 = texelSize.y.negate().mul( radius );
  24752. const dx1 = texelSize.x.mul( radius );
  24753. const dy1 = texelSize.y.mul( radius );
  24754. const dx2 = dx0.div( 2 );
  24755. const dy2 = dy0.div( 2 );
  24756. const dx3 = dx1.div( 2 );
  24757. const dy3 = dy1.div( 2 );
  24758. return add(
  24759. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  24760. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  24761. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  24762. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  24763. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  24764. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  24765. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  24766. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  24767. depthCompare( shadowCoord.xy, shadowCoord.z ),
  24768. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  24769. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  24770. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  24771. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  24772. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  24773. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  24774. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  24775. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  24776. ).mul( 1 / 17 );
  24777. } );
  24778. /**
  24779. * A shadow filtering function performing PCF soft filtering.
  24780. *
  24781. * @method
  24782. * @param {Object} inputs - The input parameter object.
  24783. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24784. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24785. * @param {LightShadow} inputs.shadow - The light shadow.
  24786. * @return {Node<float>} The filtering result.
  24787. */
  24788. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  24789. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  24790. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  24791. const texelSize = vec2( 1 ).div( mapSize );
  24792. const dx = texelSize.x;
  24793. const dy = texelSize.y;
  24794. const uv = shadowCoord.xy;
  24795. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  24796. uv.subAssign( f.mul( texelSize ) );
  24797. return add(
  24798. depthCompare( uv, shadowCoord.z ),
  24799. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  24800. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  24801. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  24802. mix(
  24803. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  24804. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  24805. f.x
  24806. ),
  24807. mix(
  24808. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  24809. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  24810. f.x
  24811. ),
  24812. mix(
  24813. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  24814. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  24815. f.y
  24816. ),
  24817. mix(
  24818. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  24819. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  24820. f.y
  24821. ),
  24822. mix(
  24823. mix(
  24824. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  24825. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  24826. f.x
  24827. ),
  24828. mix(
  24829. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  24830. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  24831. f.x
  24832. ),
  24833. f.y
  24834. )
  24835. ).mul( 1 / 9 );
  24836. } );
  24837. /**
  24838. * A shadow filtering function performing VSM filtering.
  24839. *
  24840. * @method
  24841. * @param {Object} inputs - The input parameter object.
  24842. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  24843. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  24844. * @return {Node<float>} The filtering result.
  24845. */
  24846. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  24847. const occlusion = float( 1 ).toVar();
  24848. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  24849. const hardShadow = step( shadowCoord.z, distribution.x );
  24850. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  24851. const distance = shadowCoord.z.sub( distribution.x );
  24852. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  24853. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  24854. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  24855. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  24856. } );
  24857. return occlusion;
  24858. } );
  24859. /**
  24860. * Represents the shader code for the first VSM render pass.
  24861. *
  24862. * @method
  24863. * @param {Object} inputs - The input parameter object.
  24864. * @param {Node<float>} inputs.samples - The number of samples
  24865. * @param {Node<float>} inputs.radius - The radius.
  24866. * @param {Node<float>} inputs.size - The size.
  24867. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  24868. * @return {Node<vec2>} The VSM output.
  24869. */
  24870. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  24871. const mean = float( 0 ).toVar();
  24872. const squaredMean = float( 0 ).toVar();
  24873. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  24874. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  24875. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  24876. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  24877. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  24878. mean.addAssign( depth );
  24879. squaredMean.addAssign( depth.mul( depth ) );
  24880. } );
  24881. mean.divAssign( samples );
  24882. squaredMean.divAssign( samples );
  24883. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  24884. return vec2( mean, std_dev );
  24885. } );
  24886. /**
  24887. * Represents the shader code for the second VSM render pass.
  24888. *
  24889. * @method
  24890. * @param {Object} inputs - The input parameter object.
  24891. * @param {Node<float>} inputs.samples - The number of samples
  24892. * @param {Node<float>} inputs.radius - The radius.
  24893. * @param {Node<float>} inputs.size - The size.
  24894. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  24895. * @return {Node<vec2>} The VSM output.
  24896. */
  24897. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  24898. const mean = float( 0 ).toVar();
  24899. const squaredMean = float( 0 ).toVar();
  24900. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  24901. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  24902. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  24903. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  24904. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  24905. mean.addAssign( distribution.x );
  24906. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  24907. } );
  24908. mean.divAssign( samples );
  24909. squaredMean.divAssign( samples );
  24910. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  24911. return vec2( mean, std_dev );
  24912. } );
  24913. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  24914. //
  24915. let _rendererState;
  24916. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  24917. /**
  24918. * Represents the default shadow implementation for lighting nodes.
  24919. *
  24920. * @augments module:ShadowBaseNode~ShadowBaseNode
  24921. */
  24922. class ShadowNode extends ShadowBaseNode {
  24923. static get type() {
  24924. return 'ShadowNode';
  24925. }
  24926. /**
  24927. * Constructs a new shadow node.
  24928. *
  24929. * @param {Light} light - The shadow casting light.
  24930. * @param {LightShadow?} [shadow=null] - An optional light shadow.
  24931. */
  24932. constructor( light, shadow = null ) {
  24933. super( light );
  24934. /**
  24935. * The light shadow which defines the properties light's
  24936. * shadow.
  24937. *
  24938. * @type {LightShadow?}
  24939. * @default null
  24940. */
  24941. this.shadow = shadow || light.shadow;
  24942. /**
  24943. * A reference to the shadow map which is a render target.
  24944. *
  24945. * @type {RenderTarget?}
  24946. * @default null
  24947. */
  24948. this.shadowMap = null;
  24949. /**
  24950. * Only relevant for VSM shadows. Render target for the
  24951. * first VSM render pass.
  24952. *
  24953. * @type {RenderTarget?}
  24954. * @default null
  24955. */
  24956. this.vsmShadowMapVertical = null;
  24957. /**
  24958. * Only relevant for VSM shadows. Render target for the
  24959. * second VSM render pass.
  24960. *
  24961. * @type {RenderTarget?}
  24962. * @default null
  24963. */
  24964. this.vsmShadowMapHorizontal = null;
  24965. /**
  24966. * Only relevant for VSM shadows. Node material which
  24967. * is used to render the first VSM pass.
  24968. *
  24969. * @type {NodeMaterial?}
  24970. * @default null
  24971. */
  24972. this.vsmMaterialVertical = null;
  24973. /**
  24974. * Only relevant for VSM shadows. Node material which
  24975. * is used to render the second VSM pass.
  24976. *
  24977. * @type {NodeMaterial?}
  24978. * @default null
  24979. */
  24980. this.vsmMaterialHorizontal = null;
  24981. /**
  24982. * A reference to the output node which defines the
  24983. * final result of this shadow node.
  24984. *
  24985. * @type {Node?}
  24986. * @private
  24987. * @default null
  24988. */
  24989. this._node = null;
  24990. /**
  24991. * This flag can be used for type testing.
  24992. *
  24993. * @type {Boolean}
  24994. * @readonly
  24995. * @default true
  24996. */
  24997. this.isShadowNode = true;
  24998. }
  24999. /**
  25000. * Setups the shadow filtering.
  25001. *
  25002. * @param {NodeBuilder} builder - A reference to the current node builder.
  25003. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25004. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25005. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25006. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25007. * @param {LightShadow} inputs.shadow - The light shadow.
  25008. * @return {Node<float>} The result node of the shadow filtering.
  25009. */
  25010. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  25011. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25012. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25013. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25014. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25015. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25016. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  25017. return frustumTest.select( shadowNode, float( 1 ) );
  25018. }
  25019. /**
  25020. * Setups the shadow coordinates.
  25021. *
  25022. * @param {NodeBuilder} builder - A reference to the current node builder.
  25023. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25024. * @return {Node<vec3>} The shadow coordinates.
  25025. */
  25026. setupShadowCoord( builder, shadowPosition ) {
  25027. const { shadow } = this;
  25028. const { renderer } = builder;
  25029. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25030. let shadowCoord = shadowPosition;
  25031. let coordZ;
  25032. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  25033. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25034. coordZ = shadowCoord.z;
  25035. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25036. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  25037. }
  25038. } else {
  25039. const w = shadowCoord.w;
  25040. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  25041. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  25042. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  25043. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  25044. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  25045. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  25046. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  25047. }
  25048. shadowCoord = vec3(
  25049. shadowCoord.x,
  25050. shadowCoord.y.oneMinus(), // follow webgpu standards
  25051. coordZ.add( bias )
  25052. );
  25053. return shadowCoord;
  25054. }
  25055. /**
  25056. * Returns the shadow filtering function for the given shadow type.
  25057. *
  25058. * @param {Number} type - The shadow type.
  25059. * @return {Function} The filtering function.
  25060. */
  25061. getShadowFilterFn( type ) {
  25062. return _shadowFilterLib[ type ];
  25063. }
  25064. /**
  25065. * Setups the shadow output node.
  25066. *
  25067. * @param {NodeBuilder} builder - A reference to the current node builder.
  25068. * @return {Node<vec3>} The shadow output node.
  25069. */
  25070. setupShadow( builder ) {
  25071. const { renderer } = builder;
  25072. const { light, shadow } = this;
  25073. const shadowMapType = renderer.shadowMap.type;
  25074. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  25075. depthTexture.compareFunction = LessCompare;
  25076. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25077. shadowMap.depthTexture = depthTexture;
  25078. shadow.camera.updateProjectionMatrix();
  25079. // VSM
  25080. if ( shadowMapType === VSMShadowMap ) {
  25081. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  25082. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25083. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25084. const shadowPassVertical = texture( depthTexture );
  25085. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  25086. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  25087. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25088. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25089. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  25090. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  25091. material.name = 'VSMVertical';
  25092. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  25093. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  25094. material.name = 'VSMHorizontal';
  25095. }
  25096. //
  25097. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  25098. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  25099. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  25100. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  25101. //
  25102. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  25103. if ( filterFn === null ) {
  25104. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  25105. }
  25106. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  25107. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  25108. const shadowColor = texture( shadowMap.texture, shadowCoord );
  25109. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  25110. this.shadowMap = shadowMap;
  25111. this.shadow.map = shadowMap;
  25112. return shadowOutput;
  25113. }
  25114. /**
  25115. * The implementation performs the setup of the output node. An output is only
  25116. * produces if shadow mapping is globally enabled in the renderer.
  25117. *
  25118. * @param {NodeBuilder} builder - A reference to the current node builder.
  25119. * @return {ShaderCallNodeInternal} The output node.
  25120. */
  25121. setup( builder ) {
  25122. if ( builder.renderer.shadowMap.enabled === false ) return;
  25123. return Fn( () => {
  25124. let node = this._node;
  25125. this.setupShadowPosition( builder );
  25126. if ( node === null ) {
  25127. this._node = node = this.setupShadow( builder );
  25128. }
  25129. if ( builder.material.shadowNode ) { // @deprecated, r171
  25130. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  25131. }
  25132. if ( builder.material.receivedShadowNode ) {
  25133. node = builder.material.receivedShadowNode( node );
  25134. }
  25135. return node;
  25136. } )();
  25137. }
  25138. /**
  25139. * Renders the shadow. The logic of this function could be included
  25140. * into {@link ShadowNode#updateShadow} however more specialized shadow
  25141. * nodes might require a custom shadow map rendering. By having a
  25142. * dedicated method, it's easier to overwrite the default behavior.
  25143. *
  25144. * @param {NodeFrame} frame - A reference to the current node frame.
  25145. */
  25146. renderShadow( frame ) {
  25147. const { shadow, shadowMap, light } = this;
  25148. const { renderer, scene } = frame;
  25149. shadow.updateMatrices( light );
  25150. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25151. renderer.render( scene, shadow.camera );
  25152. }
  25153. /**
  25154. * Updates the shadow.
  25155. *
  25156. * @param {NodeFrame} frame - A reference to the current node frame.
  25157. */
  25158. updateShadow( frame ) {
  25159. const { shadowMap, light, shadow } = this;
  25160. const { renderer, scene, camera } = frame;
  25161. const shadowType = renderer.shadowMap.type;
  25162. const depthVersion = shadowMap.depthTexture.version;
  25163. this._depthVersionCached = depthVersion;
  25164. shadow.camera.layers.mask = camera.layers.mask;
  25165. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25166. const currentMRT = renderer.getMRT();
  25167. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  25168. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  25169. scene.overrideMaterial = getShadowMaterial( light );
  25170. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  25171. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  25172. if ( useVelocity ) {
  25173. getDataFromObject( object ).useVelocity = true;
  25174. }
  25175. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25176. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  25177. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25178. }
  25179. } );
  25180. renderer.setRenderTarget( shadowMap );
  25181. this.renderShadow( frame );
  25182. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25183. // vsm blur pass
  25184. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  25185. this.vsmPass( renderer );
  25186. }
  25187. restoreRendererAndSceneState( renderer, scene, _rendererState );
  25188. }
  25189. /**
  25190. * For VSM additional render passes are required.
  25191. *
  25192. * @param {Renderer} renderer - A reference to the current renderer.
  25193. */
  25194. vsmPass( renderer ) {
  25195. const { shadow } = this;
  25196. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25197. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25198. renderer.setRenderTarget( this.vsmShadowMapVertical );
  25199. _quadMesh$1.material = this.vsmMaterialVertical;
  25200. _quadMesh$1.render( renderer );
  25201. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  25202. _quadMesh$1.material = this.vsmMaterialHorizontal;
  25203. _quadMesh$1.render( renderer );
  25204. }
  25205. /**
  25206. * Frees the internal resources of this shadow node.
  25207. */
  25208. dispose() {
  25209. this.shadowMap.dispose();
  25210. this.shadowMap = null;
  25211. if ( this.vsmShadowMapVertical !== null ) {
  25212. this.vsmShadowMapVertical.dispose();
  25213. this.vsmShadowMapVertical = null;
  25214. this.vsmMaterialVertical.dispose();
  25215. this.vsmMaterialVertical = null;
  25216. }
  25217. if ( this.vsmShadowMapHorizontal !== null ) {
  25218. this.vsmShadowMapHorizontal.dispose();
  25219. this.vsmShadowMapHorizontal = null;
  25220. this.vsmMaterialHorizontal.dispose();
  25221. this.vsmMaterialHorizontal = null;
  25222. }
  25223. super.dispose();
  25224. }
  25225. /**
  25226. * The implementation performs the update of the shadow map if necessary.
  25227. *
  25228. * @param {NodeFrame} frame - A reference to the current node frame.
  25229. */
  25230. updateBefore( frame ) {
  25231. const { shadow } = this;
  25232. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  25233. if ( needsUpdate ) {
  25234. this.updateShadow( frame );
  25235. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  25236. shadow.needsUpdate = false;
  25237. }
  25238. }
  25239. }
  25240. }
  25241. /**
  25242. * TSL function for creating an instance of `ShadowNode`.
  25243. *
  25244. * @function
  25245. * @param {Light} light - The shadow casting light.
  25246. * @param {LightShadow} shadow - The light shadow.
  25247. * @return {ShadowNode} The created shadow node.
  25248. */
  25249. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  25250. /**
  25251. * Base class for analytic light nodes.
  25252. *
  25253. * @augments LightingNode
  25254. */
  25255. class AnalyticLightNode extends LightingNode {
  25256. static get type() {
  25257. return 'AnalyticLightNode';
  25258. }
  25259. /**
  25260. * Constructs a new analytic light node.
  25261. *
  25262. * @param {Light?} [light=null] - The light source.
  25263. */
  25264. constructor( light = null ) {
  25265. super();
  25266. /**
  25267. * The light source.
  25268. *
  25269. * @type {Light?}
  25270. * @default null
  25271. */
  25272. this.light = light;
  25273. /**
  25274. * The light's color value.
  25275. *
  25276. * @type {Color}
  25277. */
  25278. this.color = new Color();
  25279. /**
  25280. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  25281. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  25282. *
  25283. * @type {Node}
  25284. */
  25285. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  25286. /**
  25287. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  25288. * The final color node is represented by a different node when using shadows.
  25289. *
  25290. * @type {Node?}
  25291. * @default null
  25292. */
  25293. this.baseColorNode = null;
  25294. /**
  25295. * Represents the light's shadow.
  25296. *
  25297. * @type {ShadowNode?}
  25298. * @default null
  25299. */
  25300. this.shadowNode = null;
  25301. /**
  25302. * Represents the light's shadow color.
  25303. *
  25304. * @type {Node?}
  25305. * @default null
  25306. */
  25307. this.shadowColorNode = null;
  25308. /**
  25309. * This flag can be used for type testing.
  25310. *
  25311. * @type {Boolean}
  25312. * @readonly
  25313. * @default true
  25314. */
  25315. this.isAnalyticLightNode = true;
  25316. /**
  25317. * Overwritten since analytic light nodes are updated
  25318. * once per frame.
  25319. *
  25320. * @type {String}
  25321. * @default 'frame'
  25322. */
  25323. this.updateType = NodeUpdateType.FRAME;
  25324. }
  25325. /**
  25326. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  25327. * `light.id` and `light.castShadow` into the cache key.
  25328. *
  25329. * @return {Number} The custom cache key.
  25330. */
  25331. customCacheKey() {
  25332. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  25333. }
  25334. getHash() {
  25335. return this.light.uuid;
  25336. }
  25337. /**
  25338. * Setups the shadow node for this light. The method exists so concrete light classes
  25339. * can setup different types of shadow nodes.
  25340. *
  25341. * @return {ShadowNode} The created shadow node.
  25342. */
  25343. setupShadowNode() {
  25344. return shadow( this.light );
  25345. }
  25346. /**
  25347. * Setups the shadow for this light. This method is only executed if the light
  25348. * cast shadows and the current build object receives shadows. It incorporates
  25349. * shadows into the lighting computation.
  25350. *
  25351. * @param {NodeBuilder} builder - The current node builder.
  25352. */
  25353. setupShadow( builder ) {
  25354. const { renderer } = builder;
  25355. if ( renderer.shadowMap.enabled === false ) return;
  25356. let shadowColorNode = this.shadowColorNode;
  25357. if ( shadowColorNode === null ) {
  25358. const customShadowNode = this.light.shadow.shadowNode;
  25359. let shadowNode;
  25360. if ( customShadowNode !== undefined ) {
  25361. shadowNode = nodeObject( customShadowNode );
  25362. } else {
  25363. shadowNode = this.setupShadowNode( builder );
  25364. }
  25365. this.shadowNode = shadowNode;
  25366. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  25367. this.baseColorNode = this.colorNode;
  25368. }
  25369. //
  25370. this.colorNode = shadowColorNode;
  25371. }
  25372. /**
  25373. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  25374. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  25375. * invocate the respective interface methods.
  25376. *
  25377. * @param {NodeBuilder} builder - The current node builder.
  25378. */
  25379. setup( builder ) {
  25380. this.colorNode = this.baseColorNode || this.colorNode;
  25381. if ( this.light.castShadow ) {
  25382. if ( builder.object.receiveShadow ) {
  25383. this.setupShadow( builder );
  25384. }
  25385. } else if ( this.shadowNode !== null ) {
  25386. this.shadowNode.dispose();
  25387. this.shadowNode = null;
  25388. this.shadowColorNode = null;
  25389. }
  25390. }
  25391. /**
  25392. * The update method is used to update light uniforms per frame.
  25393. * Potentially overwritten in concrete light nodes to update light
  25394. * specific uniforms.
  25395. *
  25396. * @param {NodeFrame} frame - A reference to the current node frame.
  25397. */
  25398. update( /*frame*/ ) {
  25399. const { light } = this;
  25400. this.color.copy( light.color ).multiplyScalar( light.intensity );
  25401. }
  25402. }
  25403. /** @module LightUtils **/
  25404. /**
  25405. * Represents a `discard` shader operation in TSL.
  25406. *
  25407. * @method
  25408. * @param {Object} inputs - The input parameter object.
  25409. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  25410. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  25411. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  25412. * @return {Node<float>} The distance falloff.
  25413. */
  25414. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  25415. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  25416. // based upon Frostbite 3 Moving to Physically-based Rendering
  25417. // page 32, equation 26: E[window1]
  25418. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25419. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  25420. return cutoffDistance.greaterThan( 0 ).select(
  25421. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  25422. distanceFalloff
  25423. );
  25424. } ); // validated
  25425. /** @module PointShadowNode **/
  25426. const _clearColor$2 = /*@__PURE__*/ new Color();
  25427. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  25428. // vector suitable for 2D texture mapping. This code uses the following layout for the
  25429. // 2D texture:
  25430. //
  25431. // xzXZ
  25432. // y Y
  25433. //
  25434. // Y - Positive y direction
  25435. // y - Negative y direction
  25436. // X - Positive x direction
  25437. // x - Negative x direction
  25438. // Z - Positive z direction
  25439. // z - Negative z direction
  25440. //
  25441. // Source and test bed:
  25442. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  25443. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  25444. const v = pos.toVar();
  25445. // Number of texels to avoid at the edge of each square
  25446. const absV = abs( v );
  25447. // Intersect unit cube
  25448. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  25449. absV.mulAssign( scaleToCube );
  25450. // Apply scale to avoid seams
  25451. // two texels less per square (one texel will do for NEAREST)
  25452. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  25453. // Unwrap
  25454. // space: -1 ... 1 range for each square
  25455. //
  25456. // #X## dim := ( 4 , 2 )
  25457. // # # center := ( 1 , 1 )
  25458. const planar = vec2( v.xy ).toVar();
  25459. const almostATexel = texelSizeY.mul( 1.5 );
  25460. const almostOne = almostATexel.oneMinus();
  25461. If( absV.z.greaterThanEqual( almostOne ), () => {
  25462. If( v.z.greaterThan( 0.0 ), () => {
  25463. planar.x.assign( sub( 4.0, v.x ) );
  25464. } );
  25465. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  25466. const signX = sign( v.x );
  25467. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  25468. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  25469. const signY = sign( v.y );
  25470. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  25471. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  25472. } );
  25473. // Transform to UV space
  25474. // scale := 0.5 / dim
  25475. // translate := ( center + 0.5 ) / dim
  25476. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  25477. } ).setLayout( {
  25478. name: 'cubeToUV',
  25479. type: 'vec2',
  25480. inputs: [
  25481. { name: 'pos', type: 'vec3' },
  25482. { name: 'texelSizeY', type: 'float' }
  25483. ]
  25484. } );
  25485. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  25486. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  25487. } );
  25488. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  25489. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25490. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  25491. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  25492. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  25493. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  25494. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  25495. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  25496. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  25497. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  25498. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  25499. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  25500. .mul( 1.0 / 9.0 );
  25501. } );
  25502. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  25503. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  25504. // the vector from the light to the world-space position of the fragment.
  25505. const lightToPosition = shadowCoord.xyz.toVar();
  25506. const lightToPositionLength = lightToPosition.length();
  25507. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  25508. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  25509. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25510. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  25511. const result = float( 1.0 ).toVar();
  25512. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  25513. // dp = normalized distance from light to fragment position
  25514. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  25515. dp.addAssign( bias );
  25516. // bd3D = base direction 3D
  25517. const bd3D = lightToPosition.normalize();
  25518. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  25519. // percentage-closer filtering
  25520. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  25521. } );
  25522. return result;
  25523. } );
  25524. const _viewport = /*@__PURE__*/ new Vector4();
  25525. const _viewportSize = /*@__PURE__*/ new Vector2();
  25526. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  25527. /**
  25528. * Represents the shadow implementation for point light nodes.
  25529. *
  25530. * @augments module:ShadowNode~ShadowNode
  25531. */
  25532. class PointShadowNode extends ShadowNode {
  25533. static get type() {
  25534. return 'PointShadowNode';
  25535. }
  25536. /**
  25537. * Constructs a new point shadow node.
  25538. *
  25539. * @param {PointLight} light - The shadow casting point light.
  25540. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25541. */
  25542. constructor( light, shadow = null ) {
  25543. super( light, shadow );
  25544. }
  25545. /**
  25546. * Overwrites the default implementation to return point light shadow specific
  25547. * filtering functions.
  25548. *
  25549. * @param {Number} type - The shadow type.
  25550. * @return {Function} The filtering function.
  25551. */
  25552. getShadowFilterFn( type ) {
  25553. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  25554. }
  25555. /**
  25556. * Overwrites the default implementation so the unaltered shadow position is used.
  25557. *
  25558. * @param {NodeBuilder} builder - A reference to the current node builder.
  25559. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25560. * @return {Node<vec3>} The shadow coordinates.
  25561. */
  25562. setupShadowCoord( builder, shadowPosition ) {
  25563. return shadowPosition;
  25564. }
  25565. /**
  25566. * Overwrites the default implementation to only use point light specific
  25567. * shadow filter functions.
  25568. *
  25569. * @param {NodeBuilder} builder - A reference to the current node builder.
  25570. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25571. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25572. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  25573. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25574. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25575. * @param {LightShadow} inputs.shadow - The light shadow.
  25576. * @return {Node<float>} The result node of the shadow filtering.
  25577. */
  25578. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  25579. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  25580. }
  25581. /**
  25582. * Overwrites the default implementation with point light specific
  25583. * rendering code.
  25584. *
  25585. * @param {NodeFrame} frame - A reference to the current node frame.
  25586. */
  25587. renderShadow( frame ) {
  25588. const { shadow, shadowMap, light } = this;
  25589. const { renderer, scene } = frame;
  25590. const shadowFrameExtents = shadow.getFrameExtents();
  25591. _shadowMapSize.copy( shadow.mapSize );
  25592. _shadowMapSize.multiply( shadowFrameExtents );
  25593. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  25594. _viewportSize.copy( shadow.mapSize );
  25595. //
  25596. const previousAutoClear = renderer.autoClear;
  25597. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  25598. const previousClearAlpha = renderer.getClearAlpha();
  25599. renderer.autoClear = false;
  25600. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  25601. renderer.clear();
  25602. const viewportCount = shadow.getViewportCount();
  25603. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  25604. const viewport = shadow.getViewport( vp );
  25605. const x = _viewportSize.x * viewport.x;
  25606. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  25607. _viewport.set(
  25608. x,
  25609. y,
  25610. _viewportSize.x * viewport.z,
  25611. _viewportSize.y * viewport.w
  25612. );
  25613. shadowMap.viewport.copy( _viewport );
  25614. shadow.updateMatrices( light, vp );
  25615. renderer.render( scene, shadow.camera );
  25616. }
  25617. //
  25618. renderer.autoClear = previousAutoClear;
  25619. renderer.setClearColor( previousClearColor, previousClearAlpha );
  25620. }
  25621. }
  25622. /**
  25623. * TSL function for creating an instance of `PointShadowNode`.
  25624. *
  25625. * @function
  25626. * @param {PointLight} light - The shadow casting point light.
  25627. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25628. * @return {PointShadowNode} The created point shadow node.
  25629. */
  25630. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  25631. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  25632. const lightingModel = builder.context.lightingModel;
  25633. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  25634. const lightDirection = lVector.normalize();
  25635. const lightDistance = lVector.length();
  25636. const lightAttenuation = getDistanceAttenuation( {
  25637. lightDistance,
  25638. cutoffDistance,
  25639. decayExponent
  25640. } );
  25641. const lightColor = color.mul( lightAttenuation );
  25642. const reflectedLight = builder.context.reflectedLight;
  25643. lightingModel.direct( {
  25644. lightDirection,
  25645. lightColor,
  25646. reflectedLight
  25647. }, builder.stack, builder );
  25648. } );
  25649. /**
  25650. * Module for representing point lights as nodes.
  25651. *
  25652. * @augments AnalyticLightNode
  25653. */
  25654. class PointLightNode extends AnalyticLightNode {
  25655. static get type() {
  25656. return 'PointLightNode';
  25657. }
  25658. /**
  25659. * Constructs a new point light node.
  25660. *
  25661. * @param {PointLight?} [light=null] - The point light source.
  25662. */
  25663. constructor( light = null ) {
  25664. super( light );
  25665. /**
  25666. * Uniform node representing the cutoff distance.
  25667. *
  25668. * @type {UniformNode<float>}
  25669. */
  25670. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  25671. /**
  25672. * Uniform node representing the decay exponent.
  25673. *
  25674. * @type {UniformNode<float>}
  25675. */
  25676. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  25677. }
  25678. /**
  25679. * Overwritten to updated point light specific uniforms.
  25680. *
  25681. * @param {NodeFrame} frame - A reference to the current node frame.
  25682. */
  25683. update( frame ) {
  25684. const { light } = this;
  25685. super.update( frame );
  25686. this.cutoffDistanceNode.value = light.distance;
  25687. this.decayExponentNode.value = light.decay;
  25688. }
  25689. /**
  25690. * Overwritten to setup point light specific shadow.
  25691. *
  25692. * @return {PointShadowNode}
  25693. */
  25694. setupShadowNode() {
  25695. return pointShadow( this.light );
  25696. }
  25697. setup( builder ) {
  25698. super.setup( builder );
  25699. directPointLight( {
  25700. color: this.colorNode,
  25701. lightViewPosition: lightViewPosition( this.light ),
  25702. cutoffDistance: this.cutoffDistanceNode,
  25703. decayExponent: this.decayExponentNode
  25704. } ).append();
  25705. }
  25706. }
  25707. /** @module Procedural **/
  25708. /**
  25709. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  25710. *
  25711. * @method
  25712. * @param {Node<vec2>} coord - The uv coordinates.
  25713. * @return {Node<float>} The result data.
  25714. */
  25715. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  25716. const uv = coord.mul( 2.0 );
  25717. const cx = uv.x.floor();
  25718. const cy = uv.y.floor();
  25719. const result = cx.add( cy ).mod( 2.0 );
  25720. return result.sign();
  25721. } );
  25722. // Three.js Transpiler
  25723. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  25724. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  25725. const f = float( f_immutable ).toVar();
  25726. const t = float( t_immutable ).toVar();
  25727. const b = bool( b_immutable ).toVar();
  25728. return select( b, t, f );
  25729. } ).setLayout( {
  25730. name: 'mx_select',
  25731. type: 'float',
  25732. inputs: [
  25733. { name: 'b', type: 'bool' },
  25734. { name: 't', type: 'float' },
  25735. { name: 'f', type: 'float' }
  25736. ]
  25737. } );
  25738. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  25739. const b = bool( b_immutable ).toVar();
  25740. const val = float( val_immutable ).toVar();
  25741. return select( b, val.negate(), val );
  25742. } ).setLayout( {
  25743. name: 'mx_negate_if',
  25744. type: 'float',
  25745. inputs: [
  25746. { name: 'val', type: 'float' },
  25747. { name: 'b', type: 'bool' }
  25748. ]
  25749. } );
  25750. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  25751. const x = float( x_immutable ).toVar();
  25752. return int( floor( x ) );
  25753. } ).setLayout( {
  25754. name: 'mx_floor',
  25755. type: 'int',
  25756. inputs: [
  25757. { name: 'x', type: 'float' }
  25758. ]
  25759. } );
  25760. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  25761. const x = float( x_immutable ).toVar();
  25762. i.assign( mx_floor( x ) );
  25763. return x.sub( float( i ) );
  25764. } );
  25765. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  25766. const t = float( t_immutable ).toVar();
  25767. const s = float( s_immutable ).toVar();
  25768. const v3 = float( v3_immutable ).toVar();
  25769. const v2 = float( v2_immutable ).toVar();
  25770. const v1 = float( v1_immutable ).toVar();
  25771. const v0 = float( v0_immutable ).toVar();
  25772. const s1 = float( sub( 1.0, s ) ).toVar();
  25773. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  25774. } ).setLayout( {
  25775. name: 'mx_bilerp_0',
  25776. type: 'float',
  25777. inputs: [
  25778. { name: 'v0', type: 'float' },
  25779. { name: 'v1', type: 'float' },
  25780. { name: 'v2', type: 'float' },
  25781. { name: 'v3', type: 'float' },
  25782. { name: 's', type: 'float' },
  25783. { name: 't', type: 'float' }
  25784. ]
  25785. } );
  25786. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  25787. const t = float( t_immutable ).toVar();
  25788. const s = float( s_immutable ).toVar();
  25789. const v3 = vec3( v3_immutable ).toVar();
  25790. const v2 = vec3( v2_immutable ).toVar();
  25791. const v1 = vec3( v1_immutable ).toVar();
  25792. const v0 = vec3( v0_immutable ).toVar();
  25793. const s1 = float( sub( 1.0, s ) ).toVar();
  25794. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  25795. } ).setLayout( {
  25796. name: 'mx_bilerp_1',
  25797. type: 'vec3',
  25798. inputs: [
  25799. { name: 'v0', type: 'vec3' },
  25800. { name: 'v1', type: 'vec3' },
  25801. { name: 'v2', type: 'vec3' },
  25802. { name: 'v3', type: 'vec3' },
  25803. { name: 's', type: 'float' },
  25804. { name: 't', type: 'float' }
  25805. ]
  25806. } );
  25807. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  25808. const mx_trilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  25809. const r = float( r_immutable ).toVar();
  25810. const t = float( t_immutable ).toVar();
  25811. const s = float( s_immutable ).toVar();
  25812. const v7 = float( v7_immutable ).toVar();
  25813. const v6 = float( v6_immutable ).toVar();
  25814. const v5 = float( v5_immutable ).toVar();
  25815. const v4 = float( v4_immutable ).toVar();
  25816. const v3 = float( v3_immutable ).toVar();
  25817. const v2 = float( v2_immutable ).toVar();
  25818. const v1 = float( v1_immutable ).toVar();
  25819. const v0 = float( v0_immutable ).toVar();
  25820. const s1 = float( sub( 1.0, s ) ).toVar();
  25821. const t1 = float( sub( 1.0, t ) ).toVar();
  25822. const r1 = float( sub( 1.0, r ) ).toVar();
  25823. return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) );
  25824. } ).setLayout( {
  25825. name: 'mx_trilerp_0',
  25826. type: 'float',
  25827. inputs: [
  25828. { name: 'v0', type: 'float' },
  25829. { name: 'v1', type: 'float' },
  25830. { name: 'v2', type: 'float' },
  25831. { name: 'v3', type: 'float' },
  25832. { name: 'v4', type: 'float' },
  25833. { name: 'v5', type: 'float' },
  25834. { name: 'v6', type: 'float' },
  25835. { name: 'v7', type: 'float' },
  25836. { name: 's', type: 'float' },
  25837. { name: 't', type: 'float' },
  25838. { name: 'r', type: 'float' }
  25839. ]
  25840. } );
  25841. const mx_trilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  25842. const r = float( r_immutable ).toVar();
  25843. const t = float( t_immutable ).toVar();
  25844. const s = float( s_immutable ).toVar();
  25845. const v7 = vec3( v7_immutable ).toVar();
  25846. const v6 = vec3( v6_immutable ).toVar();
  25847. const v5 = vec3( v5_immutable ).toVar();
  25848. const v4 = vec3( v4_immutable ).toVar();
  25849. const v3 = vec3( v3_immutable ).toVar();
  25850. const v2 = vec3( v2_immutable ).toVar();
  25851. const v1 = vec3( v1_immutable ).toVar();
  25852. const v0 = vec3( v0_immutable ).toVar();
  25853. const s1 = float( sub( 1.0, s ) ).toVar();
  25854. const t1 = float( sub( 1.0, t ) ).toVar();
  25855. const r1 = float( sub( 1.0, r ) ).toVar();
  25856. return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) );
  25857. } ).setLayout( {
  25858. name: 'mx_trilerp_1',
  25859. type: 'vec3',
  25860. inputs: [
  25861. { name: 'v0', type: 'vec3' },
  25862. { name: 'v1', type: 'vec3' },
  25863. { name: 'v2', type: 'vec3' },
  25864. { name: 'v3', type: 'vec3' },
  25865. { name: 'v4', type: 'vec3' },
  25866. { name: 'v5', type: 'vec3' },
  25867. { name: 'v6', type: 'vec3' },
  25868. { name: 'v7', type: 'vec3' },
  25869. { name: 's', type: 'float' },
  25870. { name: 't', type: 'float' },
  25871. { name: 'r', type: 'float' }
  25872. ]
  25873. } );
  25874. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  25875. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  25876. const y = float( y_immutable ).toVar();
  25877. const x = float( x_immutable ).toVar();
  25878. const hash = uint( hash_immutable ).toVar();
  25879. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  25880. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  25881. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  25882. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  25883. } ).setLayout( {
  25884. name: 'mx_gradient_float_0',
  25885. type: 'float',
  25886. inputs: [
  25887. { name: 'hash', type: 'uint' },
  25888. { name: 'x', type: 'float' },
  25889. { name: 'y', type: 'float' }
  25890. ]
  25891. } );
  25892. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  25893. const z = float( z_immutable ).toVar();
  25894. const y = float( y_immutable ).toVar();
  25895. const x = float( x_immutable ).toVar();
  25896. const hash = uint( hash_immutable ).toVar();
  25897. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  25898. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  25899. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  25900. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  25901. } ).setLayout( {
  25902. name: 'mx_gradient_float_1',
  25903. type: 'float',
  25904. inputs: [
  25905. { name: 'hash', type: 'uint' },
  25906. { name: 'x', type: 'float' },
  25907. { name: 'y', type: 'float' },
  25908. { name: 'z', type: 'float' }
  25909. ]
  25910. } );
  25911. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  25912. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  25913. const y = float( y_immutable ).toVar();
  25914. const x = float( x_immutable ).toVar();
  25915. const hash = uvec3( hash_immutable ).toVar();
  25916. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  25917. } ).setLayout( {
  25918. name: 'mx_gradient_vec3_0',
  25919. type: 'vec3',
  25920. inputs: [
  25921. { name: 'hash', type: 'uvec3' },
  25922. { name: 'x', type: 'float' },
  25923. { name: 'y', type: 'float' }
  25924. ]
  25925. } );
  25926. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  25927. const z = float( z_immutable ).toVar();
  25928. const y = float( y_immutable ).toVar();
  25929. const x = float( x_immutable ).toVar();
  25930. const hash = uvec3( hash_immutable ).toVar();
  25931. return vec3( mx_gradient_float( hash.x, x, y, z ), mx_gradient_float( hash.y, x, y, z ), mx_gradient_float( hash.z, x, y, z ) );
  25932. } ).setLayout( {
  25933. name: 'mx_gradient_vec3_1',
  25934. type: 'vec3',
  25935. inputs: [
  25936. { name: 'hash', type: 'uvec3' },
  25937. { name: 'x', type: 'float' },
  25938. { name: 'y', type: 'float' },
  25939. { name: 'z', type: 'float' }
  25940. ]
  25941. } );
  25942. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  25943. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  25944. const v = float( v_immutable ).toVar();
  25945. return mul( 0.6616, v );
  25946. } ).setLayout( {
  25947. name: 'mx_gradient_scale2d_0',
  25948. type: 'float',
  25949. inputs: [
  25950. { name: 'v', type: 'float' }
  25951. ]
  25952. } );
  25953. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  25954. const v = float( v_immutable ).toVar();
  25955. return mul( 0.9820, v );
  25956. } ).setLayout( {
  25957. name: 'mx_gradient_scale3d_0',
  25958. type: 'float',
  25959. inputs: [
  25960. { name: 'v', type: 'float' }
  25961. ]
  25962. } );
  25963. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  25964. const v = vec3( v_immutable ).toVar();
  25965. return mul( 0.6616, v );
  25966. } ).setLayout( {
  25967. name: 'mx_gradient_scale2d_1',
  25968. type: 'vec3',
  25969. inputs: [
  25970. { name: 'v', type: 'vec3' }
  25971. ]
  25972. } );
  25973. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  25974. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  25975. const v = vec3( v_immutable ).toVar();
  25976. return mul( 0.9820, v );
  25977. } ).setLayout( {
  25978. name: 'mx_gradient_scale3d_1',
  25979. type: 'vec3',
  25980. inputs: [
  25981. { name: 'v', type: 'vec3' }
  25982. ]
  25983. } );
  25984. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  25985. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  25986. const k = int( k_immutable ).toVar();
  25987. const x = uint( x_immutable ).toVar();
  25988. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  25989. } ).setLayout( {
  25990. name: 'mx_rotl32',
  25991. type: 'uint',
  25992. inputs: [
  25993. { name: 'x', type: 'uint' },
  25994. { name: 'k', type: 'int' }
  25995. ]
  25996. } );
  25997. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  25998. a.subAssign( c );
  25999. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  26000. c.addAssign( b );
  26001. b.subAssign( a );
  26002. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  26003. a.addAssign( c );
  26004. c.subAssign( b );
  26005. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  26006. b.addAssign( a );
  26007. a.subAssign( c );
  26008. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  26009. c.addAssign( b );
  26010. b.subAssign( a );
  26011. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  26012. a.addAssign( c );
  26013. c.subAssign( b );
  26014. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  26015. b.addAssign( a );
  26016. } );
  26017. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  26018. const c = uint( c_immutable ).toVar();
  26019. const b = uint( b_immutable ).toVar();
  26020. const a = uint( a_immutable ).toVar();
  26021. c.bitXorAssign( b );
  26022. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  26023. a.bitXorAssign( c );
  26024. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  26025. b.bitXorAssign( a );
  26026. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  26027. c.bitXorAssign( b );
  26028. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  26029. a.bitXorAssign( c );
  26030. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  26031. b.bitXorAssign( a );
  26032. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  26033. c.bitXorAssign( b );
  26034. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  26035. return c;
  26036. } ).setLayout( {
  26037. name: 'mx_bjfinal',
  26038. type: 'uint',
  26039. inputs: [
  26040. { name: 'a', type: 'uint' },
  26041. { name: 'b', type: 'uint' },
  26042. { name: 'c', type: 'uint' }
  26043. ]
  26044. } );
  26045. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  26046. const bits = uint( bits_immutable ).toVar();
  26047. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  26048. } ).setLayout( {
  26049. name: 'mx_bits_to_01',
  26050. type: 'float',
  26051. inputs: [
  26052. { name: 'bits', type: 'uint' }
  26053. ]
  26054. } );
  26055. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  26056. const t = float( t_immutable ).toVar();
  26057. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  26058. } ).setLayout( {
  26059. name: 'mx_fade',
  26060. type: 'float',
  26061. inputs: [
  26062. { name: 't', type: 'float' }
  26063. ]
  26064. } );
  26065. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26066. const x = int( x_immutable ).toVar();
  26067. const len = uint( uint( 1 ) ).toVar();
  26068. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  26069. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  26070. } ).setLayout( {
  26071. name: 'mx_hash_int_0',
  26072. type: 'uint',
  26073. inputs: [
  26074. { name: 'x', type: 'int' }
  26075. ]
  26076. } );
  26077. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26078. const y = int( y_immutable ).toVar();
  26079. const x = int( x_immutable ).toVar();
  26080. const len = uint( uint( 2 ) ).toVar();
  26081. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26082. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26083. a.addAssign( uint( x ) );
  26084. b.addAssign( uint( y ) );
  26085. return mx_bjfinal( a, b, c );
  26086. } ).setLayout( {
  26087. name: 'mx_hash_int_1',
  26088. type: 'uint',
  26089. inputs: [
  26090. { name: 'x', type: 'int' },
  26091. { name: 'y', type: 'int' }
  26092. ]
  26093. } );
  26094. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26095. const z = int( z_immutable ).toVar();
  26096. const y = int( y_immutable ).toVar();
  26097. const x = int( x_immutable ).toVar();
  26098. const len = uint( uint( 3 ) ).toVar();
  26099. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26100. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26101. a.addAssign( uint( x ) );
  26102. b.addAssign( uint( y ) );
  26103. c.addAssign( uint( z ) );
  26104. return mx_bjfinal( a, b, c );
  26105. } ).setLayout( {
  26106. name: 'mx_hash_int_2',
  26107. type: 'uint',
  26108. inputs: [
  26109. { name: 'x', type: 'int' },
  26110. { name: 'y', type: 'int' },
  26111. { name: 'z', type: 'int' }
  26112. ]
  26113. } );
  26114. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  26115. const xx = int( xx_immutable ).toVar();
  26116. const z = int( z_immutable ).toVar();
  26117. const y = int( y_immutable ).toVar();
  26118. const x = int( x_immutable ).toVar();
  26119. const len = uint( uint( 4 ) ).toVar();
  26120. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26121. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26122. a.addAssign( uint( x ) );
  26123. b.addAssign( uint( y ) );
  26124. c.addAssign( uint( z ) );
  26125. mx_bjmix( a, b, c );
  26126. a.addAssign( uint( xx ) );
  26127. return mx_bjfinal( a, b, c );
  26128. } ).setLayout( {
  26129. name: 'mx_hash_int_3',
  26130. type: 'uint',
  26131. inputs: [
  26132. { name: 'x', type: 'int' },
  26133. { name: 'y', type: 'int' },
  26134. { name: 'z', type: 'int' },
  26135. { name: 'xx', type: 'int' }
  26136. ]
  26137. } );
  26138. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  26139. const yy = int( yy_immutable ).toVar();
  26140. const xx = int( xx_immutable ).toVar();
  26141. const z = int( z_immutable ).toVar();
  26142. const y = int( y_immutable ).toVar();
  26143. const x = int( x_immutable ).toVar();
  26144. const len = uint( uint( 5 ) ).toVar();
  26145. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26146. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26147. a.addAssign( uint( x ) );
  26148. b.addAssign( uint( y ) );
  26149. c.addAssign( uint( z ) );
  26150. mx_bjmix( a, b, c );
  26151. a.addAssign( uint( xx ) );
  26152. b.addAssign( uint( yy ) );
  26153. return mx_bjfinal( a, b, c );
  26154. } ).setLayout( {
  26155. name: 'mx_hash_int_4',
  26156. type: 'uint',
  26157. inputs: [
  26158. { name: 'x', type: 'int' },
  26159. { name: 'y', type: 'int' },
  26160. { name: 'z', type: 'int' },
  26161. { name: 'xx', type: 'int' },
  26162. { name: 'yy', type: 'int' }
  26163. ]
  26164. } );
  26165. const mx_hash_int = /*@__PURE__*/ overloadingFn( [ mx_hash_int_0, mx_hash_int_1, mx_hash_int_2, mx_hash_int_3, mx_hash_int_4 ] );
  26166. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26167. const y = int( y_immutable ).toVar();
  26168. const x = int( x_immutable ).toVar();
  26169. const h = uint( mx_hash_int( x, y ) ).toVar();
  26170. const result = uvec3().toVar();
  26171. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26172. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26173. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26174. return result;
  26175. } ).setLayout( {
  26176. name: 'mx_hash_vec3_0',
  26177. type: 'uvec3',
  26178. inputs: [
  26179. { name: 'x', type: 'int' },
  26180. { name: 'y', type: 'int' }
  26181. ]
  26182. } );
  26183. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26184. const z = int( z_immutable ).toVar();
  26185. const y = int( y_immutable ).toVar();
  26186. const x = int( x_immutable ).toVar();
  26187. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  26188. const result = uvec3().toVar();
  26189. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26190. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26191. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26192. return result;
  26193. } ).setLayout( {
  26194. name: 'mx_hash_vec3_1',
  26195. type: 'uvec3',
  26196. inputs: [
  26197. { name: 'x', type: 'int' },
  26198. { name: 'y', type: 'int' },
  26199. { name: 'z', type: 'int' }
  26200. ]
  26201. } );
  26202. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  26203. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26204. const p = vec2( p_immutable ).toVar();
  26205. const X = int().toVar(), Y = int().toVar();
  26206. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26207. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26208. const u = float( mx_fade( fx ) ).toVar();
  26209. const v = float( mx_fade( fy ) ).toVar();
  26210. const result = float( mx_bilerp( mx_gradient_float( mx_hash_int( X, Y ), fx, fy ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar();
  26211. return mx_gradient_scale2d( result );
  26212. } ).setLayout( {
  26213. name: 'mx_perlin_noise_float_0',
  26214. type: 'float',
  26215. inputs: [
  26216. { name: 'p', type: 'vec2' }
  26217. ]
  26218. } );
  26219. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26220. const p = vec3( p_immutable ).toVar();
  26221. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26222. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26223. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26224. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26225. const u = float( mx_fade( fx ) ).toVar();
  26226. const v = float( mx_fade( fy ) ).toVar();
  26227. const w = float( mx_fade( fz ) ).toVar();
  26228. const result = float( mx_trilerp( mx_gradient_float( mx_hash_int( X, Y, Z ), fx, fy, fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar();
  26229. return mx_gradient_scale3d( result );
  26230. } ).setLayout( {
  26231. name: 'mx_perlin_noise_float_1',
  26232. type: 'float',
  26233. inputs: [
  26234. { name: 'p', type: 'vec3' }
  26235. ]
  26236. } );
  26237. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  26238. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26239. const p = vec2( p_immutable ).toVar();
  26240. const X = int().toVar(), Y = int().toVar();
  26241. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26242. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26243. const u = float( mx_fade( fx ) ).toVar();
  26244. const v = float( mx_fade( fy ) ).toVar();
  26245. const result = vec3( mx_bilerp( mx_gradient_vec3( mx_hash_vec3( X, Y ), fx, fy ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar();
  26246. return mx_gradient_scale2d( result );
  26247. } ).setLayout( {
  26248. name: 'mx_perlin_noise_vec3_0',
  26249. type: 'vec3',
  26250. inputs: [
  26251. { name: 'p', type: 'vec2' }
  26252. ]
  26253. } );
  26254. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26255. const p = vec3( p_immutable ).toVar();
  26256. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26257. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26258. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26259. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26260. const u = float( mx_fade( fx ) ).toVar();
  26261. const v = float( mx_fade( fy ) ).toVar();
  26262. const w = float( mx_fade( fz ) ).toVar();
  26263. const result = vec3( mx_trilerp( mx_gradient_vec3( mx_hash_vec3( X, Y, Z ), fx, fy, fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar();
  26264. return mx_gradient_scale3d( result );
  26265. } ).setLayout( {
  26266. name: 'mx_perlin_noise_vec3_1',
  26267. type: 'vec3',
  26268. inputs: [
  26269. { name: 'p', type: 'vec3' }
  26270. ]
  26271. } );
  26272. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  26273. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26274. const p = float( p_immutable ).toVar();
  26275. const ix = int( mx_floor( p ) ).toVar();
  26276. return mx_bits_to_01( mx_hash_int( ix ) );
  26277. } ).setLayout( {
  26278. name: 'mx_cell_noise_float_0',
  26279. type: 'float',
  26280. inputs: [
  26281. { name: 'p', type: 'float' }
  26282. ]
  26283. } );
  26284. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26285. const p = vec2( p_immutable ).toVar();
  26286. const ix = int( mx_floor( p.x ) ).toVar();
  26287. const iy = int( mx_floor( p.y ) ).toVar();
  26288. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  26289. } ).setLayout( {
  26290. name: 'mx_cell_noise_float_1',
  26291. type: 'float',
  26292. inputs: [
  26293. { name: 'p', type: 'vec2' }
  26294. ]
  26295. } );
  26296. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26297. const p = vec3( p_immutable ).toVar();
  26298. const ix = int( mx_floor( p.x ) ).toVar();
  26299. const iy = int( mx_floor( p.y ) ).toVar();
  26300. const iz = int( mx_floor( p.z ) ).toVar();
  26301. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  26302. } ).setLayout( {
  26303. name: 'mx_cell_noise_float_2',
  26304. type: 'float',
  26305. inputs: [
  26306. { name: 'p', type: 'vec3' }
  26307. ]
  26308. } );
  26309. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26310. const p = vec4( p_immutable ).toVar();
  26311. const ix = int( mx_floor( p.x ) ).toVar();
  26312. const iy = int( mx_floor( p.y ) ).toVar();
  26313. const iz = int( mx_floor( p.z ) ).toVar();
  26314. const iw = int( mx_floor( p.w ) ).toVar();
  26315. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  26316. } ).setLayout( {
  26317. name: 'mx_cell_noise_float_3',
  26318. type: 'float',
  26319. inputs: [
  26320. { name: 'p', type: 'vec4' }
  26321. ]
  26322. } );
  26323. const mx_cell_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_float_0, mx_cell_noise_float_1, mx_cell_noise_float_2, mx_cell_noise_float_3 ] );
  26324. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26325. const p = float( p_immutable ).toVar();
  26326. const ix = int( mx_floor( p ) ).toVar();
  26327. return vec3( mx_bits_to_01( mx_hash_int( ix, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 2 ) ) ) );
  26328. } ).setLayout( {
  26329. name: 'mx_cell_noise_vec3_0',
  26330. type: 'vec3',
  26331. inputs: [
  26332. { name: 'p', type: 'float' }
  26333. ]
  26334. } );
  26335. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26336. const p = vec2( p_immutable ).toVar();
  26337. const ix = int( mx_floor( p.x ) ).toVar();
  26338. const iy = int( mx_floor( p.y ) ).toVar();
  26339. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 2 ) ) ) );
  26340. } ).setLayout( {
  26341. name: 'mx_cell_noise_vec3_1',
  26342. type: 'vec3',
  26343. inputs: [
  26344. { name: 'p', type: 'vec2' }
  26345. ]
  26346. } );
  26347. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26348. const p = vec3( p_immutable ).toVar();
  26349. const ix = int( mx_floor( p.x ) ).toVar();
  26350. const iy = int( mx_floor( p.y ) ).toVar();
  26351. const iz = int( mx_floor( p.z ) ).toVar();
  26352. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 2 ) ) ) );
  26353. } ).setLayout( {
  26354. name: 'mx_cell_noise_vec3_2',
  26355. type: 'vec3',
  26356. inputs: [
  26357. { name: 'p', type: 'vec3' }
  26358. ]
  26359. } );
  26360. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26361. const p = vec4( p_immutable ).toVar();
  26362. const ix = int( mx_floor( p.x ) ).toVar();
  26363. const iy = int( mx_floor( p.y ) ).toVar();
  26364. const iz = int( mx_floor( p.z ) ).toVar();
  26365. const iw = int( mx_floor( p.w ) ).toVar();
  26366. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 2 ) ) ) );
  26367. } ).setLayout( {
  26368. name: 'mx_cell_noise_vec3_3',
  26369. type: 'vec3',
  26370. inputs: [
  26371. { name: 'p', type: 'vec4' }
  26372. ]
  26373. } );
  26374. const mx_cell_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_vec3_0, mx_cell_noise_vec3_1, mx_cell_noise_vec3_2, mx_cell_noise_vec3_3 ] );
  26375. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26376. const diminish = float( diminish_immutable ).toVar();
  26377. const lacunarity = float( lacunarity_immutable ).toVar();
  26378. const octaves = int( octaves_immutable ).toVar();
  26379. const p = vec3( p_immutable ).toVar();
  26380. const result = float( 0.0 ).toVar();
  26381. const amplitude = float( 1.0 ).toVar();
  26382. Loop( octaves, () => {
  26383. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  26384. amplitude.mulAssign( diminish );
  26385. p.mulAssign( lacunarity );
  26386. } );
  26387. return result;
  26388. } ).setLayout( {
  26389. name: 'mx_fractal_noise_float',
  26390. type: 'float',
  26391. inputs: [
  26392. { name: 'p', type: 'vec3' },
  26393. { name: 'octaves', type: 'int' },
  26394. { name: 'lacunarity', type: 'float' },
  26395. { name: 'diminish', type: 'float' }
  26396. ]
  26397. } );
  26398. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26399. const diminish = float( diminish_immutable ).toVar();
  26400. const lacunarity = float( lacunarity_immutable ).toVar();
  26401. const octaves = int( octaves_immutable ).toVar();
  26402. const p = vec3( p_immutable ).toVar();
  26403. const result = vec3( 0.0 ).toVar();
  26404. const amplitude = float( 1.0 ).toVar();
  26405. Loop( octaves, () => {
  26406. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  26407. amplitude.mulAssign( diminish );
  26408. p.mulAssign( lacunarity );
  26409. } );
  26410. return result;
  26411. } ).setLayout( {
  26412. name: 'mx_fractal_noise_vec3',
  26413. type: 'vec3',
  26414. inputs: [
  26415. { name: 'p', type: 'vec3' },
  26416. { name: 'octaves', type: 'int' },
  26417. { name: 'lacunarity', type: 'float' },
  26418. { name: 'diminish', type: 'float' }
  26419. ]
  26420. } );
  26421. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26422. const diminish = float( diminish_immutable ).toVar();
  26423. const lacunarity = float( lacunarity_immutable ).toVar();
  26424. const octaves = int( octaves_immutable ).toVar();
  26425. const p = vec3( p_immutable ).toVar();
  26426. return vec2( mx_fractal_noise_float$1( p, octaves, lacunarity, diminish ), mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) );
  26427. } ).setLayout( {
  26428. name: 'mx_fractal_noise_vec2',
  26429. type: 'vec2',
  26430. inputs: [
  26431. { name: 'p', type: 'vec3' },
  26432. { name: 'octaves', type: 'int' },
  26433. { name: 'lacunarity', type: 'float' },
  26434. { name: 'diminish', type: 'float' }
  26435. ]
  26436. } );
  26437. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26438. const diminish = float( diminish_immutable ).toVar();
  26439. const lacunarity = float( lacunarity_immutable ).toVar();
  26440. const octaves = int( octaves_immutable ).toVar();
  26441. const p = vec3( p_immutable ).toVar();
  26442. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  26443. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  26444. return vec4( c, f );
  26445. } ).setLayout( {
  26446. name: 'mx_fractal_noise_vec4',
  26447. type: 'vec4',
  26448. inputs: [
  26449. { name: 'p', type: 'vec3' },
  26450. { name: 'octaves', type: 'int' },
  26451. { name: 'lacunarity', type: 'float' },
  26452. { name: 'diminish', type: 'float' }
  26453. ]
  26454. } );
  26455. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  26456. const metric = int( metric_immutable ).toVar();
  26457. const jitter = float( jitter_immutable ).toVar();
  26458. const yoff = int( yoff_immutable ).toVar();
  26459. const xoff = int( xoff_immutable ).toVar();
  26460. const y = int( y_immutable ).toVar();
  26461. const x = int( x_immutable ).toVar();
  26462. const p = vec2( p_immutable ).toVar();
  26463. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  26464. const off = vec2( tmp.x, tmp.y ).toVar();
  26465. off.subAssign( 0.5 );
  26466. off.mulAssign( jitter );
  26467. off.addAssign( 0.5 );
  26468. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  26469. const diff = vec2( cellpos.sub( p ) ).toVar();
  26470. If( metric.equal( int( 2 ) ), () => {
  26471. return abs( diff.x ).add( abs( diff.y ) );
  26472. } );
  26473. If( metric.equal( int( 3 ) ), () => {
  26474. return max$1( abs( diff.x ), abs( diff.y ) );
  26475. } );
  26476. return dot( diff, diff );
  26477. } ).setLayout( {
  26478. name: 'mx_worley_distance_0',
  26479. type: 'float',
  26480. inputs: [
  26481. { name: 'p', type: 'vec2' },
  26482. { name: 'x', type: 'int' },
  26483. { name: 'y', type: 'int' },
  26484. { name: 'xoff', type: 'int' },
  26485. { name: 'yoff', type: 'int' },
  26486. { name: 'jitter', type: 'float' },
  26487. { name: 'metric', type: 'int' }
  26488. ]
  26489. } );
  26490. const mx_worley_distance_1 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => {
  26491. const metric = int( metric_immutable ).toVar();
  26492. const jitter = float( jitter_immutable ).toVar();
  26493. const zoff = int( zoff_immutable ).toVar();
  26494. const yoff = int( yoff_immutable ).toVar();
  26495. const xoff = int( xoff_immutable ).toVar();
  26496. const z = int( z_immutable ).toVar();
  26497. const y = int( y_immutable ).toVar();
  26498. const x = int( x_immutable ).toVar();
  26499. const p = vec3( p_immutable ).toVar();
  26500. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  26501. off.subAssign( 0.5 );
  26502. off.mulAssign( jitter );
  26503. off.addAssign( 0.5 );
  26504. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  26505. const diff = vec3( cellpos.sub( p ) ).toVar();
  26506. If( metric.equal( int( 2 ) ), () => {
  26507. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  26508. } );
  26509. If( metric.equal( int( 3 ) ), () => {
  26510. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  26511. } );
  26512. return dot( diff, diff );
  26513. } ).setLayout( {
  26514. name: 'mx_worley_distance_1',
  26515. type: 'float',
  26516. inputs: [
  26517. { name: 'p', type: 'vec3' },
  26518. { name: 'x', type: 'int' },
  26519. { name: 'y', type: 'int' },
  26520. { name: 'z', type: 'int' },
  26521. { name: 'xoff', type: 'int' },
  26522. { name: 'yoff', type: 'int' },
  26523. { name: 'zoff', type: 'int' },
  26524. { name: 'jitter', type: 'float' },
  26525. { name: 'metric', type: 'int' }
  26526. ]
  26527. } );
  26528. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  26529. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26530. const metric = int( metric_immutable ).toVar();
  26531. const jitter = float( jitter_immutable ).toVar();
  26532. const p = vec2( p_immutable ).toVar();
  26533. const X = int().toVar(), Y = int().toVar();
  26534. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26535. const sqdist = float( 1e6 ).toVar();
  26536. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26537. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26538. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26539. sqdist.assign( min$1( sqdist, dist ) );
  26540. } );
  26541. } );
  26542. If( metric.equal( int( 0 ) ), () => {
  26543. sqdist.assign( sqrt( sqdist ) );
  26544. } );
  26545. return sqdist;
  26546. } ).setLayout( {
  26547. name: 'mx_worley_noise_float_0',
  26548. type: 'float',
  26549. inputs: [
  26550. { name: 'p', type: 'vec2' },
  26551. { name: 'jitter', type: 'float' },
  26552. { name: 'metric', type: 'int' }
  26553. ]
  26554. } );
  26555. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26556. const metric = int( metric_immutable ).toVar();
  26557. const jitter = float( jitter_immutable ).toVar();
  26558. const p = vec2( p_immutable ).toVar();
  26559. const X = int().toVar(), Y = int().toVar();
  26560. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26561. const sqdist = vec2( 1e6, 1e6 ).toVar();
  26562. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26563. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26564. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26565. If( dist.lessThan( sqdist.x ), () => {
  26566. sqdist.y.assign( sqdist.x );
  26567. sqdist.x.assign( dist );
  26568. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26569. sqdist.y.assign( dist );
  26570. } );
  26571. } );
  26572. } );
  26573. If( metric.equal( int( 0 ) ), () => {
  26574. sqdist.assign( sqrt( sqdist ) );
  26575. } );
  26576. return sqdist;
  26577. } ).setLayout( {
  26578. name: 'mx_worley_noise_vec2_0',
  26579. type: 'vec2',
  26580. inputs: [
  26581. { name: 'p', type: 'vec2' },
  26582. { name: 'jitter', type: 'float' },
  26583. { name: 'metric', type: 'int' }
  26584. ]
  26585. } );
  26586. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26587. const metric = int( metric_immutable ).toVar();
  26588. const jitter = float( jitter_immutable ).toVar();
  26589. const p = vec2( p_immutable ).toVar();
  26590. const X = int().toVar(), Y = int().toVar();
  26591. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26592. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  26593. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26594. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26595. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26596. If( dist.lessThan( sqdist.x ), () => {
  26597. sqdist.z.assign( sqdist.y );
  26598. sqdist.y.assign( sqdist.x );
  26599. sqdist.x.assign( dist );
  26600. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26601. sqdist.z.assign( sqdist.y );
  26602. sqdist.y.assign( dist );
  26603. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  26604. sqdist.z.assign( dist );
  26605. } );
  26606. } );
  26607. } );
  26608. If( metric.equal( int( 0 ) ), () => {
  26609. sqdist.assign( sqrt( sqdist ) );
  26610. } );
  26611. return sqdist;
  26612. } ).setLayout( {
  26613. name: 'mx_worley_noise_vec3_0',
  26614. type: 'vec3',
  26615. inputs: [
  26616. { name: 'p', type: 'vec2' },
  26617. { name: 'jitter', type: 'float' },
  26618. { name: 'metric', type: 'int' }
  26619. ]
  26620. } );
  26621. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26622. const metric = int( metric_immutable ).toVar();
  26623. const jitter = float( jitter_immutable ).toVar();
  26624. const p = vec3( p_immutable ).toVar();
  26625. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26626. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26627. const sqdist = float( 1e6 ).toVar();
  26628. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26629. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26630. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26631. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26632. sqdist.assign( min$1( sqdist, dist ) );
  26633. } );
  26634. } );
  26635. } );
  26636. If( metric.equal( int( 0 ) ), () => {
  26637. sqdist.assign( sqrt( sqdist ) );
  26638. } );
  26639. return sqdist;
  26640. } ).setLayout( {
  26641. name: 'mx_worley_noise_float_1',
  26642. type: 'float',
  26643. inputs: [
  26644. { name: 'p', type: 'vec3' },
  26645. { name: 'jitter', type: 'float' },
  26646. { name: 'metric', type: 'int' }
  26647. ]
  26648. } );
  26649. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  26650. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26651. const metric = int( metric_immutable ).toVar();
  26652. const jitter = float( jitter_immutable ).toVar();
  26653. const p = vec3( p_immutable ).toVar();
  26654. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26655. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26656. const sqdist = vec2( 1e6, 1e6 ).toVar();
  26657. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26658. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26659. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26660. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26661. If( dist.lessThan( sqdist.x ), () => {
  26662. sqdist.y.assign( sqdist.x );
  26663. sqdist.x.assign( dist );
  26664. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26665. sqdist.y.assign( dist );
  26666. } );
  26667. } );
  26668. } );
  26669. } );
  26670. If( metric.equal( int( 0 ) ), () => {
  26671. sqdist.assign( sqrt( sqdist ) );
  26672. } );
  26673. return sqdist;
  26674. } ).setLayout( {
  26675. name: 'mx_worley_noise_vec2_1',
  26676. type: 'vec2',
  26677. inputs: [
  26678. { name: 'p', type: 'vec3' },
  26679. { name: 'jitter', type: 'float' },
  26680. { name: 'metric', type: 'int' }
  26681. ]
  26682. } );
  26683. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  26684. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26685. const metric = int( metric_immutable ).toVar();
  26686. const jitter = float( jitter_immutable ).toVar();
  26687. const p = vec3( p_immutable ).toVar();
  26688. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26689. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26690. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  26691. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26692. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26693. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26694. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26695. If( dist.lessThan( sqdist.x ), () => {
  26696. sqdist.z.assign( sqdist.y );
  26697. sqdist.y.assign( sqdist.x );
  26698. sqdist.x.assign( dist );
  26699. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26700. sqdist.z.assign( sqdist.y );
  26701. sqdist.y.assign( dist );
  26702. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  26703. sqdist.z.assign( dist );
  26704. } );
  26705. } );
  26706. } );
  26707. } );
  26708. If( metric.equal( int( 0 ) ), () => {
  26709. sqdist.assign( sqrt( sqdist ) );
  26710. } );
  26711. return sqdist;
  26712. } ).setLayout( {
  26713. name: 'mx_worley_noise_vec3_1',
  26714. type: 'vec3',
  26715. inputs: [
  26716. { name: 'p', type: 'vec3' },
  26717. { name: 'jitter', type: 'float' },
  26718. { name: 'metric', type: 'int' }
  26719. ]
  26720. } );
  26721. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  26722. // Three.js Transpiler
  26723. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  26724. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  26725. const s = hsv.y;
  26726. const v = hsv.z;
  26727. const result = vec3().toVar();
  26728. If( s.lessThan( 0.0001 ), () => {
  26729. result.assign( vec3( v, v, v ) );
  26730. } ).Else( () => {
  26731. let h = hsv.x;
  26732. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  26733. const hi = int( trunc( h ) );
  26734. const f = h.sub( float( hi ) );
  26735. const p = v.mul( s.oneMinus() );
  26736. const q = v.mul( s.mul( f ).oneMinus() );
  26737. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  26738. If( hi.equal( int( 0 ) ), () => {
  26739. result.assign( vec3( v, t, p ) );
  26740. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  26741. result.assign( vec3( q, v, p ) );
  26742. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  26743. result.assign( vec3( p, v, t ) );
  26744. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  26745. result.assign( vec3( p, q, v ) );
  26746. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  26747. result.assign( vec3( t, p, v ) );
  26748. } ).Else( () => {
  26749. result.assign( vec3( v, p, q ) );
  26750. } );
  26751. } );
  26752. return result;
  26753. } ).setLayout( {
  26754. name: 'mx_hsvtorgb',
  26755. type: 'vec3',
  26756. inputs: [
  26757. { name: 'hsv', type: 'vec3' }
  26758. ]
  26759. } );
  26760. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  26761. const c = vec3( c_immutable ).toVar();
  26762. const r = float( c.x ).toVar();
  26763. const g = float( c.y ).toVar();
  26764. const b = float( c.z ).toVar();
  26765. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  26766. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  26767. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  26768. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  26769. v.assign( maxcomp );
  26770. If( maxcomp.greaterThan( 0.0 ), () => {
  26771. s.assign( delta.div( maxcomp ) );
  26772. } ).Else( () => {
  26773. s.assign( 0.0 );
  26774. } );
  26775. If( s.lessThanEqual( 0.0 ), () => {
  26776. h.assign( 0.0 );
  26777. } ).Else( () => {
  26778. If( r.greaterThanEqual( maxcomp ), () => {
  26779. h.assign( g.sub( b ).div( delta ) );
  26780. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  26781. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  26782. } ).Else( () => {
  26783. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  26784. } );
  26785. h.mulAssign( 1.0 / 6.0 );
  26786. If( h.lessThan( 0.0 ), () => {
  26787. h.addAssign( 1.0 );
  26788. } );
  26789. } );
  26790. return vec3( h, s, v );
  26791. } ).setLayout( {
  26792. name: 'mx_rgbtohsv',
  26793. type: 'vec3',
  26794. inputs: [
  26795. { name: 'c', type: 'vec3' }
  26796. ]
  26797. } );
  26798. // Three.js Transpiler
  26799. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  26800. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  26801. const color = vec3( color_immutable ).toVar();
  26802. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  26803. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  26804. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  26805. return mix( linSeg, powSeg, isAbove );
  26806. } ).setLayout( {
  26807. name: 'mx_srgb_texture_to_lin_rec709',
  26808. type: 'vec3',
  26809. inputs: [
  26810. { name: 'color', type: 'vec3' }
  26811. ]
  26812. } );
  26813. const mx_aastep = ( threshold, value ) => {
  26814. threshold = float( threshold );
  26815. value = float( value );
  26816. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  26817. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  26818. };
  26819. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  26820. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  26821. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  26822. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  26823. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  26824. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  26825. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  26826. const mx_safepower = ( in1, in2 = 1 ) => {
  26827. in1 = float( in1 );
  26828. return in1.abs().pow( in2 ).mul( in1.sign() );
  26829. };
  26830. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  26831. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  26832. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  26833. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  26834. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  26835. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  26836. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  26837. return noise_vec4.mul( amplitude ).add( pivot );
  26838. };
  26839. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  26840. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  26841. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  26842. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  26843. const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  26844. const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  26845. const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  26846. const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  26847. /** @module getParallaxCorrectNormal **/
  26848. /**
  26849. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  26850. *
  26851. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  26852. *
  26853. * ```js
  26854. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  26855. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  26856. * ```
  26857. * @function
  26858. * @param {Node<vec3>} normal - The normal to correct.
  26859. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  26860. * @param {Node<vec3>} cubePos - The cube position.
  26861. * @return {Node<vec3>} The parallax corrected normal.
  26862. */
  26863. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  26864. const nDir = normalize( normal ).toVar( 'nDir' );
  26865. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  26866. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  26867. const rbminmax = vec3().toVar( 'rbminmax' );
  26868. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  26869. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  26870. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  26871. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  26872. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  26873. return boxIntersection.sub( cubePos );
  26874. } );
  26875. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  26876. // normal is assumed to have unit length
  26877. const x = normal.x, y = normal.y, z = normal.z;
  26878. // band 0
  26879. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  26880. // band 1
  26881. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  26882. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  26883. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  26884. // band 2
  26885. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  26886. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  26887. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  26888. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  26889. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  26890. return result;
  26891. } );
  26892. // constants
  26893. var TSL = /*#__PURE__*/Object.freeze({
  26894. __proto__: null,
  26895. BRDF_GGX: BRDF_GGX,
  26896. BRDF_Lambert: BRDF_Lambert,
  26897. BasicShadowFilter: BasicShadowFilter,
  26898. Break: Break,
  26899. Continue: Continue,
  26900. DFGApprox: DFGApprox,
  26901. D_GGX: D_GGX,
  26902. Discard: Discard,
  26903. EPSILON: EPSILON,
  26904. F_Schlick: F_Schlick,
  26905. Fn: Fn,
  26906. INFINITY: INFINITY,
  26907. If: If,
  26908. Loop: Loop,
  26909. NodeAccess: NodeAccess,
  26910. NodeShaderStage: NodeShaderStage,
  26911. NodeType: NodeType,
  26912. NodeUpdateType: NodeUpdateType,
  26913. PCFShadowFilter: PCFShadowFilter,
  26914. PCFSoftShadowFilter: PCFSoftShadowFilter,
  26915. PI: PI,
  26916. PI2: PI2,
  26917. Return: Return,
  26918. Schlick_to_F0: Schlick_to_F0,
  26919. ScriptableNodeResources: ScriptableNodeResources,
  26920. ShaderNode: ShaderNode,
  26921. TBNViewMatrix: TBNViewMatrix,
  26922. VSMShadowFilter: VSMShadowFilter,
  26923. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  26924. abs: abs,
  26925. acesFilmicToneMapping: acesFilmicToneMapping,
  26926. acos: acos,
  26927. add: add,
  26928. addMethodChaining: addMethodChaining,
  26929. addNodeElement: addNodeElement,
  26930. agxToneMapping: agxToneMapping,
  26931. all: all,
  26932. alphaT: alphaT,
  26933. and: and,
  26934. anisotropy: anisotropy,
  26935. anisotropyB: anisotropyB,
  26936. anisotropyT: anisotropyT,
  26937. any: any,
  26938. append: append,
  26939. arrayBuffer: arrayBuffer,
  26940. asin: asin,
  26941. assign: assign,
  26942. atan: atan,
  26943. atan2: atan2,
  26944. atomicAdd: atomicAdd,
  26945. atomicAnd: atomicAnd,
  26946. atomicFunc: atomicFunc,
  26947. atomicMax: atomicMax,
  26948. atomicMin: atomicMin,
  26949. atomicOr: atomicOr,
  26950. atomicStore: atomicStore,
  26951. atomicSub: atomicSub,
  26952. atomicXor: atomicXor,
  26953. attenuationColor: attenuationColor,
  26954. attenuationDistance: attenuationDistance,
  26955. attribute: attribute,
  26956. attributeArray: attributeArray,
  26957. backgroundBlurriness: backgroundBlurriness,
  26958. backgroundIntensity: backgroundIntensity,
  26959. backgroundRotation: backgroundRotation,
  26960. batch: batch,
  26961. billboarding: billboarding,
  26962. bitAnd: bitAnd,
  26963. bitNot: bitNot,
  26964. bitOr: bitOr,
  26965. bitXor: bitXor,
  26966. bitangentGeometry: bitangentGeometry,
  26967. bitangentLocal: bitangentLocal,
  26968. bitangentView: bitangentView,
  26969. bitangentWorld: bitangentWorld,
  26970. bitcast: bitcast,
  26971. blendBurn: blendBurn,
  26972. blendColor: blendColor,
  26973. blendDodge: blendDodge,
  26974. blendOverlay: blendOverlay,
  26975. blendScreen: blendScreen,
  26976. blur: blur,
  26977. bool: bool,
  26978. buffer: buffer,
  26979. bufferAttribute: bufferAttribute,
  26980. bumpMap: bumpMap,
  26981. burn: burn,
  26982. bvec2: bvec2,
  26983. bvec3: bvec3,
  26984. bvec4: bvec4,
  26985. bypass: bypass,
  26986. cache: cache,
  26987. call: call,
  26988. cameraFar: cameraFar,
  26989. cameraNear: cameraNear,
  26990. cameraNormalMatrix: cameraNormalMatrix,
  26991. cameraPosition: cameraPosition,
  26992. cameraProjectionMatrix: cameraProjectionMatrix,
  26993. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  26994. cameraViewMatrix: cameraViewMatrix,
  26995. cameraWorldMatrix: cameraWorldMatrix,
  26996. cbrt: cbrt,
  26997. cdl: cdl,
  26998. ceil: ceil,
  26999. checker: checker,
  27000. cineonToneMapping: cineonToneMapping,
  27001. clamp: clamp,
  27002. clearcoat: clearcoat,
  27003. clearcoatRoughness: clearcoatRoughness,
  27004. code: code,
  27005. color: color,
  27006. colorSpaceToWorking: colorSpaceToWorking,
  27007. colorToDirection: colorToDirection,
  27008. compute: compute,
  27009. cond: cond,
  27010. context: context,
  27011. convert: convert,
  27012. convertColorSpace: convertColorSpace,
  27013. convertToTexture: convertToTexture,
  27014. cos: cos,
  27015. cross: cross,
  27016. cubeTexture: cubeTexture,
  27017. dFdx: dFdx,
  27018. dFdy: dFdy,
  27019. dashSize: dashSize,
  27020. defaultBuildStages: defaultBuildStages,
  27021. defaultShaderStages: defaultShaderStages,
  27022. defined: defined,
  27023. degrees: degrees,
  27024. deltaTime: deltaTime,
  27025. densityFog: densityFog,
  27026. densityFogFactor: densityFogFactor,
  27027. depth: depth,
  27028. depthPass: depthPass,
  27029. difference: difference,
  27030. diffuseColor: diffuseColor,
  27031. directPointLight: directPointLight,
  27032. directionToColor: directionToColor,
  27033. dispersion: dispersion,
  27034. distance: distance,
  27035. div: div,
  27036. dodge: dodge,
  27037. dot: dot,
  27038. drawIndex: drawIndex,
  27039. dynamicBufferAttribute: dynamicBufferAttribute,
  27040. element: element,
  27041. emissive: emissive,
  27042. equal: equal,
  27043. equals: equals,
  27044. equirectUV: equirectUV,
  27045. exp: exp,
  27046. exp2: exp2,
  27047. expression: expression,
  27048. faceDirection: faceDirection,
  27049. faceForward: faceForward,
  27050. faceforward: faceforward,
  27051. float: float,
  27052. floor: floor,
  27053. fog: fog,
  27054. fract: fract,
  27055. frameGroup: frameGroup,
  27056. frameId: frameId,
  27057. frontFacing: frontFacing,
  27058. fwidth: fwidth,
  27059. gain: gain,
  27060. gapSize: gapSize,
  27061. getConstNodeType: getConstNodeType,
  27062. getCurrentStack: getCurrentStack,
  27063. getDirection: getDirection,
  27064. getDistanceAttenuation: getDistanceAttenuation,
  27065. getGeometryRoughness: getGeometryRoughness,
  27066. getNormalFromDepth: getNormalFromDepth,
  27067. getParallaxCorrectNormal: getParallaxCorrectNormal,
  27068. getRoughness: getRoughness,
  27069. getScreenPosition: getScreenPosition,
  27070. getShIrradianceAt: getShIrradianceAt,
  27071. getTextureIndex: getTextureIndex,
  27072. getViewPosition: getViewPosition,
  27073. glsl: glsl,
  27074. glslFn: glslFn,
  27075. grayscale: grayscale,
  27076. greaterThan: greaterThan,
  27077. greaterThanEqual: greaterThanEqual,
  27078. hash: hash,
  27079. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  27080. highpModelViewMatrix: highpModelViewMatrix,
  27081. hue: hue,
  27082. instance: instance,
  27083. instanceIndex: instanceIndex,
  27084. instancedArray: instancedArray,
  27085. instancedBufferAttribute: instancedBufferAttribute,
  27086. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  27087. instancedMesh: instancedMesh,
  27088. int: int,
  27089. inverseSqrt: inverseSqrt,
  27090. inversesqrt: inversesqrt,
  27091. invocationLocalIndex: invocationLocalIndex,
  27092. invocationSubgroupIndex: invocationSubgroupIndex,
  27093. ior: ior,
  27094. iridescence: iridescence,
  27095. iridescenceIOR: iridescenceIOR,
  27096. iridescenceThickness: iridescenceThickness,
  27097. ivec2: ivec2,
  27098. ivec3: ivec3,
  27099. ivec4: ivec4,
  27100. js: js,
  27101. label: label,
  27102. length: length,
  27103. lengthSq: lengthSq,
  27104. lessThan: lessThan,
  27105. lessThanEqual: lessThanEqual,
  27106. lightPosition: lightPosition,
  27107. lightProjectionUV: lightProjectionUV,
  27108. lightShadowMatrix: lightShadowMatrix,
  27109. lightTargetDirection: lightTargetDirection,
  27110. lightTargetPosition: lightTargetPosition,
  27111. lightViewPosition: lightViewPosition,
  27112. lightingContext: lightingContext,
  27113. lights: lights,
  27114. linearDepth: linearDepth,
  27115. linearToneMapping: linearToneMapping,
  27116. localId: localId,
  27117. log: log,
  27118. log2: log2,
  27119. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  27120. loop: loop,
  27121. luminance: luminance,
  27122. mat2: mat2,
  27123. mat3: mat3,
  27124. mat4: mat4,
  27125. matcapUV: matcapUV,
  27126. materialAO: materialAO,
  27127. materialAlphaTest: materialAlphaTest,
  27128. materialAnisotropy: materialAnisotropy,
  27129. materialAnisotropyVector: materialAnisotropyVector,
  27130. materialAttenuationColor: materialAttenuationColor,
  27131. materialAttenuationDistance: materialAttenuationDistance,
  27132. materialClearcoat: materialClearcoat,
  27133. materialClearcoatNormal: materialClearcoatNormal,
  27134. materialClearcoatRoughness: materialClearcoatRoughness,
  27135. materialColor: materialColor,
  27136. materialDispersion: materialDispersion,
  27137. materialEmissive: materialEmissive,
  27138. materialIOR: materialIOR,
  27139. materialIridescence: materialIridescence,
  27140. materialIridescenceIOR: materialIridescenceIOR,
  27141. materialIridescenceThickness: materialIridescenceThickness,
  27142. materialLightMap: materialLightMap,
  27143. materialLineDashOffset: materialLineDashOffset,
  27144. materialLineDashSize: materialLineDashSize,
  27145. materialLineGapSize: materialLineGapSize,
  27146. materialLineScale: materialLineScale,
  27147. materialLineWidth: materialLineWidth,
  27148. materialMetalness: materialMetalness,
  27149. materialNormal: materialNormal,
  27150. materialOpacity: materialOpacity,
  27151. materialPointWidth: materialPointWidth,
  27152. materialReference: materialReference,
  27153. materialReflectivity: materialReflectivity,
  27154. materialRefractionRatio: materialRefractionRatio,
  27155. materialRotation: materialRotation,
  27156. materialRoughness: materialRoughness,
  27157. materialSheen: materialSheen,
  27158. materialSheenRoughness: materialSheenRoughness,
  27159. materialShininess: materialShininess,
  27160. materialSpecular: materialSpecular,
  27161. materialSpecularColor: materialSpecularColor,
  27162. materialSpecularIntensity: materialSpecularIntensity,
  27163. materialSpecularStrength: materialSpecularStrength,
  27164. materialThickness: materialThickness,
  27165. materialTransmission: materialTransmission,
  27166. max: max$1,
  27167. maxMipLevel: maxMipLevel,
  27168. mediumpModelViewMatrix: mediumpModelViewMatrix,
  27169. metalness: metalness,
  27170. min: min$1,
  27171. mix: mix,
  27172. mixElement: mixElement,
  27173. mod: mod,
  27174. modInt: modInt,
  27175. modelDirection: modelDirection,
  27176. modelNormalMatrix: modelNormalMatrix,
  27177. modelPosition: modelPosition,
  27178. modelScale: modelScale,
  27179. modelViewMatrix: modelViewMatrix,
  27180. modelViewPosition: modelViewPosition,
  27181. modelViewProjection: modelViewProjection,
  27182. modelWorldMatrix: modelWorldMatrix,
  27183. modelWorldMatrixInverse: modelWorldMatrixInverse,
  27184. morphReference: morphReference,
  27185. mrt: mrt,
  27186. mul: mul,
  27187. mx_aastep: mx_aastep,
  27188. mx_cell_noise_float: mx_cell_noise_float,
  27189. mx_contrast: mx_contrast,
  27190. mx_fractal_noise_float: mx_fractal_noise_float,
  27191. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  27192. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  27193. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  27194. mx_hsvtorgb: mx_hsvtorgb,
  27195. mx_noise_float: mx_noise_float,
  27196. mx_noise_vec3: mx_noise_vec3,
  27197. mx_noise_vec4: mx_noise_vec4,
  27198. mx_ramplr: mx_ramplr,
  27199. mx_ramptb: mx_ramptb,
  27200. mx_rgbtohsv: mx_rgbtohsv,
  27201. mx_safepower: mx_safepower,
  27202. mx_splitlr: mx_splitlr,
  27203. mx_splittb: mx_splittb,
  27204. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  27205. mx_transform_uv: mx_transform_uv,
  27206. mx_worley_noise_float: mx_worley_noise_float,
  27207. mx_worley_noise_vec2: mx_worley_noise_vec2,
  27208. mx_worley_noise_vec3: mx_worley_noise_vec3,
  27209. negate: negate,
  27210. neutralToneMapping: neutralToneMapping,
  27211. nodeArray: nodeArray,
  27212. nodeImmutable: nodeImmutable,
  27213. nodeObject: nodeObject,
  27214. nodeObjects: nodeObjects,
  27215. nodeProxy: nodeProxy,
  27216. normalFlat: normalFlat,
  27217. normalGeometry: normalGeometry,
  27218. normalLocal: normalLocal,
  27219. normalMap: normalMap,
  27220. normalView: normalView,
  27221. normalWorld: normalWorld,
  27222. normalize: normalize,
  27223. not: not,
  27224. notEqual: notEqual,
  27225. numWorkgroups: numWorkgroups,
  27226. objectDirection: objectDirection,
  27227. objectGroup: objectGroup,
  27228. objectPosition: objectPosition,
  27229. objectScale: objectScale,
  27230. objectViewPosition: objectViewPosition,
  27231. objectWorldMatrix: objectWorldMatrix,
  27232. oneMinus: oneMinus,
  27233. or: or,
  27234. orthographicDepthToViewZ: orthographicDepthToViewZ,
  27235. oscSawtooth: oscSawtooth,
  27236. oscSine: oscSine,
  27237. oscSquare: oscSquare,
  27238. oscTriangle: oscTriangle,
  27239. output: output,
  27240. outputStruct: outputStruct,
  27241. overlay: overlay,
  27242. overloadingFn: overloadingFn,
  27243. parabola: parabola,
  27244. parallaxDirection: parallaxDirection,
  27245. parallaxUV: parallaxUV,
  27246. parameter: parameter,
  27247. pass: pass,
  27248. passTexture: passTexture,
  27249. pcurve: pcurve,
  27250. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  27251. pmremTexture: pmremTexture,
  27252. pointUV: pointUV,
  27253. pointWidth: pointWidth,
  27254. positionGeometry: positionGeometry,
  27255. positionLocal: positionLocal,
  27256. positionPrevious: positionPrevious,
  27257. positionView: positionView,
  27258. positionViewDirection: positionViewDirection,
  27259. positionWorld: positionWorld,
  27260. positionWorldDirection: positionWorldDirection,
  27261. posterize: posterize,
  27262. pow: pow,
  27263. pow2: pow2,
  27264. pow3: pow3,
  27265. pow4: pow4,
  27266. property: property,
  27267. radians: radians,
  27268. rand: rand,
  27269. range: range,
  27270. rangeFog: rangeFog,
  27271. rangeFogFactor: rangeFogFactor,
  27272. reciprocal: reciprocal,
  27273. reference: reference,
  27274. referenceBuffer: referenceBuffer,
  27275. reflect: reflect,
  27276. reflectVector: reflectVector,
  27277. reflectView: reflectView,
  27278. reflector: reflector,
  27279. refract: refract,
  27280. refractVector: refractVector,
  27281. refractView: refractView,
  27282. reinhardToneMapping: reinhardToneMapping,
  27283. remainder: remainder,
  27284. remap: remap,
  27285. remapClamp: remapClamp,
  27286. renderGroup: renderGroup,
  27287. renderOutput: renderOutput,
  27288. rendererReference: rendererReference,
  27289. rotate: rotate,
  27290. rotateUV: rotateUV,
  27291. roughness: roughness,
  27292. round: round,
  27293. rtt: rtt,
  27294. sRGBTransferEOTF: sRGBTransferEOTF,
  27295. sRGBTransferOETF: sRGBTransferOETF,
  27296. sampler: sampler,
  27297. saturate: saturate,
  27298. saturation: saturation,
  27299. screen: screen,
  27300. screenCoordinate: screenCoordinate,
  27301. screenSize: screenSize,
  27302. screenUV: screenUV,
  27303. scriptable: scriptable,
  27304. scriptableValue: scriptableValue,
  27305. select: select,
  27306. setCurrentStack: setCurrentStack,
  27307. shaderStages: shaderStages,
  27308. shadow: shadow,
  27309. shadowPositionWorld: shadowPositionWorld,
  27310. sharedUniformGroup: sharedUniformGroup,
  27311. sheen: sheen,
  27312. sheenRoughness: sheenRoughness,
  27313. shiftLeft: shiftLeft,
  27314. shiftRight: shiftRight,
  27315. shininess: shininess,
  27316. sign: sign,
  27317. sin: sin,
  27318. sinc: sinc,
  27319. skinning: skinning,
  27320. skinningReference: skinningReference,
  27321. smoothstep: smoothstep,
  27322. smoothstepElement: smoothstepElement,
  27323. specularColor: specularColor,
  27324. specularF90: specularF90,
  27325. spherizeUV: spherizeUV,
  27326. split: split,
  27327. spritesheetUV: spritesheetUV,
  27328. sqrt: sqrt,
  27329. stack: stack,
  27330. step: step,
  27331. storage: storage,
  27332. storageBarrier: storageBarrier,
  27333. storageObject: storageObject,
  27334. storageTexture: storageTexture,
  27335. string: string,
  27336. sub: sub,
  27337. subgroupIndex: subgroupIndex,
  27338. subgroupSize: subgroupSize,
  27339. tan: tan,
  27340. tangentGeometry: tangentGeometry,
  27341. tangentLocal: tangentLocal,
  27342. tangentView: tangentView,
  27343. tangentWorld: tangentWorld,
  27344. temp: temp,
  27345. texture: texture,
  27346. texture3D: texture3D,
  27347. textureBarrier: textureBarrier,
  27348. textureBicubic: textureBicubic,
  27349. textureCubeUV: textureCubeUV,
  27350. textureLoad: textureLoad,
  27351. textureSize: textureSize,
  27352. textureStore: textureStore,
  27353. thickness: thickness,
  27354. time: time,
  27355. timerDelta: timerDelta,
  27356. timerGlobal: timerGlobal,
  27357. timerLocal: timerLocal,
  27358. toOutputColorSpace: toOutputColorSpace,
  27359. toWorkingColorSpace: toWorkingColorSpace,
  27360. toneMapping: toneMapping,
  27361. toneMappingExposure: toneMappingExposure,
  27362. toonOutlinePass: toonOutlinePass,
  27363. transformDirection: transformDirection,
  27364. transformNormal: transformNormal,
  27365. transformNormalToView: transformNormalToView,
  27366. transformedBentNormalView: transformedBentNormalView,
  27367. transformedBitangentView: transformedBitangentView,
  27368. transformedBitangentWorld: transformedBitangentWorld,
  27369. transformedClearcoatNormalView: transformedClearcoatNormalView,
  27370. transformedNormalView: transformedNormalView,
  27371. transformedNormalWorld: transformedNormalWorld,
  27372. transformedTangentView: transformedTangentView,
  27373. transformedTangentWorld: transformedTangentWorld,
  27374. transmission: transmission,
  27375. transpose: transpose,
  27376. triNoise3D: triNoise3D,
  27377. triplanarTexture: triplanarTexture,
  27378. triplanarTextures: triplanarTextures,
  27379. trunc: trunc,
  27380. tslFn: tslFn,
  27381. uint: uint,
  27382. uniform: uniform,
  27383. uniformArray: uniformArray,
  27384. uniformGroup: uniformGroup,
  27385. uniforms: uniforms,
  27386. userData: userData,
  27387. uv: uv,
  27388. uvec2: uvec2,
  27389. uvec3: uvec3,
  27390. uvec4: uvec4,
  27391. varying: varying,
  27392. varyingProperty: varyingProperty,
  27393. vec2: vec2,
  27394. vec3: vec3,
  27395. vec4: vec4,
  27396. vectorComponents: vectorComponents,
  27397. velocity: velocity,
  27398. vertexColor: vertexColor,
  27399. vertexIndex: vertexIndex,
  27400. vertexStage: vertexStage,
  27401. vibrance: vibrance,
  27402. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  27403. viewZToOrthographicDepth: viewZToOrthographicDepth,
  27404. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  27405. viewport: viewport,
  27406. viewportBottomLeft: viewportBottomLeft,
  27407. viewportCoordinate: viewportCoordinate,
  27408. viewportDepthTexture: viewportDepthTexture,
  27409. viewportLinearDepth: viewportLinearDepth,
  27410. viewportMipTexture: viewportMipTexture,
  27411. viewportResolution: viewportResolution,
  27412. viewportSafeUV: viewportSafeUV,
  27413. viewportSharedTexture: viewportSharedTexture,
  27414. viewportSize: viewportSize,
  27415. viewportTexture: viewportTexture,
  27416. viewportTopLeft: viewportTopLeft,
  27417. viewportUV: viewportUV,
  27418. wgsl: wgsl,
  27419. wgslFn: wgslFn,
  27420. workgroupArray: workgroupArray,
  27421. workgroupBarrier: workgroupBarrier,
  27422. workgroupId: workgroupId,
  27423. workingToColorSpace: workingToColorSpace,
  27424. xor: xor
  27425. });
  27426. const _clearColor$1 = /*@__PURE__*/ new Color4();
  27427. /**
  27428. * This renderer module manages the background.
  27429. *
  27430. * @private
  27431. * @augments DataMap
  27432. */
  27433. class Background extends DataMap {
  27434. /**
  27435. * Constructs a new background management component.
  27436. *
  27437. * @param {Renderer} renderer - The renderer.
  27438. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  27439. */
  27440. constructor( renderer, nodes ) {
  27441. super();
  27442. /**
  27443. * The renderer.
  27444. *
  27445. * @type {Renderer}
  27446. */
  27447. this.renderer = renderer;
  27448. /**
  27449. * Renderer component for managing nodes related logic.
  27450. *
  27451. * @type {Nodes}
  27452. */
  27453. this.nodes = nodes;
  27454. }
  27455. /**
  27456. * Updates the background for the given scene. Depending on how `Scene.background`
  27457. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  27458. * or add a mesh to the render list for rendering the background as a textured plane
  27459. * or skybox.
  27460. *
  27461. * @param {Scene} scene - The scene.
  27462. * @param {RenderList} renderList - The current render list.
  27463. * @param {RenderContext} renderContext - The current render context.
  27464. */
  27465. update( scene, renderList, renderContext ) {
  27466. const renderer = this.renderer;
  27467. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  27468. let forceClear = false;
  27469. if ( background === null ) {
  27470. // no background settings, use clear color configuration from the renderer
  27471. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27472. _clearColor$1.a = renderer._clearColor.a;
  27473. } else if ( background.isColor === true ) {
  27474. // background is an opaque color
  27475. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27476. _clearColor$1.a = 1;
  27477. forceClear = true;
  27478. } else if ( background.isNode === true ) {
  27479. const sceneData = this.get( scene );
  27480. const backgroundNode = background;
  27481. _clearColor$1.copy( renderer._clearColor );
  27482. let backgroundMesh = sceneData.backgroundMesh;
  27483. if ( backgroundMesh === undefined ) {
  27484. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  27485. // @TODO: Add Texture2D support using node context
  27486. getUV: () => backgroundRotation.mul( normalWorld ),
  27487. getTextureLevel: () => backgroundBlurriness
  27488. } );
  27489. let viewProj = modelViewProjection;
  27490. viewProj = viewProj.setZ( viewProj.w );
  27491. const nodeMaterial = new NodeMaterial();
  27492. nodeMaterial.name = 'Background.material';
  27493. nodeMaterial.side = BackSide;
  27494. nodeMaterial.depthTest = false;
  27495. nodeMaterial.depthWrite = false;
  27496. nodeMaterial.fog = false;
  27497. nodeMaterial.lights = false;
  27498. nodeMaterial.vertexNode = viewProj;
  27499. nodeMaterial.colorNode = backgroundMeshNode;
  27500. sceneData.backgroundMeshNode = backgroundMeshNode;
  27501. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  27502. backgroundMesh.frustumCulled = false;
  27503. backgroundMesh.name = 'Background.mesh';
  27504. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  27505. this.matrixWorld.copyPosition( camera.matrixWorld );
  27506. };
  27507. }
  27508. const backgroundCacheKey = backgroundNode.getCacheKey();
  27509. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  27510. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  27511. sceneData.backgroundMeshNode.needsUpdate = true;
  27512. backgroundMesh.material.needsUpdate = true;
  27513. sceneData.backgroundCacheKey = backgroundCacheKey;
  27514. }
  27515. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  27516. } else {
  27517. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  27518. }
  27519. //
  27520. if ( renderer.autoClear === true || forceClear === true ) {
  27521. const clearColorValue = renderContext.clearColorValue;
  27522. clearColorValue.r = _clearColor$1.r;
  27523. clearColorValue.g = _clearColor$1.g;
  27524. clearColorValue.b = _clearColor$1.b;
  27525. clearColorValue.a = _clearColor$1.a;
  27526. // premultiply alpha
  27527. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  27528. clearColorValue.r *= clearColorValue.a;
  27529. clearColorValue.g *= clearColorValue.a;
  27530. clearColorValue.b *= clearColorValue.a;
  27531. }
  27532. //
  27533. renderContext.depthClearValue = renderer._clearDepth;
  27534. renderContext.stencilClearValue = renderer._clearStencil;
  27535. renderContext.clearColor = renderer.autoClearColor === true;
  27536. renderContext.clearDepth = renderer.autoClearDepth === true;
  27537. renderContext.clearStencil = renderer.autoClearStencil === true;
  27538. } else {
  27539. renderContext.clearColor = false;
  27540. renderContext.clearDepth = false;
  27541. renderContext.clearStencil = false;
  27542. }
  27543. }
  27544. }
  27545. let _id$6 = 0;
  27546. /**
  27547. * A bind group represents a collection of bindings and thus a collection
  27548. * or resources. Bind groups are assigned to pipelines to provide them
  27549. * with the required resources (like uniform buffers or textures).
  27550. *
  27551. * @private
  27552. */
  27553. class BindGroup {
  27554. /**
  27555. * Constructs a new bind group.
  27556. *
  27557. * @param {String} name - The bind group's name.
  27558. * @param {Array<Binding>} bindings - An array of bindings.
  27559. * @param {Number} index - The group index.
  27560. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  27561. */
  27562. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  27563. /**
  27564. * The bind group's name.
  27565. *
  27566. * @type {String}
  27567. */
  27568. this.name = name;
  27569. /**
  27570. * An array of bindings.
  27571. *
  27572. * @type {Array<Binding>}
  27573. */
  27574. this.bindings = bindings;
  27575. /**
  27576. * The group index.
  27577. *
  27578. * @type {Number}
  27579. */
  27580. this.index = index;
  27581. /**
  27582. * An array of reference bindings.
  27583. *
  27584. * @type {Array<Binding>}
  27585. */
  27586. this.bindingsReference = bindingsReference;
  27587. /**
  27588. * The group's ID.
  27589. *
  27590. * @type {Number}
  27591. */
  27592. this.id = _id$6 ++;
  27593. }
  27594. }
  27595. /**
  27596. * This module represents the state of a node builder after it was
  27597. * used to build the nodes for a render object. The state holds the
  27598. * results of the build for further processing in the renderer.
  27599. *
  27600. * Render objects with identical cache keys share the same node builder state.
  27601. *
  27602. * @private
  27603. */
  27604. class NodeBuilderState {
  27605. /**
  27606. * Constructs a new node builder state.
  27607. *
  27608. * @param {String?} vertexShader - The native vertex shader code.
  27609. * @param {String?} fragmentShader - The native fragment shader code.
  27610. * @param {String?} computeShader - The native compute shader code.
  27611. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  27612. * @param {Array<BindGroup>} bindings - An array of bind groups.
  27613. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  27614. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  27615. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  27616. * @param {NodeMaterialObserver} monitor - A node material observer.
  27617. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  27618. */
  27619. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  27620. /**
  27621. * The native vertex shader code.
  27622. *
  27623. * @type {String}
  27624. */
  27625. this.vertexShader = vertexShader;
  27626. /**
  27627. * The native fragment shader code.
  27628. *
  27629. * @type {String}
  27630. */
  27631. this.fragmentShader = fragmentShader;
  27632. /**
  27633. * The native compute shader code.
  27634. *
  27635. * @type {String}
  27636. */
  27637. this.computeShader = computeShader;
  27638. /**
  27639. * An array with transform attribute objects.
  27640. * Only relevant when using compute shaders with WebGL 2.
  27641. *
  27642. * @type {Array<Object>}
  27643. */
  27644. this.transforms = transforms;
  27645. /**
  27646. * An array of node attributes representing
  27647. * the attributes of the shaders.
  27648. *
  27649. * @type {Array<NodeAttribute>}
  27650. */
  27651. this.nodeAttributes = nodeAttributes;
  27652. /**
  27653. * An array of bind groups representing the uniform or storage
  27654. * buffers, texture or samplers of the shader.
  27655. *
  27656. * @type {Array<BindGroup>}
  27657. */
  27658. this.bindings = bindings;
  27659. /**
  27660. * An array of nodes that implement their `update()` method.
  27661. *
  27662. * @type {Array<Node>}
  27663. */
  27664. this.updateNodes = updateNodes;
  27665. /**
  27666. * An array of nodes that implement their `updateBefore()` method.
  27667. *
  27668. * @type {Array<Node>}
  27669. */
  27670. this.updateBeforeNodes = updateBeforeNodes;
  27671. /**
  27672. * An array of nodes that implement their `updateAfter()` method.
  27673. *
  27674. * @type {Array<Node>}
  27675. */
  27676. this.updateAfterNodes = updateAfterNodes;
  27677. /**
  27678. * A node material observer.
  27679. *
  27680. * @type {NodeMaterialObserver}
  27681. */
  27682. this.monitor = monitor;
  27683. /**
  27684. * How often this state is used by render objects.
  27685. *
  27686. * @type {Number}
  27687. */
  27688. this.usedTimes = 0;
  27689. }
  27690. /**
  27691. * This method is used to create a array of bind groups based
  27692. * on the existing bind groups of this state. Shared groups are
  27693. * not cloned.
  27694. *
  27695. * @return {Array<BindGroup>} A array of bind groups.
  27696. */
  27697. createBindings() {
  27698. const bindings = [];
  27699. for ( const instanceGroup of this.bindings ) {
  27700. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // TODO: Is it safe to always check the first binding in the group?
  27701. if ( shared !== true ) {
  27702. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  27703. bindings.push( bindingsGroup );
  27704. for ( const instanceBinding of instanceGroup.bindings ) {
  27705. bindingsGroup.bindings.push( instanceBinding.clone() );
  27706. }
  27707. } else {
  27708. bindings.push( instanceGroup );
  27709. }
  27710. }
  27711. return bindings;
  27712. }
  27713. }
  27714. /**
  27715. * {@link NodeBuilder} is going to create instances of this class during the build process
  27716. * of nodes. They represent the final shader attributes that are going to be generated
  27717. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  27718. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  27719. */
  27720. class NodeAttribute {
  27721. /**
  27722. * Constructs a new node attribute.
  27723. *
  27724. * @param {String} name - The name of the attribute.
  27725. * @param {String} type - The type of the attribute.
  27726. * @param {Node?} node - An optional reference to the node.
  27727. */
  27728. constructor( name, type, node = null ) {
  27729. /**
  27730. * This flag can be used for type testing.
  27731. *
  27732. * @type {Boolean}
  27733. * @readonly
  27734. * @default true
  27735. */
  27736. this.isNodeAttribute = true;
  27737. /**
  27738. * The name of the attribute.
  27739. *
  27740. * @type {String}
  27741. */
  27742. this.name = name;
  27743. /**
  27744. * The type of the attribute.
  27745. *
  27746. * @type {String}
  27747. */
  27748. this.type = type;
  27749. /**
  27750. * An optional reference to the node.
  27751. *
  27752. * @type {Node?}
  27753. * @default null
  27754. */
  27755. this.node = node;
  27756. }
  27757. }
  27758. /**
  27759. * {@link NodeBuilder} is going to create instances of this class during the build process
  27760. * of nodes. They represent the final shader uniforms that are going to be generated
  27761. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  27762. * for this purpose.
  27763. */
  27764. class NodeUniform {
  27765. /**
  27766. * Constructs a new node uniform.
  27767. *
  27768. * @param {String} name - The name of the uniform.
  27769. * @param {String} type - The type of the uniform.
  27770. * @param {UniformNode} node - An reference to the node.
  27771. */
  27772. constructor( name, type, node ) {
  27773. /**
  27774. * This flag can be used for type testing.
  27775. *
  27776. * @type {Boolean}
  27777. * @readonly
  27778. * @default true
  27779. */
  27780. this.isNodeUniform = true;
  27781. /**
  27782. * The name of the uniform.
  27783. *
  27784. * @type {String}
  27785. */
  27786. this.name = name;
  27787. /**
  27788. * The type of the uniform.
  27789. *
  27790. * @type {String}
  27791. */
  27792. this.type = type;
  27793. /**
  27794. * An reference to the node.
  27795. *
  27796. * @type {UniformNode}
  27797. */
  27798. this.node = node.getSelf();
  27799. }
  27800. /**
  27801. * The value of the uniform node.
  27802. *
  27803. * @type {Any}
  27804. */
  27805. get value() {
  27806. return this.node.value;
  27807. }
  27808. set value( val ) {
  27809. this.node.value = val;
  27810. }
  27811. /**
  27812. * The id of the uniform node.
  27813. *
  27814. * @type {Number}
  27815. */
  27816. get id() {
  27817. return this.node.id;
  27818. }
  27819. /**
  27820. * The uniform node's group.
  27821. *
  27822. * @type {UniformGroupNode}
  27823. */
  27824. get groupNode() {
  27825. return this.node.groupNode;
  27826. }
  27827. }
  27828. /**
  27829. * {@link NodeBuilder} is going to create instances of this class during the build process
  27830. * of nodes. They represent the final shader variables that are going to be generated
  27831. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  27832. * this purpose.
  27833. */
  27834. class NodeVar {
  27835. /**
  27836. * Constructs a new node variable.
  27837. *
  27838. * @param {String} name - The name of the variable.
  27839. * @param {String} type - The type of the variable.
  27840. */
  27841. constructor( name, type ) {
  27842. /**
  27843. * This flag can be used for type testing.
  27844. *
  27845. * @type {Boolean}
  27846. * @readonly
  27847. * @default true
  27848. */
  27849. this.isNodeVar = true;
  27850. /**
  27851. * The name of the variable.
  27852. *
  27853. * @type {String}
  27854. */
  27855. this.name = name;
  27856. /**
  27857. * The type of the variable.
  27858. *
  27859. * @type {String}
  27860. */
  27861. this.type = type;
  27862. }
  27863. }
  27864. /**
  27865. * {@link NodeBuilder} is going to create instances of this class during the build process
  27866. * of nodes. They represent the final shader varyings that are going to be generated
  27867. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  27868. * this purpose.
  27869. *
  27870. * @augments NodeVar
  27871. */
  27872. class NodeVarying extends NodeVar {
  27873. /**
  27874. * Constructs a new node varying.
  27875. *
  27876. * @param {String} name - The name of the varying.
  27877. * @param {String} type - The type of the varying.
  27878. */
  27879. constructor( name, type ) {
  27880. super( name, type );
  27881. /**
  27882. * Whether this varying requires interpolation or not. This property can be used
  27883. * to check if the varying can be optimized for a variable.
  27884. *
  27885. * @type {Boolean}
  27886. * @default false
  27887. */
  27888. this.needsInterpolation = false;
  27889. /**
  27890. * This flag can be used for type testing.
  27891. *
  27892. * @type {Boolean}
  27893. * @readonly
  27894. * @default true
  27895. */
  27896. this.isNodeVarying = true;
  27897. }
  27898. }
  27899. /**
  27900. * {@link NodeBuilder} is going to create instances of this class during the build process
  27901. * of nodes. They represent user-defined, native shader code portions that are going to be
  27902. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  27903. * for this purpose.
  27904. */
  27905. class NodeCode {
  27906. /**
  27907. * Constructs a new code node.
  27908. *
  27909. * @param {String} name - The name of the code.
  27910. * @param {String} type - The node type.
  27911. * @param {String} [code=''] - The native shader code.
  27912. */
  27913. constructor( name, type, code = '' ) {
  27914. /**
  27915. * The name of the code.
  27916. *
  27917. * @type {String}
  27918. */
  27919. this.name = name;
  27920. /**
  27921. * The node type.
  27922. *
  27923. * @type {String}
  27924. */
  27925. this.type = type;
  27926. /**
  27927. * The native shader code.
  27928. *
  27929. * @type {String}
  27930. * @default ''
  27931. */
  27932. this.code = code;
  27933. Object.defineProperty( this, 'isNodeCode', { value: true } );
  27934. }
  27935. }
  27936. let _id$5 = 0;
  27937. /**
  27938. * This utility class is used in {@link NodeBuilder} as an internal
  27939. * cache data structure for node data.
  27940. */
  27941. class NodeCache {
  27942. /**
  27943. * Constructs a new node cache.
  27944. *
  27945. * @param {NodeCache?} parent - A reference to a parent cache.
  27946. */
  27947. constructor( parent = null ) {
  27948. /**
  27949. * The id of the cache.
  27950. *
  27951. * @type {Number}
  27952. * @readonly
  27953. */
  27954. this.id = _id$5 ++;
  27955. /**
  27956. * A weak map for managing node data.
  27957. *
  27958. * @type {WeakMap<Node, Object>}
  27959. */
  27960. this.nodesData = new WeakMap();
  27961. /**
  27962. * Reference to a parent node cache.
  27963. *
  27964. * @type {NodeCache?}
  27965. * @default null
  27966. */
  27967. this.parent = parent;
  27968. }
  27969. /**
  27970. * Returns the data for the given node.
  27971. *
  27972. * @param {Node} node - The node.
  27973. * @return {Object?} The data for the node.
  27974. */
  27975. getData( node ) {
  27976. let data = this.nodesData.get( node );
  27977. if ( data === undefined && this.parent !== null ) {
  27978. data = this.parent.getData( node );
  27979. }
  27980. return data;
  27981. }
  27982. /**
  27983. * Sets the data for a given node.
  27984. *
  27985. * @param {Node} node - The node.
  27986. * @param {Object} data - The data that should be cached.
  27987. */
  27988. setData( node, data ) {
  27989. this.nodesData.set( node, data );
  27990. }
  27991. }
  27992. /**
  27993. * {@link NodeBuilder} is going to create instances of this class during the build process
  27994. * of nodes. They represent the final shader struct data that are going to be generated
  27995. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  27996. * for this purpose.
  27997. */
  27998. class StructTypeNode extends Node {
  27999. static get type() {
  28000. return 'StructTypeNode';
  28001. }
  28002. /**
  28003. * Constructs a new struct type node.
  28004. *
  28005. * @param {String} name - The name of the struct.
  28006. * @param {Array<String>} types - An array of types.
  28007. */
  28008. constructor( name, types ) {
  28009. super();
  28010. /**
  28011. * The name of the struct.
  28012. *
  28013. * @type {String}
  28014. */
  28015. this.name = name;
  28016. /**
  28017. * An array of types.
  28018. *
  28019. * @type {Array<String>}
  28020. */
  28021. this.types = types;
  28022. /**
  28023. * This flag can be used for type testing.
  28024. *
  28025. * @type {Boolean}
  28026. * @readonly
  28027. * @default true
  28028. */
  28029. this.isStructTypeNode = true;
  28030. }
  28031. /**
  28032. * Returns the member types.
  28033. *
  28034. * @return {Array<String>} The types.
  28035. */
  28036. getMemberTypes() {
  28037. return this.types;
  28038. }
  28039. }
  28040. /**
  28041. * Abstract base class for uniforms.
  28042. *
  28043. * @abstract
  28044. * @private
  28045. */
  28046. class Uniform {
  28047. /**
  28048. * Constructs a new uniform.
  28049. *
  28050. * @param {String} name - The uniform's name.
  28051. * @param {Any} value - The uniform's value.
  28052. */
  28053. constructor( name, value ) {
  28054. /**
  28055. * The uniform's name.
  28056. *
  28057. * @type {String}
  28058. */
  28059. this.name = name;
  28060. /**
  28061. * The uniform's value.
  28062. *
  28063. * @type {Any}
  28064. */
  28065. this.value = value;
  28066. /**
  28067. * Used to build the uniform buffer according to the STD140 layout.
  28068. * Derived uniforms will set this property to a data type specific
  28069. * value.
  28070. *
  28071. * @type {Number}
  28072. */
  28073. this.boundary = 0;
  28074. /**
  28075. * The item size. Derived uniforms will set this property to a data
  28076. * type specific value.
  28077. *
  28078. * @type {Number}
  28079. */
  28080. this.itemSize = 0;
  28081. /**
  28082. * This property is set by {@link UniformsGroup} and marks
  28083. * the start position in the uniform buffer.
  28084. *
  28085. * @type {Number}
  28086. */
  28087. this.offset = 0;
  28088. }
  28089. /**
  28090. * Sets the uniform's value.
  28091. *
  28092. * @param {Any} value - The value to set.
  28093. */
  28094. setValue( value ) {
  28095. this.value = value;
  28096. }
  28097. /**
  28098. * Returns the uniform's value.
  28099. *
  28100. * @return {Any} The value.
  28101. */
  28102. getValue() {
  28103. return this.value;
  28104. }
  28105. }
  28106. /**
  28107. * Represents a Number uniform.
  28108. *
  28109. * @private
  28110. * @augments Uniform
  28111. */
  28112. class NumberUniform extends Uniform {
  28113. /**
  28114. * Constructs a new Number uniform.
  28115. *
  28116. * @param {String} name - The uniform's name.
  28117. * @param {Number} value - The uniform's value.
  28118. */
  28119. constructor( name, value = 0 ) {
  28120. super( name, value );
  28121. /**
  28122. * This flag can be used for type testing.
  28123. *
  28124. * @type {Boolean}
  28125. * @readonly
  28126. * @default true
  28127. */
  28128. this.isNumberUniform = true;
  28129. this.boundary = 4;
  28130. this.itemSize = 1;
  28131. }
  28132. }
  28133. /**
  28134. * Represents a Vector2 uniform.
  28135. *
  28136. * @private
  28137. * @augments Uniform
  28138. */
  28139. class Vector2Uniform extends Uniform {
  28140. /**
  28141. * Constructs a new Number uniform.
  28142. *
  28143. * @param {String} name - The uniform's name.
  28144. * @param {Vector2} value - The uniform's value.
  28145. */
  28146. constructor( name, value = new Vector2() ) {
  28147. super( name, value );
  28148. /**
  28149. * This flag can be used for type testing.
  28150. *
  28151. * @type {Boolean}
  28152. * @readonly
  28153. * @default true
  28154. */
  28155. this.isVector2Uniform = true;
  28156. this.boundary = 8;
  28157. this.itemSize = 2;
  28158. }
  28159. }
  28160. /**
  28161. * Represents a Vector3 uniform.
  28162. *
  28163. * @private
  28164. * @augments Uniform
  28165. */
  28166. class Vector3Uniform extends Uniform {
  28167. /**
  28168. * Constructs a new Number uniform.
  28169. *
  28170. * @param {String} name - The uniform's name.
  28171. * @param {Vector3} value - The uniform's value.
  28172. */
  28173. constructor( name, value = new Vector3() ) {
  28174. super( name, value );
  28175. /**
  28176. * This flag can be used for type testing.
  28177. *
  28178. * @type {Boolean}
  28179. * @readonly
  28180. * @default true
  28181. */
  28182. this.isVector3Uniform = true;
  28183. this.boundary = 16;
  28184. this.itemSize = 3;
  28185. }
  28186. }
  28187. /**
  28188. * Represents a Vector4 uniform.
  28189. *
  28190. * @private
  28191. * @augments Uniform
  28192. */
  28193. class Vector4Uniform extends Uniform {
  28194. /**
  28195. * Constructs a new Number uniform.
  28196. *
  28197. * @param {String} name - The uniform's name.
  28198. * @param {Vector4} value - The uniform's value.
  28199. */
  28200. constructor( name, value = new Vector4() ) {
  28201. super( name, value );
  28202. /**
  28203. * This flag can be used for type testing.
  28204. *
  28205. * @type {Boolean}
  28206. * @readonly
  28207. * @default true
  28208. */
  28209. this.isVector4Uniform = true;
  28210. this.boundary = 16;
  28211. this.itemSize = 4;
  28212. }
  28213. }
  28214. /**
  28215. * Represents a Color uniform.
  28216. *
  28217. * @private
  28218. * @augments Uniform
  28219. */
  28220. class ColorUniform extends Uniform {
  28221. /**
  28222. * Constructs a new Number uniform.
  28223. *
  28224. * @param {String} name - The uniform's name.
  28225. * @param {Color} value - The uniform's value.
  28226. */
  28227. constructor( name, value = new Color() ) {
  28228. super( name, value );
  28229. /**
  28230. * This flag can be used for type testing.
  28231. *
  28232. * @type {Boolean}
  28233. * @readonly
  28234. * @default true
  28235. */
  28236. this.isColorUniform = true;
  28237. this.boundary = 16;
  28238. this.itemSize = 3;
  28239. }
  28240. }
  28241. /**
  28242. * Represents a Matrix3 uniform.
  28243. *
  28244. * @private
  28245. * @augments Uniform
  28246. */
  28247. class Matrix3Uniform extends Uniform {
  28248. /**
  28249. * Constructs a new Number uniform.
  28250. *
  28251. * @param {String} name - The uniform's name.
  28252. * @param {Matrix3} value - The uniform's value.
  28253. */
  28254. constructor( name, value = new Matrix3() ) {
  28255. super( name, value );
  28256. /**
  28257. * This flag can be used for type testing.
  28258. *
  28259. * @type {Boolean}
  28260. * @readonly
  28261. * @default true
  28262. */
  28263. this.isMatrix3Uniform = true;
  28264. this.boundary = 48;
  28265. this.itemSize = 12;
  28266. }
  28267. }
  28268. /**
  28269. * Represents a Matrix4 uniform.
  28270. *
  28271. * @private
  28272. * @augments Uniform
  28273. */
  28274. class Matrix4Uniform extends Uniform {
  28275. /**
  28276. * Constructs a new Number uniform.
  28277. *
  28278. * @param {String} name - The uniform's name.
  28279. * @param {Matrix4} value - The uniform's value.
  28280. */
  28281. constructor( name, value = new Matrix4() ) {
  28282. super( name, value );
  28283. /**
  28284. * This flag can be used for type testing.
  28285. *
  28286. * @type {Boolean}
  28287. * @readonly
  28288. * @default true
  28289. */
  28290. this.isMatrix4Uniform = true;
  28291. this.boundary = 64;
  28292. this.itemSize = 16;
  28293. }
  28294. }
  28295. /**
  28296. * A special form of Number uniform binding type.
  28297. * It's value is managed by a node object.
  28298. *
  28299. * @private
  28300. * @augments NumberUniform
  28301. */
  28302. class NumberNodeUniform extends NumberUniform {
  28303. /**
  28304. * Constructs a new node-based Number uniform.
  28305. *
  28306. * @param {NodeUniform} nodeUniform - The node uniform.
  28307. */
  28308. constructor( nodeUniform ) {
  28309. super( nodeUniform.name, nodeUniform.value );
  28310. /**
  28311. * The node uniform.
  28312. *
  28313. * @type {NodeUniform}
  28314. */
  28315. this.nodeUniform = nodeUniform;
  28316. }
  28317. /**
  28318. * Overwritten to return the value of the node uniform.
  28319. *
  28320. * @return {Number} The value.
  28321. */
  28322. getValue() {
  28323. return this.nodeUniform.value;
  28324. }
  28325. /**
  28326. * Returns the node uniform data type.
  28327. *
  28328. * @return {String} The data type.
  28329. */
  28330. getType() {
  28331. return this.nodeUniform.type;
  28332. }
  28333. }
  28334. /**
  28335. * A special form of Vector2 uniform binding type.
  28336. * It's value is managed by a node object.
  28337. *
  28338. * @private
  28339. * @augments Vector2Uniform
  28340. */
  28341. class Vector2NodeUniform extends Vector2Uniform {
  28342. /**
  28343. * Constructs a new node-based Vector2 uniform.
  28344. *
  28345. * @param {NodeUniform} nodeUniform - The node uniform.
  28346. */
  28347. constructor( nodeUniform ) {
  28348. super( nodeUniform.name, nodeUniform.value );
  28349. /**
  28350. * The node uniform.
  28351. *
  28352. * @type {NodeUniform}
  28353. */
  28354. this.nodeUniform = nodeUniform;
  28355. }
  28356. /**
  28357. * Overwritten to return the value of the node uniform.
  28358. *
  28359. * @return {Vector2} The value.
  28360. */
  28361. getValue() {
  28362. return this.nodeUniform.value;
  28363. }
  28364. /**
  28365. * Returns the node uniform data type.
  28366. *
  28367. * @return {String} The data type.
  28368. */
  28369. getType() {
  28370. return this.nodeUniform.type;
  28371. }
  28372. }
  28373. /**
  28374. * A special form of Vector3 uniform binding type.
  28375. * It's value is managed by a node object.
  28376. *
  28377. * @private
  28378. * @augments Vector3Uniform
  28379. */
  28380. class Vector3NodeUniform extends Vector3Uniform {
  28381. /**
  28382. * Constructs a new node-based Vector3 uniform.
  28383. *
  28384. * @param {NodeUniform} nodeUniform - The node uniform.
  28385. */
  28386. constructor( nodeUniform ) {
  28387. super( nodeUniform.name, nodeUniform.value );
  28388. /**
  28389. * The node uniform.
  28390. *
  28391. * @type {NodeUniform}
  28392. */
  28393. this.nodeUniform = nodeUniform;
  28394. }
  28395. /**
  28396. * Overwritten to return the value of the node uniform.
  28397. *
  28398. * @return {Vector3} The value.
  28399. */
  28400. getValue() {
  28401. return this.nodeUniform.value;
  28402. }
  28403. /**
  28404. * Returns the node uniform data type.
  28405. *
  28406. * @return {String} The data type.
  28407. */
  28408. getType() {
  28409. return this.nodeUniform.type;
  28410. }
  28411. }
  28412. /**
  28413. * A special form of Vector4 uniform binding type.
  28414. * It's value is managed by a node object.
  28415. *
  28416. * @private
  28417. * @augments Vector4Uniform
  28418. */
  28419. class Vector4NodeUniform extends Vector4Uniform {
  28420. /**
  28421. * Constructs a new node-based Vector4 uniform.
  28422. *
  28423. * @param {NodeUniform} nodeUniform - The node uniform.
  28424. */
  28425. constructor( nodeUniform ) {
  28426. super( nodeUniform.name, nodeUniform.value );
  28427. /**
  28428. * The node uniform.
  28429. *
  28430. * @type {NodeUniform}
  28431. */
  28432. this.nodeUniform = nodeUniform;
  28433. }
  28434. /**
  28435. * Overwritten to return the value of the node uniform.
  28436. *
  28437. * @return {Vector4} The value.
  28438. */
  28439. getValue() {
  28440. return this.nodeUniform.value;
  28441. }
  28442. /**
  28443. * Returns the node uniform data type.
  28444. *
  28445. * @return {String} The data type.
  28446. */
  28447. getType() {
  28448. return this.nodeUniform.type;
  28449. }
  28450. }
  28451. /**
  28452. * A special form of Color uniform binding type.
  28453. * It's value is managed by a node object.
  28454. *
  28455. * @private
  28456. * @augments ColorUniform
  28457. */
  28458. class ColorNodeUniform extends ColorUniform {
  28459. /**
  28460. * Constructs a new node-based Color uniform.
  28461. *
  28462. * @param {NodeUniform} nodeUniform - The node uniform.
  28463. */
  28464. constructor( nodeUniform ) {
  28465. super( nodeUniform.name, nodeUniform.value );
  28466. /**
  28467. * The node uniform.
  28468. *
  28469. * @type {NodeUniform}
  28470. */
  28471. this.nodeUniform = nodeUniform;
  28472. }
  28473. /**
  28474. * Overwritten to return the value of the node uniform.
  28475. *
  28476. * @return {Color} The value.
  28477. */
  28478. getValue() {
  28479. return this.nodeUniform.value;
  28480. }
  28481. /**
  28482. * Returns the node uniform data type.
  28483. *
  28484. * @return {String} The data type.
  28485. */
  28486. getType() {
  28487. return this.nodeUniform.type;
  28488. }
  28489. }
  28490. /**
  28491. * A special form of Matrix3 uniform binding type.
  28492. * It's value is managed by a node object.
  28493. *
  28494. * @private
  28495. * @augments Matrix3Uniform
  28496. */
  28497. class Matrix3NodeUniform extends Matrix3Uniform {
  28498. /**
  28499. * Constructs a new node-based Matrix3 uniform.
  28500. *
  28501. * @param {NodeUniform} nodeUniform - The node uniform.
  28502. */
  28503. constructor( nodeUniform ) {
  28504. super( nodeUniform.name, nodeUniform.value );
  28505. /**
  28506. * The node uniform.
  28507. *
  28508. * @type {NodeUniform}
  28509. */
  28510. this.nodeUniform = nodeUniform;
  28511. }
  28512. /**
  28513. * Overwritten to return the value of the node uniform.
  28514. *
  28515. * @return {Matrix3} The value.
  28516. */
  28517. getValue() {
  28518. return this.nodeUniform.value;
  28519. }
  28520. /**
  28521. * Returns the node uniform data type.
  28522. *
  28523. * @return {String} The data type.
  28524. */
  28525. getType() {
  28526. return this.nodeUniform.type;
  28527. }
  28528. }
  28529. /**
  28530. * A special form of Matrix4 uniform binding type.
  28531. * It's value is managed by a node object.
  28532. *
  28533. * @private
  28534. * @augments Matrix4Uniform
  28535. */
  28536. class Matrix4NodeUniform extends Matrix4Uniform {
  28537. /**
  28538. * Constructs a new node-based Matrix4 uniform.
  28539. *
  28540. * @param {NodeUniform} nodeUniform - The node uniform.
  28541. */
  28542. constructor( nodeUniform ) {
  28543. super( nodeUniform.name, nodeUniform.value );
  28544. /**
  28545. * The node uniform.
  28546. *
  28547. * @type {NodeUniform}
  28548. */
  28549. this.nodeUniform = nodeUniform;
  28550. }
  28551. /**
  28552. * Overwritten to return the value of the node uniform.
  28553. *
  28554. * @return {Matrix4} The value.
  28555. */
  28556. getValue() {
  28557. return this.nodeUniform.value;
  28558. }
  28559. /**
  28560. * Returns the node uniform data type.
  28561. *
  28562. * @return {String} The data type.
  28563. */
  28564. getType() {
  28565. return this.nodeUniform.type;
  28566. }
  28567. }
  28568. const LOD_MIN = 4;
  28569. // The standard deviations (radians) associated with the extra mips. These are
  28570. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28571. // geometric shadowing function. These sigma values squared must match the
  28572. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28573. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  28574. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28575. // samples and exit early, but not recompile the shader.
  28576. const MAX_SAMPLES = 20;
  28577. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  28578. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  28579. const _clearColor = /*@__PURE__*/ new Color();
  28580. let _oldTarget = null;
  28581. let _oldActiveCubeFace = 0;
  28582. let _oldActiveMipmapLevel = 0;
  28583. // Golden Ratio
  28584. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  28585. const INV_PHI = 1 / PHI;
  28586. // Vertices of a dodecahedron (except the opposites, which represent the
  28587. // same axis), used as axis directions evenly spread on a sphere.
  28588. const _axisDirections = [
  28589. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  28590. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  28591. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  28592. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  28593. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  28594. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  28595. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  28596. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  28597. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  28598. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  28599. ];
  28600. //
  28601. // WebGPU Face indices
  28602. const _faceLib = [
  28603. 3, 1, 5,
  28604. 0, 4, 2
  28605. ];
  28606. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  28607. const outputDirection = vec3( direction.x, direction.y, direction.z );
  28608. /**
  28609. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28610. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28611. * blur to be quickly accessed based on material roughness. It is packed into a
  28612. * special CubeUV format that allows us to perform custom interpolation so that
  28613. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28614. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28615. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28616. * higher roughness levels. In this way we maintain resolution to smoothly
  28617. * interpolate diffuse lighting while limiting sampling computation.
  28618. *
  28619. * Paper: Fast, Accurate Image-Based Lighting
  28620. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  28621. */
  28622. class PMREMGenerator {
  28623. constructor( renderer ) {
  28624. this._renderer = renderer;
  28625. this._pingPongRenderTarget = null;
  28626. this._lodMax = 0;
  28627. this._cubeSize = 0;
  28628. this._lodPlanes = [];
  28629. this._sizeLods = [];
  28630. this._sigmas = [];
  28631. this._lodMeshes = [];
  28632. this._blurMaterial = null;
  28633. this._cubemapMaterial = null;
  28634. this._equirectMaterial = null;
  28635. this._backgroundBox = null;
  28636. }
  28637. get _hasInitialized() {
  28638. return this._renderer.hasInitialized();
  28639. }
  28640. /**
  28641. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28642. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28643. * in radians to be applied to the scene before PMREM generation. Optional near
  28644. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28645. * is placed at the origin).
  28646. *
  28647. * @param {Scene} scene - The scene to be captured.
  28648. * @param {Number} [sigma=0] - The blur radius in radians.
  28649. * @param {Number} [near=0.1] - The near plane distance.
  28650. * @param {Number} [far=100] - The far plane distance.
  28651. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28652. * @return {RenderTarget} The resulting PMREM.
  28653. */
  28654. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  28655. this._setSize( 256 );
  28656. if ( this._hasInitialized === false ) {
  28657. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  28658. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28659. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  28660. return cubeUVRenderTarget;
  28661. }
  28662. _oldTarget = this._renderer.getRenderTarget();
  28663. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  28664. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  28665. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28666. cubeUVRenderTarget.depthBuffer = true;
  28667. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  28668. if ( sigma > 0 ) {
  28669. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  28670. }
  28671. this._applyPMREM( cubeUVRenderTarget );
  28672. this._cleanup( cubeUVRenderTarget );
  28673. return cubeUVRenderTarget;
  28674. }
  28675. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  28676. if ( this._hasInitialized === false ) await this._renderer.init();
  28677. return this.fromScene( scene, sigma, near, far, renderTarget );
  28678. }
  28679. /**
  28680. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28681. * or HDR. The ideal input image size is 1k (1024 x 512),
  28682. * as this matches best with the 256 x 256 cubemap output.
  28683. *
  28684. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  28685. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28686. * @return {RenderTarget} The resulting PMREM.
  28687. */
  28688. fromEquirectangular( equirectangular, renderTarget = null ) {
  28689. if ( this._hasInitialized === false ) {
  28690. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  28691. this._setSizeFromTexture( equirectangular );
  28692. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28693. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  28694. return cubeUVRenderTarget;
  28695. }
  28696. return this._fromTexture( equirectangular, renderTarget );
  28697. }
  28698. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  28699. if ( this._hasInitialized === false ) await this._renderer.init();
  28700. return this._fromTexture( equirectangular, renderTarget );
  28701. }
  28702. /**
  28703. * Generates a PMREM from an cubemap texture, which can be either LDR
  28704. * or HDR. The ideal input cube size is 256 x 256,
  28705. * as this matches best with the 256 x 256 cubemap output.
  28706. *
  28707. * @param {Texture} cubemap - The cubemap texture to be converted.
  28708. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  28709. * @return {RenderTarget} The resulting PMREM.
  28710. */
  28711. fromCubemap( cubemap, renderTarget = null ) {
  28712. if ( this._hasInitialized === false ) {
  28713. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  28714. this._setSizeFromTexture( cubemap );
  28715. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28716. this.fromCubemapAsync( cubemap, renderTarget );
  28717. return cubeUVRenderTarget;
  28718. }
  28719. return this._fromTexture( cubemap, renderTarget );
  28720. }
  28721. async fromCubemapAsync( cubemap, renderTarget = null ) {
  28722. if ( this._hasInitialized === false ) await this._renderer.init();
  28723. return this._fromTexture( cubemap, renderTarget );
  28724. }
  28725. /**
  28726. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  28727. * your texture's network fetch for increased concurrency.
  28728. */
  28729. async compileCubemapShader() {
  28730. if ( this._cubemapMaterial === null ) {
  28731. this._cubemapMaterial = _getCubemapMaterial();
  28732. await this._compileMaterial( this._cubemapMaterial );
  28733. }
  28734. }
  28735. /**
  28736. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  28737. * your texture's network fetch for increased concurrency.
  28738. */
  28739. async compileEquirectangularShader() {
  28740. if ( this._equirectMaterial === null ) {
  28741. this._equirectMaterial = _getEquirectMaterial();
  28742. await this._compileMaterial( this._equirectMaterial );
  28743. }
  28744. }
  28745. /**
  28746. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  28747. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  28748. * one of them will cause any others to also become unusable.
  28749. */
  28750. dispose() {
  28751. this._dispose();
  28752. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  28753. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  28754. if ( this._backgroundBox !== null ) {
  28755. this._backgroundBox.geometry.dispose();
  28756. this._backgroundBox.material.dispose();
  28757. }
  28758. }
  28759. // private interface
  28760. _setSizeFromTexture( texture ) {
  28761. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  28762. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  28763. } else { // Equirectangular
  28764. this._setSize( texture.image.width / 4 );
  28765. }
  28766. }
  28767. _setSize( cubeSize ) {
  28768. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  28769. this._cubeSize = Math.pow( 2, this._lodMax );
  28770. }
  28771. _dispose() {
  28772. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  28773. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  28774. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  28775. this._lodPlanes[ i ].dispose();
  28776. }
  28777. }
  28778. _cleanup( outputTarget ) {
  28779. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  28780. outputTarget.scissorTest = false;
  28781. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  28782. }
  28783. _fromTexture( texture, renderTarget ) {
  28784. this._setSizeFromTexture( texture );
  28785. _oldTarget = this._renderer.getRenderTarget();
  28786. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  28787. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  28788. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  28789. this._textureToCubeUV( texture, cubeUVRenderTarget );
  28790. this._applyPMREM( cubeUVRenderTarget );
  28791. this._cleanup( cubeUVRenderTarget );
  28792. return cubeUVRenderTarget;
  28793. }
  28794. _allocateTargets() {
  28795. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  28796. const height = 4 * this._cubeSize;
  28797. const params = {
  28798. magFilter: LinearFilter,
  28799. minFilter: LinearFilter,
  28800. generateMipmaps: false,
  28801. type: HalfFloatType,
  28802. format: RGBAFormat,
  28803. colorSpace: LinearSRGBColorSpace,
  28804. //depthBuffer: false
  28805. };
  28806. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  28807. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  28808. if ( this._pingPongRenderTarget !== null ) {
  28809. this._dispose();
  28810. }
  28811. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  28812. const { _lodMax } = this;
  28813. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  28814. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  28815. }
  28816. return cubeUVRenderTarget;
  28817. }
  28818. async _compileMaterial( material ) {
  28819. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  28820. await this._renderer.compile( tmpMesh, _flatCamera );
  28821. }
  28822. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  28823. const cubeCamera = _cubeCamera;
  28824. cubeCamera.near = near;
  28825. cubeCamera.far = far;
  28826. // px, py, pz, nx, ny, nz
  28827. const upSign = [ 1, 1, 1, 1, - 1, 1 ];
  28828. const forwardSign = [ 1, - 1, 1, - 1, 1, - 1 ];
  28829. const renderer = this._renderer;
  28830. const originalAutoClear = renderer.autoClear;
  28831. renderer.getClearColor( _clearColor );
  28832. renderer.autoClear = false;
  28833. let backgroundBox = this._backgroundBox;
  28834. if ( backgroundBox === null ) {
  28835. const backgroundMaterial = new MeshBasicMaterial( {
  28836. name: 'PMREM.Background',
  28837. side: BackSide,
  28838. depthWrite: false,
  28839. depthTest: false
  28840. } );
  28841. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  28842. }
  28843. let useSolidColor = false;
  28844. const background = scene.background;
  28845. if ( background ) {
  28846. if ( background.isColor ) {
  28847. backgroundBox.material.color.copy( background );
  28848. scene.background = null;
  28849. useSolidColor = true;
  28850. }
  28851. } else {
  28852. backgroundBox.material.color.copy( _clearColor );
  28853. useSolidColor = true;
  28854. }
  28855. renderer.setRenderTarget( cubeUVRenderTarget );
  28856. renderer.clear();
  28857. if ( useSolidColor ) {
  28858. renderer.render( backgroundBox, cubeCamera );
  28859. }
  28860. for ( let i = 0; i < 6; i ++ ) {
  28861. const col = i % 3;
  28862. if ( col === 0 ) {
  28863. cubeCamera.up.set( 0, upSign[ i ], 0 );
  28864. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  28865. } else if ( col === 1 ) {
  28866. cubeCamera.up.set( 0, 0, upSign[ i ] );
  28867. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  28868. } else {
  28869. cubeCamera.up.set( 0, upSign[ i ], 0 );
  28870. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  28871. }
  28872. const size = this._cubeSize;
  28873. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  28874. renderer.render( scene, cubeCamera );
  28875. }
  28876. renderer.autoClear = originalAutoClear;
  28877. scene.background = background;
  28878. }
  28879. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  28880. const renderer = this._renderer;
  28881. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  28882. if ( isCubeTexture ) {
  28883. if ( this._cubemapMaterial === null ) {
  28884. this._cubemapMaterial = _getCubemapMaterial( texture );
  28885. }
  28886. } else {
  28887. if ( this._equirectMaterial === null ) {
  28888. this._equirectMaterial = _getEquirectMaterial( texture );
  28889. }
  28890. }
  28891. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  28892. material.fragmentNode.value = texture;
  28893. const mesh = this._lodMeshes[ 0 ];
  28894. mesh.material = material;
  28895. const size = this._cubeSize;
  28896. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  28897. renderer.setRenderTarget( cubeUVRenderTarget );
  28898. renderer.render( mesh, _flatCamera );
  28899. }
  28900. _applyPMREM( cubeUVRenderTarget ) {
  28901. const renderer = this._renderer;
  28902. const autoClear = renderer.autoClear;
  28903. renderer.autoClear = false;
  28904. const n = this._lodPlanes.length;
  28905. for ( let i = 1; i < n; i ++ ) {
  28906. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  28907. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  28908. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  28909. }
  28910. renderer.autoClear = autoClear;
  28911. }
  28912. /**
  28913. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  28914. * vertically and horizontally, but this breaks down on a cube. Here we apply
  28915. * the blur latitudinally (around the poles), and then longitudinally (towards
  28916. * the poles) to approximate the orthogonally-separable blur. It is least
  28917. * accurate at the poles, but still does a decent job.
  28918. *
  28919. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  28920. * @param {Number} lodIn - The input level-of-detail.
  28921. * @param {Number} lodOut - The output level-of-detail.
  28922. * @param {Number} sigma - The blur radius in radians.
  28923. * @param {Vector3} [poleAxis] - The pole axis.
  28924. */
  28925. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  28926. const pingPongRenderTarget = this._pingPongRenderTarget;
  28927. this._halfBlur(
  28928. cubeUVRenderTarget,
  28929. pingPongRenderTarget,
  28930. lodIn,
  28931. lodOut,
  28932. sigma,
  28933. 'latitudinal',
  28934. poleAxis );
  28935. this._halfBlur(
  28936. pingPongRenderTarget,
  28937. cubeUVRenderTarget,
  28938. lodOut,
  28939. lodOut,
  28940. sigma,
  28941. 'longitudinal',
  28942. poleAxis );
  28943. }
  28944. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  28945. const renderer = this._renderer;
  28946. const blurMaterial = this._blurMaterial;
  28947. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  28948. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  28949. }
  28950. // Number of standard deviations at which to cut off the discrete approximation.
  28951. const STANDARD_DEVIATIONS = 3;
  28952. const blurMesh = this._lodMeshes[ lodOut ];
  28953. blurMesh.material = blurMaterial;
  28954. const blurUniforms = blurMaterial.uniforms;
  28955. const pixels = this._sizeLods[ lodIn ] - 1;
  28956. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  28957. const sigmaPixels = sigmaRadians / radiansPerPixel;
  28958. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  28959. if ( samples > MAX_SAMPLES ) {
  28960. console.warn( `sigmaRadians, ${
  28961. sigmaRadians}, is too large and will clip, as it requested ${
  28962. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  28963. }
  28964. const weights = [];
  28965. let sum = 0;
  28966. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  28967. const x = i / sigmaPixels;
  28968. const weight = Math.exp( - x * x / 2 );
  28969. weights.push( weight );
  28970. if ( i === 0 ) {
  28971. sum += weight;
  28972. } else if ( i < samples ) {
  28973. sum += 2 * weight;
  28974. }
  28975. }
  28976. for ( let i = 0; i < weights.length; i ++ ) {
  28977. weights[ i ] = weights[ i ] / sum;
  28978. }
  28979. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  28980. blurUniforms.envMap.value = targetIn.texture;
  28981. blurUniforms.samples.value = samples;
  28982. blurUniforms.weights.array = weights;
  28983. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  28984. if ( poleAxis ) {
  28985. blurUniforms.poleAxis.value = poleAxis;
  28986. }
  28987. const { _lodMax } = this;
  28988. blurUniforms.dTheta.value = radiansPerPixel;
  28989. blurUniforms.mipInt.value = _lodMax - lodIn;
  28990. const outputSize = this._sizeLods[ lodOut ];
  28991. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  28992. const y = 4 * ( this._cubeSize - outputSize );
  28993. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  28994. renderer.setRenderTarget( targetOut );
  28995. renderer.render( blurMesh, _flatCamera );
  28996. }
  28997. }
  28998. function _createPlanes( lodMax ) {
  28999. const lodPlanes = [];
  29000. const sizeLods = [];
  29001. const sigmas = [];
  29002. const lodMeshes = [];
  29003. let lod = lodMax;
  29004. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29005. for ( let i = 0; i < totalLods; i ++ ) {
  29006. const sizeLod = Math.pow( 2, lod );
  29007. sizeLods.push( sizeLod );
  29008. let sigma = 1.0 / sizeLod;
  29009. if ( i > lodMax - LOD_MIN ) {
  29010. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  29011. } else if ( i === 0 ) {
  29012. sigma = 0;
  29013. }
  29014. sigmas.push( sigma );
  29015. const texelSize = 1.0 / ( sizeLod - 2 );
  29016. const min = - texelSize;
  29017. const max = 1 + texelSize;
  29018. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29019. const cubeFaces = 6;
  29020. const vertices = 6;
  29021. const positionSize = 3;
  29022. const uvSize = 2;
  29023. const faceIndexSize = 1;
  29024. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29025. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29026. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29027. for ( let face = 0; face < cubeFaces; face ++ ) {
  29028. const x = ( face % 3 ) * 2 / 3 - 1;
  29029. const y = face > 2 ? 0 : - 1;
  29030. const coordinates = [
  29031. x, y, 0,
  29032. x + 2 / 3, y, 0,
  29033. x + 2 / 3, y + 1, 0,
  29034. x, y, 0,
  29035. x + 2 / 3, y + 1, 0,
  29036. x, y + 1, 0
  29037. ];
  29038. const faceIdx = _faceLib[ face ];
  29039. position.set( coordinates, positionSize * vertices * faceIdx );
  29040. uv.set( uv1, uvSize * vertices * faceIdx );
  29041. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  29042. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  29043. }
  29044. const planes = new BufferGeometry();
  29045. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29046. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29047. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29048. lodPlanes.push( planes );
  29049. lodMeshes.push( new Mesh( planes, null ) );
  29050. if ( lod > LOD_MIN ) {
  29051. lod --;
  29052. }
  29053. }
  29054. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  29055. }
  29056. function _createRenderTarget( width, height, params ) {
  29057. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  29058. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29059. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29060. cubeUVRenderTarget.texture.isPMREMTexture = true;
  29061. cubeUVRenderTarget.scissorTest = true;
  29062. return cubeUVRenderTarget;
  29063. }
  29064. function _setViewport( target, x, y, width, height ) {
  29065. target.viewport.set( x, y, width, height );
  29066. target.scissor.set( x, y, width, height );
  29067. }
  29068. function _getMaterial( type ) {
  29069. const material = new NodeMaterial();
  29070. material.depthTest = false;
  29071. material.depthWrite = false;
  29072. material.blending = NoBlending;
  29073. material.name = `PMREM_${ type }`;
  29074. return material;
  29075. }
  29076. function _getBlurShader( lodMax, width, height ) {
  29077. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  29078. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  29079. const dTheta = uniform( 0 );
  29080. const n = float( MAX_SAMPLES );
  29081. const latitudinal = uniform( 0 ); // false, bool
  29082. const samples = uniform( 1 ); // int
  29083. const envMap = texture( null );
  29084. const mipInt = uniform( 0 ); // int
  29085. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  29086. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  29087. const CUBEUV_MAX_MIP = float( lodMax );
  29088. const materialUniforms = {
  29089. n,
  29090. latitudinal,
  29091. weights,
  29092. poleAxis,
  29093. outputDirection,
  29094. dTheta,
  29095. samples,
  29096. envMap,
  29097. mipInt,
  29098. CUBEUV_TEXEL_WIDTH,
  29099. CUBEUV_TEXEL_HEIGHT,
  29100. CUBEUV_MAX_MIP
  29101. };
  29102. const material = _getMaterial( 'blur' );
  29103. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  29104. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  29105. return material;
  29106. }
  29107. function _getCubemapMaterial( envTexture ) {
  29108. const material = _getMaterial( 'cubemap' );
  29109. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  29110. return material;
  29111. }
  29112. function _getEquirectMaterial( envTexture ) {
  29113. const material = _getMaterial( 'equirect' );
  29114. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  29115. return material;
  29116. }
  29117. const rendererCache = new WeakMap();
  29118. const typeFromArray = new Map( [
  29119. [ Int8Array, 'int' ],
  29120. [ Int16Array, 'int' ],
  29121. [ Int32Array, 'int' ],
  29122. [ Uint8Array, 'uint' ],
  29123. [ Uint16Array, 'uint' ],
  29124. [ Uint32Array, 'uint' ],
  29125. [ Float32Array, 'float' ]
  29126. ] );
  29127. const toFloat = ( value ) => {
  29128. if ( /e/g.test( value ) ) {
  29129. return String( value ).replace( /\+/g, '' );
  29130. } else {
  29131. value = Number( value );
  29132. return value + ( value % 1 ? '' : '.0' );
  29133. }
  29134. };
  29135. /**
  29136. * Base class for builders which generate a shader program based
  29137. * on a 3D object and its node material definition.
  29138. */
  29139. class NodeBuilder {
  29140. /**
  29141. * Constructs a new node builder.
  29142. *
  29143. * @param {Object3D} object - The 3D object.
  29144. * @param {Renderer} renderer - The current renderer.
  29145. * @param {NodeParser} parser - A reference to a node parser.
  29146. */
  29147. constructor( object, renderer, parser ) {
  29148. /**
  29149. * The 3D object.
  29150. *
  29151. * @type {Object3D}
  29152. */
  29153. this.object = object;
  29154. /**
  29155. * The material of the 3D object.
  29156. *
  29157. * @type {Material?}
  29158. */
  29159. this.material = ( object && object.material ) || null;
  29160. /**
  29161. * The geometry of the 3D object.
  29162. *
  29163. * @type {BufferGeometry?}
  29164. */
  29165. this.geometry = ( object && object.geometry ) || null;
  29166. /**
  29167. * The current renderer.
  29168. *
  29169. * @type {Renderer}
  29170. */
  29171. this.renderer = renderer;
  29172. /**
  29173. * A reference to a node parser.
  29174. *
  29175. * @type {NodeParser}
  29176. */
  29177. this.parser = parser;
  29178. /**
  29179. * The scene the 3D object belongs to.
  29180. *
  29181. * @type {Scene?}
  29182. * @default null
  29183. */
  29184. this.scene = null;
  29185. /**
  29186. * The camera the 3D object is rendered with.
  29187. *
  29188. * @type {Camera?}
  29189. * @default null
  29190. */
  29191. this.camera = null;
  29192. /**
  29193. * A list of all nodes the builder is processing
  29194. * for this 3D object.
  29195. *
  29196. * @type {Array<Node>}
  29197. */
  29198. this.nodes = [];
  29199. /**
  29200. * A list of all sequential nodes.
  29201. *
  29202. * @type {Array<Node>}
  29203. */
  29204. this.sequentialNodes = [];
  29205. /**
  29206. * A list of all nodes which {@link Node#update} method should be executed.
  29207. *
  29208. * @type {Array<Node>}
  29209. */
  29210. this.updateNodes = [];
  29211. /**
  29212. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  29213. *
  29214. * @type {Array<Node>}
  29215. */
  29216. this.updateBeforeNodes = [];
  29217. /**
  29218. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  29219. *
  29220. * @type {Array<Node>}
  29221. */
  29222. this.updateAfterNodes = [];
  29223. /**
  29224. * A dictionary that assigns each node to a unique hash.
  29225. *
  29226. * @type {Object<Number,Node>}
  29227. */
  29228. this.hashNodes = {};
  29229. /**
  29230. * A reference to a node material observer.
  29231. *
  29232. * @type {NodeMaterialObserver?}
  29233. * @default null
  29234. */
  29235. this.monitor = null;
  29236. /**
  29237. * A reference to the current lights node.
  29238. *
  29239. * @type {LightsNode?}
  29240. * @default null
  29241. */
  29242. this.lightsNode = null;
  29243. /**
  29244. * A reference to the current environment node.
  29245. *
  29246. * @type {Node?}
  29247. * @default null
  29248. */
  29249. this.environmentNode = null;
  29250. /**
  29251. * A reference to the current fog node.
  29252. *
  29253. * @type {FogNode?}
  29254. * @default null
  29255. */
  29256. this.fogNode = null;
  29257. /**
  29258. * The current clipping context.
  29259. *
  29260. * @type {ClippingContext?}
  29261. */
  29262. this.clippingContext = null;
  29263. /**
  29264. * The generated vertex shader.
  29265. *
  29266. * @type {String?}
  29267. */
  29268. this.vertexShader = null;
  29269. /**
  29270. * The generated fragment shader.
  29271. *
  29272. * @type {String?}
  29273. */
  29274. this.fragmentShader = null;
  29275. /**
  29276. * The generated compute shader.
  29277. *
  29278. * @type {String?}
  29279. */
  29280. this.computeShader = null;
  29281. /**
  29282. * Nodes used in the primary flow of code generation.
  29283. *
  29284. * @type {Object<String,Array<Node>>}
  29285. */
  29286. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  29287. /**
  29288. * Nodes code from `.flowNodes`.
  29289. *
  29290. * @type {Object<String,String>}
  29291. */
  29292. this.flowCode = { vertex: '', fragment: '', compute: '' };
  29293. /**
  29294. * This dictionary holds the node uniforms of the builder.
  29295. * The uniforms are maintained in an array for each shader stage.
  29296. *
  29297. * @type {Object}
  29298. */
  29299. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  29300. /**
  29301. * This dictionary holds the output structs of the builder.
  29302. * The structs are maintained in an array for each shader stage.
  29303. *
  29304. * @type {Object}
  29305. */
  29306. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  29307. /**
  29308. * This dictionary holds the bindings for each shader stage.
  29309. *
  29310. * @type {Object}
  29311. */
  29312. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  29313. /**
  29314. * This dictionary maintains the binding indices per bind group.
  29315. *
  29316. * @type {Object}
  29317. */
  29318. this.bindingsIndexes = {};
  29319. /**
  29320. * Reference to the array of bind groups.
  29321. *
  29322. * @type {Array<BindGroup>?}
  29323. */
  29324. this.bindGroups = null;
  29325. /**
  29326. * This array holds the node attributes of this builder
  29327. * created via {@link AttributeNode}.
  29328. *
  29329. * @type {Array<NodeAttribute>}
  29330. */
  29331. this.attributes = [];
  29332. /**
  29333. * This array holds the node attributes of this builder
  29334. * created via {@link BufferAttributeNode}.
  29335. *
  29336. * @type {Array<NodeAttribute>}
  29337. */
  29338. this.bufferAttributes = [];
  29339. /**
  29340. * This array holds the node varyings of this builder.
  29341. *
  29342. * @type {Array<NodeVarying>}
  29343. */
  29344. this.varyings = [];
  29345. /**
  29346. * This dictionary holds the (native) node codes of this builder.
  29347. * The codes are maintained in an array for each shader stage.
  29348. *
  29349. * @type {Object<String,Array<NodeCode>>}
  29350. */
  29351. this.codes = {};
  29352. /**
  29353. * This dictionary holds the node variables of this builder.
  29354. * The variables are maintained in an array for each shader stage.
  29355. *
  29356. * @type {Object<String,Array<NodeVar>>}
  29357. */
  29358. this.vars = {};
  29359. /**
  29360. * Current code flow.
  29361. * All code generated in this stack will be stored in `.flow`.
  29362. *
  29363. * @type {{code: String}}
  29364. */
  29365. this.flow = { code: '' };
  29366. /**
  29367. * A chain of nodes.
  29368. * Used to check recursive calls in node-graph.
  29369. *
  29370. * @type {Array<Node>}
  29371. */
  29372. this.chaining = [];
  29373. /**
  29374. * The current stack.
  29375. * This reflects the current process in the code block hierarchy,
  29376. * it is useful to know if the current process is inside a conditional for example.
  29377. *
  29378. * @type {StackNode}
  29379. */
  29380. this.stack = stack();
  29381. /**
  29382. * List of stack nodes.
  29383. * The current stack hierarchy is stored in an array.
  29384. *
  29385. * @type {Array<StackNode>}
  29386. */
  29387. this.stacks = [];
  29388. /**
  29389. * A tab value. Used for shader string generation.
  29390. *
  29391. * @type {String}
  29392. * @default '\t'
  29393. */
  29394. this.tab = '\t';
  29395. /**
  29396. * Reference to the current function node.
  29397. *
  29398. * @type {FunctionNode?}
  29399. * @default null
  29400. */
  29401. this.currentFunctionNode = null;
  29402. /**
  29403. * The builder's context.
  29404. *
  29405. * @type {Object}
  29406. */
  29407. this.context = {
  29408. material: this.material
  29409. };
  29410. /**
  29411. * The builder's cache.
  29412. *
  29413. * @type {NodeCache}
  29414. */
  29415. this.cache = new NodeCache();
  29416. /**
  29417. * Since the {@link NodeBuilder#cache} might be temporarily
  29418. * overwritten by other caches, this member retains the reference
  29419. * to the builder's own cache.
  29420. *
  29421. * @type {NodeCache}
  29422. * @default this.cache
  29423. */
  29424. this.globalCache = this.cache;
  29425. this.flowsData = new WeakMap();
  29426. /**
  29427. * The current shader stage.
  29428. *
  29429. * @type {('vertex'|'fragment'|'compute'|'any')?}
  29430. */
  29431. this.shaderStage = null;
  29432. /**
  29433. * The current build stage.
  29434. *
  29435. * @type {('setup'|'analyze'|'generate')?}
  29436. */
  29437. this.buildStage = null;
  29438. /**
  29439. * Whether comparison in shader code are generated with methods or not.
  29440. *
  29441. * @type {Boolean}
  29442. * @default false
  29443. */
  29444. this.useComparisonMethod = false;
  29445. }
  29446. /**
  29447. * Returns the bind groups of the current renderer.
  29448. *
  29449. * @return {ChainMap} The cache.
  29450. */
  29451. getBindGroupsCache() {
  29452. let bindGroupsCache = rendererCache.get( this.renderer );
  29453. if ( bindGroupsCache === undefined ) {
  29454. bindGroupsCache = new ChainMap();
  29455. rendererCache.set( this.renderer, bindGroupsCache );
  29456. }
  29457. return bindGroupsCache;
  29458. }
  29459. /**
  29460. * Factory method for creating an instance of {@link RenderTarget} with the given
  29461. * dimensions and options.
  29462. *
  29463. * @param {Number} width - The width of the render target.
  29464. * @param {Number} height - The height of the render target.
  29465. * @param {Object} options - The options of the render target.
  29466. * @return {RenderTarget} The render target.
  29467. */
  29468. createRenderTarget( width, height, options ) {
  29469. return new RenderTarget( width, height, options );
  29470. }
  29471. /**
  29472. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  29473. * dimensions and options.
  29474. *
  29475. * @param {Number} size - The size of the cube render target.
  29476. * @param {Object} options - The options of the cube render target.
  29477. * @return {CubeRenderTarget} The cube render target.
  29478. */
  29479. createCubeRenderTarget( size, options ) {
  29480. return new CubeRenderTarget( size, options );
  29481. }
  29482. /**
  29483. * Factory method for creating an instance of {@link PMREMGenerator}.
  29484. *
  29485. * @return {PMREMGenerator} The PMREM generator.
  29486. */
  29487. createPMREMGenerator() {
  29488. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  29489. return new PMREMGenerator( this.renderer );
  29490. }
  29491. /**
  29492. * Whether the given node is included in the internal array of nodes or not.
  29493. *
  29494. * @param {Node} node - The node to test.
  29495. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  29496. */
  29497. includes( node ) {
  29498. return this.nodes.includes( node );
  29499. }
  29500. /**
  29501. * Returns a bind group for the given group name and binding.
  29502. *
  29503. * @private
  29504. * @param {String} groupName - The group name.
  29505. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  29506. * @return {BindGroup} The bind group
  29507. */
  29508. _getBindGroup( groupName, bindings ) {
  29509. const bindGroupsCache = this.getBindGroupsCache();
  29510. //
  29511. const bindingsArray = [];
  29512. let sharedGroup = true;
  29513. for ( const binding of bindings ) {
  29514. bindingsArray.push( binding );
  29515. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  29516. }
  29517. //
  29518. let bindGroup;
  29519. if ( sharedGroup ) {
  29520. bindGroup = bindGroupsCache.get( bindingsArray );
  29521. if ( bindGroup === undefined ) {
  29522. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29523. bindGroupsCache.set( bindingsArray, bindGroup );
  29524. }
  29525. } else {
  29526. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29527. }
  29528. return bindGroup;
  29529. }
  29530. /**
  29531. * Returns an array of node uniform groups for the given group name and shader stage.
  29532. *
  29533. * @param {String} groupName - The group name.
  29534. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  29535. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  29536. */
  29537. getBindGroupArray( groupName, shaderStage ) {
  29538. const bindings = this.bindings[ shaderStage ];
  29539. let bindGroup = bindings[ groupName ];
  29540. if ( bindGroup === undefined ) {
  29541. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  29542. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  29543. }
  29544. bindings[ groupName ] = bindGroup = [];
  29545. }
  29546. return bindGroup;
  29547. }
  29548. /**
  29549. * Returns a list bindings of all shader stages separated by groups.
  29550. *
  29551. * @return {Array<BindGroup>} The list of bindings.
  29552. */
  29553. getBindings() {
  29554. let bindingsGroups = this.bindGroups;
  29555. if ( bindingsGroups === null ) {
  29556. const groups = {};
  29557. const bindings = this.bindings;
  29558. for ( const shaderStage of shaderStages ) {
  29559. for ( const groupName in bindings[ shaderStage ] ) {
  29560. const uniforms = bindings[ shaderStage ][ groupName ];
  29561. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  29562. groupUniforms.push( ...uniforms );
  29563. }
  29564. }
  29565. bindingsGroups = [];
  29566. for ( const groupName in groups ) {
  29567. const group = groups[ groupName ];
  29568. const bindingsGroup = this._getBindGroup( groupName, group );
  29569. bindingsGroups.push( bindingsGroup );
  29570. }
  29571. this.bindGroups = bindingsGroups;
  29572. }
  29573. return bindingsGroups;
  29574. }
  29575. /**
  29576. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  29577. */
  29578. sortBindingGroups() {
  29579. const bindingsGroups = this.getBindings();
  29580. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  29581. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  29582. const bindingGroup = bindingsGroups[ i ];
  29583. this.bindingsIndexes[ bindingGroup.name ].group = i;
  29584. bindingGroup.index = i;
  29585. }
  29586. }
  29587. /**
  29588. * The builder maintains each node in a hash-based dictionary.
  29589. * This method sets the given node (value) with the given hash (key) into this dictionary.
  29590. *
  29591. * @param {Node} node - The node to add.
  29592. * @param {Number} hash - The hash of the node.
  29593. */
  29594. setHashNode( node, hash ) {
  29595. this.hashNodes[ hash ] = node;
  29596. }
  29597. /**
  29598. * Adds a node to this builder.
  29599. *
  29600. * @param {Node} node - The node to add.
  29601. */
  29602. addNode( node ) {
  29603. if ( this.nodes.includes( node ) === false ) {
  29604. this.nodes.push( node );
  29605. this.setHashNode( node, node.getHash( this ) );
  29606. }
  29607. }
  29608. /**
  29609. * It is used to add Nodes that will be used as FRAME and RENDER events,
  29610. * and need to follow a certain sequence in the calls to work correctly.
  29611. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  29612. *
  29613. * @param {Node} node - The node to add.
  29614. */
  29615. addSequentialNode( node ) {
  29616. if ( this.sequentialNodes.includes( node ) === false ) {
  29617. this.sequentialNodes.push( node );
  29618. }
  29619. }
  29620. /**
  29621. * Checks the update types of nodes
  29622. */
  29623. buildUpdateNodes() {
  29624. for ( const node of this.nodes ) {
  29625. const updateType = node.getUpdateType();
  29626. if ( updateType !== NodeUpdateType.NONE ) {
  29627. this.updateNodes.push( node.getSelf() );
  29628. }
  29629. }
  29630. for ( const node of this.sequentialNodes ) {
  29631. const updateBeforeType = node.getUpdateBeforeType();
  29632. const updateAfterType = node.getUpdateAfterType();
  29633. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  29634. this.updateBeforeNodes.push( node.getSelf() );
  29635. }
  29636. if ( updateAfterType !== NodeUpdateType.NONE ) {
  29637. this.updateAfterNodes.push( node.getSelf() );
  29638. }
  29639. }
  29640. }
  29641. /**
  29642. * A reference the current node which is the
  29643. * last node in the chain of nodes.
  29644. *
  29645. * @type {Node}
  29646. */
  29647. get currentNode() {
  29648. return this.chaining[ this.chaining.length - 1 ];
  29649. }
  29650. /**
  29651. * Whether the given texture is filtered or not.
  29652. *
  29653. * @param {Texture} texture - The texture to check.
  29654. * @return {Boolean} Whether the given texture is filtered or not.
  29655. */
  29656. isFilteredTexture( texture ) {
  29657. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  29658. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  29659. }
  29660. /**
  29661. * Adds the given node to the internal node chain.
  29662. * This is used to check recursive calls in node-graph.
  29663. *
  29664. * @param {Node} node - The node to add.
  29665. */
  29666. addChain( node ) {
  29667. /*
  29668. if ( this.chaining.indexOf( node ) !== - 1 ) {
  29669. console.warn( 'Recursive node: ', node );
  29670. }
  29671. */
  29672. this.chaining.push( node );
  29673. }
  29674. /**
  29675. * Removes the given node from the internal node chain.
  29676. *
  29677. * @param {Node} node - The node to remove.
  29678. */
  29679. removeChain( node ) {
  29680. const lastChain = this.chaining.pop();
  29681. if ( lastChain !== node ) {
  29682. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  29683. }
  29684. }
  29685. /**
  29686. * Returns the native shader method name for a given generic name. E.g.
  29687. * the method name `textureDimensions` matches the WGSL name but must be
  29688. * resolved to `textureSize` in GLSL.
  29689. *
  29690. * @abstract
  29691. * @param {String} method - The method name to resolve.
  29692. * @return {String} The resolved method name.
  29693. */
  29694. getMethod( method ) {
  29695. return method;
  29696. }
  29697. /**
  29698. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  29699. *
  29700. * @param {Number} hash - The hash of the node.
  29701. * @return {Node} The found node.
  29702. */
  29703. getNodeFromHash( hash ) {
  29704. return this.hashNodes[ hash ];
  29705. }
  29706. /**
  29707. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  29708. *
  29709. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  29710. * @param {Node} node - The node to add.
  29711. * @return {Node} The node.
  29712. */
  29713. addFlow( shaderStage, node ) {
  29714. this.flowNodes[ shaderStage ].push( node );
  29715. return node;
  29716. }
  29717. /**
  29718. * Sets builder's context.
  29719. *
  29720. * @param {Object} context - The context to set.
  29721. */
  29722. setContext( context ) {
  29723. this.context = context;
  29724. }
  29725. /**
  29726. * Returns the builder's current context.
  29727. *
  29728. * @return {Object} The builder's current context.
  29729. */
  29730. getContext() {
  29731. return this.context;
  29732. }
  29733. /**
  29734. * Gets a context used in shader construction that can be shared across different materials.
  29735. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  29736. *
  29737. * @return {Object} The builder's current context without material.
  29738. */
  29739. getSharedContext() {
  29740. ({ ...this.context });
  29741. return this.context;
  29742. }
  29743. /**
  29744. * Sets builder's cache.
  29745. *
  29746. * @param {NodeCache} cache - The cache to set.
  29747. */
  29748. setCache( cache ) {
  29749. this.cache = cache;
  29750. }
  29751. /**
  29752. * Returns the builder's current cache.
  29753. *
  29754. * @return {NodeCache} The builder's current cache.
  29755. */
  29756. getCache() {
  29757. return this.cache;
  29758. }
  29759. /**
  29760. * Returns a cache for the given node.
  29761. *
  29762. * @param {Node} node - The node.
  29763. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  29764. * @return {NodeCache} The cache.
  29765. */
  29766. getCacheFromNode( node, parent = true ) {
  29767. const data = this.getDataFromNode( node );
  29768. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  29769. return data.cache;
  29770. }
  29771. /**
  29772. * Whether the requested feature is available or not.
  29773. *
  29774. * @abstract
  29775. * @param {String} name - The requested feature.
  29776. * @return {Boolean} Whether the requested feature is supported or not.
  29777. */
  29778. isAvailable( /*name*/ ) {
  29779. return false;
  29780. }
  29781. /**
  29782. * Returns the vertexIndex input variable as a native shader string.
  29783. *
  29784. * @abstract
  29785. * @return {String} The instanceIndex shader string.
  29786. */
  29787. getVertexIndex() {
  29788. console.warn( 'Abstract function.' );
  29789. }
  29790. /**
  29791. * Returns the instanceIndex input variable as a native shader string.
  29792. *
  29793. * @abstract
  29794. * @return {String} The instanceIndex shader string.
  29795. */
  29796. getInstanceIndex() {
  29797. console.warn( 'Abstract function.' );
  29798. }
  29799. /**
  29800. * Returns the drawIndex input variable as a native shader string.
  29801. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  29802. *
  29803. * @abstract
  29804. * @return {String} The drawIndex shader string.
  29805. */
  29806. getDrawIndex() {
  29807. console.warn( 'Abstract function.' );
  29808. }
  29809. /**
  29810. * Returns the frontFacing input variable as a native shader string.
  29811. *
  29812. * @abstract
  29813. * @return {String} The frontFacing shader string.
  29814. */
  29815. getFrontFacing() {
  29816. console.warn( 'Abstract function.' );
  29817. }
  29818. /**
  29819. * Returns the fragCoord input variable as a native shader string.
  29820. *
  29821. * @abstract
  29822. * @return {String} The fragCoord shader string.
  29823. */
  29824. getFragCoord() {
  29825. console.warn( 'Abstract function.' );
  29826. }
  29827. /**
  29828. * Whether to flip texture data along its vertical axis or not. WebGL needs
  29829. * this method evaluate to `true`, WebGPU to `false`.
  29830. *
  29831. * @abstract
  29832. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  29833. */
  29834. isFlipY() {
  29835. return false;
  29836. }
  29837. /**
  29838. * Calling this method increases the usage count for the given node by one.
  29839. *
  29840. * @param {Node} node - The node to increase the usage count for.
  29841. * @return {Number} The updated usage count.
  29842. */
  29843. increaseUsage( node ) {
  29844. const nodeData = this.getDataFromNode( node );
  29845. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  29846. return nodeData.usageCount;
  29847. }
  29848. /**
  29849. * Generates a texture sample shader string for the given texture data.
  29850. *
  29851. * @abstract
  29852. * @param {Texture} texture - The texture.
  29853. * @param {String} textureProperty - The texture property name.
  29854. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  29855. * @return {String} The generated shader string.
  29856. */
  29857. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  29858. console.warn( 'Abstract function.' );
  29859. }
  29860. /**
  29861. * Generates a texture LOD shader string for the given texture data.
  29862. *
  29863. * @abstract
  29864. * @param {Texture} texture - The texture.
  29865. * @param {String} textureProperty - The texture property name.
  29866. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  29867. * @param {String} levelSnippet - Snippet defining the mip level.
  29868. * @return {String} The generated shader string.
  29869. */
  29870. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  29871. console.warn( 'Abstract function.' );
  29872. }
  29873. /**
  29874. * Generates the shader string for the given type and value.
  29875. *
  29876. * @param {String} type - The type.
  29877. * @param {Any?} [value=null] - The value.
  29878. * @return {String} The generated value as a shader string.
  29879. */
  29880. generateConst( type, value = null ) {
  29881. if ( value === null ) {
  29882. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  29883. else if ( type === 'bool' ) value = false;
  29884. else if ( type === 'color' ) value = new Color();
  29885. else if ( type === 'vec2' ) value = new Vector2();
  29886. else if ( type === 'vec3' ) value = new Vector3();
  29887. else if ( type === 'vec4' ) value = new Vector4();
  29888. }
  29889. if ( type === 'float' ) return toFloat( value );
  29890. if ( type === 'int' ) return `${ Math.round( value ) }`;
  29891. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  29892. if ( type === 'bool' ) return value ? 'true' : 'false';
  29893. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  29894. const typeLength = this.getTypeLength( type );
  29895. const componentType = this.getComponentType( type );
  29896. const generateConst = value => this.generateConst( componentType, value );
  29897. if ( typeLength === 2 ) {
  29898. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  29899. } else if ( typeLength === 3 ) {
  29900. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  29901. } else if ( typeLength === 4 ) {
  29902. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  29903. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  29904. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  29905. } else if ( typeLength > 4 ) {
  29906. return `${ this.getType( type ) }()`;
  29907. }
  29908. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  29909. }
  29910. /**
  29911. * It might be necessary to convert certain data types to different ones
  29912. * so this method can be used to hide the conversion.
  29913. *
  29914. * @param {String} type - The type.
  29915. * @return {String} The updated type.
  29916. */
  29917. getType( type ) {
  29918. if ( type === 'color' ) return 'vec3';
  29919. return type;
  29920. }
  29921. /**
  29922. * Whether the given attribute name is defined in the geometry or not.
  29923. *
  29924. * @param {String} name - The attribute name.
  29925. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  29926. */
  29927. hasGeometryAttribute( name ) {
  29928. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  29929. }
  29930. /**
  29931. * Returns a node attribute for the given name and type.
  29932. *
  29933. * @param {String} name - The attribute's name.
  29934. * @param {String} type - The attribute's type.
  29935. * @return {NodeAttribute} The node attribute.
  29936. */
  29937. getAttribute( name, type ) {
  29938. const attributes = this.attributes;
  29939. // find attribute
  29940. for ( const attribute of attributes ) {
  29941. if ( attribute.name === name ) {
  29942. return attribute;
  29943. }
  29944. }
  29945. // create a new if no exist
  29946. const attribute = new NodeAttribute( name, type );
  29947. attributes.push( attribute );
  29948. return attribute;
  29949. }
  29950. /**
  29951. * Returns for the given node and shader stage the property name for the shader.
  29952. *
  29953. * @param {Node} node - The node.
  29954. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  29955. * @return {String} The property name.
  29956. */
  29957. getPropertyName( node/*, shaderStage*/ ) {
  29958. return node.name;
  29959. }
  29960. /**
  29961. * Whether the given type is a vector type or not.
  29962. *
  29963. * @param {String} type - The type to check.
  29964. * @return {Boolean} Whether the given type is a vector type or not.
  29965. */
  29966. isVector( type ) {
  29967. return /vec\d/.test( type );
  29968. }
  29969. /**
  29970. * Whether the given type is a matrix type or not.
  29971. *
  29972. * @param {String} type - The type to check.
  29973. * @return {Boolean} Whether the given type is a matrix type or not.
  29974. */
  29975. isMatrix( type ) {
  29976. return /mat\d/.test( type );
  29977. }
  29978. /**
  29979. * Whether the given type is a reference type or not.
  29980. *
  29981. * @param {String} type - The type to check.
  29982. * @return {Boolean} Whether the given type is a reference type or not.
  29983. */
  29984. isReference( type ) {
  29985. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  29986. }
  29987. /**
  29988. * Whether the given texture needs a conversion to working color space.
  29989. *
  29990. * @abstract
  29991. * @param {Texture} texture - The texture to check.
  29992. * @return {Boolean} Whether a color space conversion is required or not.
  29993. */
  29994. needsToWorkingColorSpace( /*texture*/ ) {
  29995. return false;
  29996. }
  29997. /**
  29998. * Returns the component type of a given texture.
  29999. *
  30000. * @param {Texture} texture - The texture.
  30001. * @return {String} The component type.
  30002. */
  30003. getComponentTypeFromTexture( texture ) {
  30004. const type = texture.type;
  30005. if ( texture.isDataTexture ) {
  30006. if ( type === IntType ) return 'int';
  30007. if ( type === UnsignedIntType ) return 'uint';
  30008. }
  30009. return 'float';
  30010. }
  30011. /**
  30012. * Returns the element type for a given type.
  30013. *
  30014. * @param {String} type - The type.
  30015. * @return {String} The element type.
  30016. */
  30017. getElementType( type ) {
  30018. if ( type === 'mat2' ) return 'vec2';
  30019. if ( type === 'mat3' ) return 'vec3';
  30020. if ( type === 'mat4' ) return 'vec4';
  30021. return this.getComponentType( type );
  30022. }
  30023. /**
  30024. * Returns the component type for a given type.
  30025. *
  30026. * @param {String} type - The type.
  30027. * @return {String} The component type.
  30028. */
  30029. getComponentType( type ) {
  30030. type = this.getVectorType( type );
  30031. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  30032. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  30033. if ( componentType === null ) return null;
  30034. if ( componentType[ 1 ] === 'b' ) return 'bool';
  30035. if ( componentType[ 1 ] === 'i' ) return 'int';
  30036. if ( componentType[ 1 ] === 'u' ) return 'uint';
  30037. return 'float';
  30038. }
  30039. /**
  30040. * Returns the vector type for a given type.
  30041. *
  30042. * @param {String} type - The type.
  30043. * @return {String} The vector type.
  30044. */
  30045. getVectorType( type ) {
  30046. if ( type === 'color' ) return 'vec3';
  30047. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  30048. return type;
  30049. }
  30050. /**
  30051. * Returns the data type for the given the length and component type.
  30052. *
  30053. * @param {Number} length - The length.
  30054. * @param {String} [componentType='float'] - The component type.
  30055. * @return {String} The type.
  30056. */
  30057. getTypeFromLength( length, componentType = 'float' ) {
  30058. if ( length === 1 ) return componentType;
  30059. const baseType = getTypeFromLength( length );
  30060. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  30061. return prefix + baseType;
  30062. }
  30063. /**
  30064. * Returns the type for a given typed array.
  30065. *
  30066. * @param {TypedArray} array - The typed array.
  30067. * @return {String} The type.
  30068. */
  30069. getTypeFromArray( array ) {
  30070. return typeFromArray.get( array.constructor );
  30071. }
  30072. /**
  30073. * Returns the type for a given buffer attribute.
  30074. *
  30075. * @param {BufferAttribute} attribute - The buffer attribute.
  30076. * @return {String} The type.
  30077. */
  30078. getTypeFromAttribute( attribute ) {
  30079. let dataAttribute = attribute;
  30080. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  30081. const array = dataAttribute.array;
  30082. const itemSize = attribute.itemSize;
  30083. const normalized = attribute.normalized;
  30084. let arrayType;
  30085. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  30086. arrayType = this.getTypeFromArray( array );
  30087. }
  30088. return this.getTypeFromLength( itemSize, arrayType );
  30089. }
  30090. /**
  30091. * Returns the length for the given data type.
  30092. *
  30093. * @param {String} type - The data type.
  30094. * @return {Number} The length.
  30095. */
  30096. getTypeLength( type ) {
  30097. const vecType = this.getVectorType( type );
  30098. const vecNum = /vec([2-4])/.exec( vecType );
  30099. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  30100. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  30101. if ( /mat2/.test( type ) === true ) return 4;
  30102. if ( /mat3/.test( type ) === true ) return 9;
  30103. if ( /mat4/.test( type ) === true ) return 16;
  30104. return 0;
  30105. }
  30106. /**
  30107. * Returns the vector type for a given matrix type.
  30108. *
  30109. * @param {String} type - The matrix type.
  30110. * @return {String} The vector type.
  30111. */
  30112. getVectorFromMatrix( type ) {
  30113. return type.replace( 'mat', 'vec' );
  30114. }
  30115. /**
  30116. * For a given type this method changes the component type to the
  30117. * given value. E.g. `vec4` should be changed to the new component type
  30118. * `uint` which results in `uvec4`.
  30119. *
  30120. * @param {String} type - The type.
  30121. * @param {String} newComponentType - The new component type.
  30122. * @return {String} The new type.
  30123. */
  30124. changeComponentType( type, newComponentType ) {
  30125. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  30126. }
  30127. /**
  30128. * Returns the integer type pendant for the given type.
  30129. *
  30130. * @param {String} type - The type.
  30131. * @return {String} The integer type.
  30132. */
  30133. getIntegerType( type ) {
  30134. const componentType = this.getComponentType( type );
  30135. if ( componentType === 'int' || componentType === 'uint' ) return type;
  30136. return this.changeComponentType( type, 'int' );
  30137. }
  30138. /**
  30139. * Adds a stack node to the internal stack.
  30140. *
  30141. * @return {StackNode} The added stack node.
  30142. */
  30143. addStack() {
  30144. this.stack = stack( this.stack );
  30145. this.stacks.push( getCurrentStack() || this.stack );
  30146. setCurrentStack( this.stack );
  30147. return this.stack;
  30148. }
  30149. /**
  30150. * Removes the last stack node from the internal stack.
  30151. *
  30152. * @return {StackNode} The removed stack node.
  30153. */
  30154. removeStack() {
  30155. const lastStack = this.stack;
  30156. this.stack = lastStack.parent;
  30157. setCurrentStack( this.stacks.pop() );
  30158. return lastStack;
  30159. }
  30160. /**
  30161. * The builder maintains (cached) data for each node during the building process. This method
  30162. * can be used to get these data for a specific shader stage and cache.
  30163. *
  30164. * @param {Node} node - The node to get the data for.
  30165. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30166. * @param {NodeCache?} cache - An optional cache.
  30167. * @return {Object} The node data.
  30168. */
  30169. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  30170. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  30171. let nodeData = cache.getData( node );
  30172. if ( nodeData === undefined ) {
  30173. nodeData = {};
  30174. cache.setData( node, nodeData );
  30175. }
  30176. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  30177. return nodeData[ shaderStage ];
  30178. }
  30179. /**
  30180. * Returns the properties for the given node and shader stage.
  30181. *
  30182. * @param {Node} node - The node to get the properties for.
  30183. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  30184. * @return {Object} The node properties.
  30185. */
  30186. getNodeProperties( node, shaderStage = 'any' ) {
  30187. const nodeData = this.getDataFromNode( node, shaderStage );
  30188. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  30189. }
  30190. /**
  30191. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  30192. *
  30193. * @param {BufferAttributeNode} node - The buffer attribute node.
  30194. * @param {String} type - The node type.
  30195. * @return {NodeAttribute} The node attribute.
  30196. */
  30197. getBufferAttributeFromNode( node, type ) {
  30198. const nodeData = this.getDataFromNode( node );
  30199. let bufferAttribute = nodeData.bufferAttribute;
  30200. if ( bufferAttribute === undefined ) {
  30201. const index = this.uniforms.index ++;
  30202. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  30203. this.bufferAttributes.push( bufferAttribute );
  30204. nodeData.bufferAttribute = bufferAttribute;
  30205. }
  30206. return bufferAttribute;
  30207. }
  30208. /**
  30209. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  30210. *
  30211. * @param {OutputStructNode} node - The output struct node.
  30212. * @param {Array<String>} types - The output struct types.
  30213. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30214. * @return {StructTypeNode} The struct type attribute.
  30215. */
  30216. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  30217. const nodeData = this.getDataFromNode( node, shaderStage );
  30218. let structType = nodeData.structType;
  30219. if ( structType === undefined ) {
  30220. const index = this.structs.index ++;
  30221. structType = new StructTypeNode( 'StructType' + index, types );
  30222. this.structs[ shaderStage ].push( structType );
  30223. nodeData.structType = structType;
  30224. }
  30225. return structType;
  30226. }
  30227. /**
  30228. * Returns an instance of {@link NodeUniform} for the given uniform node.
  30229. *
  30230. * @param {UniformNode} node - The uniform node.
  30231. * @param {String} type - The uniform type.
  30232. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30233. * @param {String?} name - The name of the uniform.
  30234. * @return {NodeUniform} The node uniform.
  30235. */
  30236. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  30237. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  30238. let nodeUniform = nodeData.uniform;
  30239. if ( nodeUniform === undefined ) {
  30240. const index = this.uniforms.index ++;
  30241. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  30242. this.uniforms[ shaderStage ].push( nodeUniform );
  30243. nodeData.uniform = nodeUniform;
  30244. }
  30245. return nodeUniform;
  30246. }
  30247. /**
  30248. * Returns an instance of {@link NodeVar} for the given variable node.
  30249. *
  30250. * @param {VarNode} node - The variable node.
  30251. * @param {String?} name - The variable's name.
  30252. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  30253. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30254. * @return {NodeVar} The node variable.
  30255. */
  30256. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  30257. const nodeData = this.getDataFromNode( node, shaderStage );
  30258. let nodeVar = nodeData.variable;
  30259. if ( nodeVar === undefined ) {
  30260. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  30261. if ( name === null ) name = 'nodeVar' + vars.length;
  30262. nodeVar = new NodeVar( name, type );
  30263. vars.push( nodeVar );
  30264. nodeData.variable = nodeVar;
  30265. }
  30266. return nodeVar;
  30267. }
  30268. /**
  30269. * Returns an instance of {@link NodeVarying} for the given varying node.
  30270. *
  30271. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  30272. * @param {String?} name - The varying's name.
  30273. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  30274. * @return {NodeVar} The node varying.
  30275. */
  30276. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  30277. const nodeData = this.getDataFromNode( node, 'any' );
  30278. let nodeVarying = nodeData.varying;
  30279. if ( nodeVarying === undefined ) {
  30280. const varyings = this.varyings;
  30281. const index = varyings.length;
  30282. if ( name === null ) name = 'nodeVarying' + index;
  30283. nodeVarying = new NodeVarying( name, type );
  30284. varyings.push( nodeVarying );
  30285. nodeData.varying = nodeVarying;
  30286. }
  30287. return nodeVarying;
  30288. }
  30289. /**
  30290. * Returns an instance of {@link NodeCode} for the given code node.
  30291. *
  30292. * @param {CodeNode} node - The code node.
  30293. * @param {String} type - The node type.
  30294. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30295. * @return {NodeCode} The node code.
  30296. */
  30297. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  30298. const nodeData = this.getDataFromNode( node );
  30299. let nodeCode = nodeData.code;
  30300. if ( nodeCode === undefined ) {
  30301. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  30302. const index = codes.length;
  30303. nodeCode = new NodeCode( 'nodeCode' + index, type );
  30304. codes.push( nodeCode );
  30305. nodeData.code = nodeCode;
  30306. }
  30307. return nodeCode;
  30308. }
  30309. /**
  30310. * Adds a code flow based on the code-block hierarchy.
  30311. * This is used so that code-blocks like If,Else create their variables locally if the Node
  30312. * is only used inside one of these conditionals in the current shader stage.
  30313. *
  30314. * @param {Node} node - The node to add.
  30315. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  30316. */
  30317. addFlowCodeHierarchy( node, nodeBlock ) {
  30318. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  30319. let needsFlowCode = true;
  30320. let nodeBlockHierarchy = nodeBlock;
  30321. while ( nodeBlockHierarchy ) {
  30322. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  30323. needsFlowCode = false;
  30324. break;
  30325. }
  30326. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  30327. }
  30328. if ( needsFlowCode ) {
  30329. for ( const flowCode of flowCodes ) {
  30330. this.addLineFlowCode( flowCode );
  30331. }
  30332. }
  30333. }
  30334. /**
  30335. * Add a inline-code to the current flow code-block.
  30336. *
  30337. * @param {Node} node - The node to add.
  30338. * @param {String} code - The code to add.
  30339. * @param {Node} nodeBlock - Current ConditionalNode
  30340. */
  30341. addLineFlowCodeBlock( node, code, nodeBlock ) {
  30342. const nodeData = this.getDataFromNode( node );
  30343. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  30344. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  30345. flowCodes.push( code );
  30346. codeBlock.set( nodeBlock, true );
  30347. }
  30348. /**
  30349. * Add a inline-code to the current flow.
  30350. *
  30351. * @param {String} code - The code to add.
  30352. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  30353. * @return {NodeBuilder} A reference to this node builder.
  30354. */
  30355. addLineFlowCode( code, node = null ) {
  30356. if ( code === '' ) return this;
  30357. if ( node !== null && this.context.nodeBlock ) {
  30358. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  30359. }
  30360. code = this.tab + code;
  30361. if ( ! /;\s*$/.test( code ) ) {
  30362. code = code + ';\n';
  30363. }
  30364. this.flow.code += code;
  30365. return this;
  30366. }
  30367. /**
  30368. * Adds a code to the current code flow.
  30369. *
  30370. * @param {String} code - Shader code.
  30371. * @return {NodeBuilder} A reference to this node builder.
  30372. */
  30373. addFlowCode( code ) {
  30374. this.flow.code += code;
  30375. return this;
  30376. }
  30377. /**
  30378. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  30379. * Typically used in codes with If,Else.
  30380. *
  30381. * @return {NodeBuilder} A reference to this node builder.
  30382. */
  30383. addFlowTab() {
  30384. this.tab += '\t';
  30385. return this;
  30386. }
  30387. /**
  30388. * Removes a tab.
  30389. *
  30390. * @return {NodeBuilder} A reference to this node builder.
  30391. */
  30392. removeFlowTab() {
  30393. this.tab = this.tab.slice( 0, - 1 );
  30394. return this;
  30395. }
  30396. /**
  30397. * Gets the current flow data based on a Node.
  30398. *
  30399. * @param {Node} node - Node that the flow was started.
  30400. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30401. * @return {Object} The flow data.
  30402. */
  30403. getFlowData( node/*, shaderStage*/ ) {
  30404. return this.flowsData.get( node );
  30405. }
  30406. /**
  30407. * Executes the node flow based on a root node to generate the final shader code.
  30408. *
  30409. * @param {Node} node - The node to execute.
  30410. * @return {Object} The code flow.
  30411. */
  30412. flowNode( node ) {
  30413. const output = node.getNodeType( this );
  30414. const flowData = this.flowChildNode( node, output );
  30415. this.flowsData.set( node, flowData );
  30416. return flowData;
  30417. }
  30418. /**
  30419. * Returns the native shader operator name for a given generic name.
  30420. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30421. *
  30422. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  30423. * @return {FunctionNode} The build function node.
  30424. */
  30425. buildFunctionNode( shaderNode ) {
  30426. const fn = new FunctionNode();
  30427. const previous = this.currentFunctionNode;
  30428. this.currentFunctionNode = fn;
  30429. fn.code = this.buildFunctionCode( shaderNode );
  30430. this.currentFunctionNode = previous;
  30431. return fn;
  30432. }
  30433. /**
  30434. * Generates a code flow based on a TSL function: Fn().
  30435. *
  30436. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  30437. * @return {Object}
  30438. */
  30439. flowShaderNode( shaderNode ) {
  30440. const layout = shaderNode.layout;
  30441. const inputs = {
  30442. [ Symbol.iterator ]() {
  30443. let index = 0;
  30444. const values = Object.values( this );
  30445. return {
  30446. next: () => ( {
  30447. value: values[ index ],
  30448. done: index ++ >= values.length
  30449. } )
  30450. };
  30451. }
  30452. };
  30453. for ( const input of layout.inputs ) {
  30454. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  30455. }
  30456. //
  30457. shaderNode.layout = null;
  30458. const callNode = shaderNode.call( inputs );
  30459. const flowData = this.flowStagesNode( callNode, layout.type );
  30460. shaderNode.layout = layout;
  30461. return flowData;
  30462. }
  30463. /**
  30464. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  30465. *
  30466. * @param {Node} node - The node to execute.
  30467. * @param {String?} output - Expected output type. For example 'vec3'.
  30468. * @return {Object}
  30469. */
  30470. flowStagesNode( node, output = null ) {
  30471. const previousFlow = this.flow;
  30472. const previousVars = this.vars;
  30473. const previousCache = this.cache;
  30474. const previousBuildStage = this.buildStage;
  30475. const previousStack = this.stack;
  30476. const flow = {
  30477. code: ''
  30478. };
  30479. this.flow = flow;
  30480. this.vars = {};
  30481. this.cache = new NodeCache();
  30482. this.stack = stack();
  30483. for ( const buildStage of defaultBuildStages ) {
  30484. this.setBuildStage( buildStage );
  30485. flow.result = node.build( this, output );
  30486. }
  30487. flow.vars = this.getVars( this.shaderStage );
  30488. this.flow = previousFlow;
  30489. this.vars = previousVars;
  30490. this.cache = previousCache;
  30491. this.stack = previousStack;
  30492. this.setBuildStage( previousBuildStage );
  30493. return flow;
  30494. }
  30495. /**
  30496. * Returns the native shader operator name for a given generic name.
  30497. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30498. *
  30499. * @abstract
  30500. * @param {String} op - The operator name to resolve.
  30501. * @return {String} The resolved operator name.
  30502. */
  30503. getFunctionOperator( /* op */ ) {
  30504. return null;
  30505. }
  30506. /**
  30507. * Generates a code flow based on a child Node.
  30508. *
  30509. * @param {Node} node - The node to execute.
  30510. * @param {String?} output - Expected output type. For example 'vec3'.
  30511. * @return {Object} The code flow.
  30512. */
  30513. flowChildNode( node, output = null ) {
  30514. const previousFlow = this.flow;
  30515. const flow = {
  30516. code: ''
  30517. };
  30518. this.flow = flow;
  30519. flow.result = node.build( this, output );
  30520. this.flow = previousFlow;
  30521. return flow;
  30522. }
  30523. /**
  30524. * Executes a flow of code in a different stage.
  30525. *
  30526. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  30527. * return the value in fragment-stage even if it is being executed in an input fragment.
  30528. *
  30529. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30530. * @param {Node} node - The node to execute.
  30531. * @param {String?} output - Expected output type. For example 'vec3'.
  30532. * @param {String?} propertyName - The property name to assign the result.
  30533. * @return {Object}
  30534. */
  30535. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  30536. const previousShaderStage = this.shaderStage;
  30537. this.setShaderStage( shaderStage );
  30538. const flowData = this.flowChildNode( node, output );
  30539. if ( propertyName !== null ) {
  30540. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  30541. }
  30542. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  30543. this.setShaderStage( previousShaderStage );
  30544. return flowData;
  30545. }
  30546. /**
  30547. * Returns an array holding all node attributes of this node builder.
  30548. *
  30549. * @return {Array<NodeAttribute>} The node attributes of this builder.
  30550. */
  30551. getAttributesArray() {
  30552. return this.attributes.concat( this.bufferAttributes );
  30553. }
  30554. /**
  30555. * Returns the attribute definitions as a shader string for the given shader stage.
  30556. *
  30557. * @abstract
  30558. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30559. * @return {String} The attribute code section.
  30560. */
  30561. getAttributes( /*shaderStage*/ ) {
  30562. console.warn( 'Abstract function.' );
  30563. }
  30564. /**
  30565. * Returns the varying definitions as a shader string for the given shader stage.
  30566. *
  30567. * @abstract
  30568. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30569. * @return {String} The varying code section.
  30570. */
  30571. getVaryings( /*shaderStage*/ ) {
  30572. console.warn( 'Abstract function.' );
  30573. }
  30574. /**
  30575. * Returns a single variable definition as a shader string for the given variable type and name.
  30576. *
  30577. * @param {String} type - The variable's type.
  30578. * @param {String} name - The variable's name.
  30579. * @return {String} The shader string.
  30580. */
  30581. getVar( type, name ) {
  30582. return `${ this.getType( type ) } ${ name }`;
  30583. }
  30584. /**
  30585. * Returns the variable definitions as a shader string for the given shader stage.
  30586. *
  30587. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30588. * @return {String} The variable code section.
  30589. */
  30590. getVars( shaderStage ) {
  30591. let snippet = '';
  30592. const vars = this.vars[ shaderStage ];
  30593. if ( vars !== undefined ) {
  30594. for ( const variable of vars ) {
  30595. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  30596. }
  30597. }
  30598. return snippet;
  30599. }
  30600. /**
  30601. * Returns the uniform definitions as a shader string for the given shader stage.
  30602. *
  30603. * @abstract
  30604. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30605. * @return {String} The uniform code section.
  30606. */
  30607. getUniforms( /*shaderStage*/ ) {
  30608. console.warn( 'Abstract function.' );
  30609. }
  30610. /**
  30611. * Returns the native code definitions as a shader string for the given shader stage.
  30612. *
  30613. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30614. * @return {String} The native code section.
  30615. */
  30616. getCodes( shaderStage ) {
  30617. const codes = this.codes[ shaderStage ];
  30618. let code = '';
  30619. if ( codes !== undefined ) {
  30620. for ( const nodeCode of codes ) {
  30621. code += nodeCode.code + '\n';
  30622. }
  30623. }
  30624. return code;
  30625. }
  30626. /**
  30627. * Returns the hash of this node builder.
  30628. *
  30629. * @return {String} The hash.
  30630. */
  30631. getHash() {
  30632. return this.vertexShader + this.fragmentShader + this.computeShader;
  30633. }
  30634. /**
  30635. * Sets the current shader stage.
  30636. *
  30637. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  30638. */
  30639. setShaderStage( shaderStage ) {
  30640. this.shaderStage = shaderStage;
  30641. }
  30642. /**
  30643. * Returns the current shader stage.
  30644. *
  30645. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  30646. */
  30647. getShaderStage() {
  30648. return this.shaderStage;
  30649. }
  30650. /**
  30651. * Sets the current build stage.
  30652. *
  30653. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  30654. */
  30655. setBuildStage( buildStage ) {
  30656. this.buildStage = buildStage;
  30657. }
  30658. /**
  30659. * Returns the current build stage.
  30660. *
  30661. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  30662. */
  30663. getBuildStage() {
  30664. return this.buildStage;
  30665. }
  30666. /**
  30667. * Controls the code build of the shader stages.
  30668. *
  30669. * @abstract
  30670. */
  30671. buildCode() {
  30672. console.warn( 'Abstract function.' );
  30673. }
  30674. /**
  30675. * Central build method which controls the build for the given object.
  30676. *
  30677. * @return {NodeBuilder} A reference to this node builder.
  30678. */
  30679. build() {
  30680. const { object, material, renderer } = this;
  30681. if ( material !== null ) {
  30682. let nodeMaterial = renderer.library.fromMaterial( material );
  30683. if ( nodeMaterial === null ) {
  30684. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  30685. nodeMaterial = new NodeMaterial();
  30686. }
  30687. nodeMaterial.build( this );
  30688. } else {
  30689. this.addFlow( 'compute', object );
  30690. }
  30691. // setup() -> stage 1: create possible new nodes and returns an output reference node
  30692. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  30693. // generate() -> stage 3: generate shader
  30694. for ( const buildStage of defaultBuildStages ) {
  30695. this.setBuildStage( buildStage );
  30696. if ( this.context.vertex && this.context.vertex.isNode ) {
  30697. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  30698. }
  30699. for ( const shaderStage of shaderStages ) {
  30700. this.setShaderStage( shaderStage );
  30701. const flowNodes = this.flowNodes[ shaderStage ];
  30702. for ( const node of flowNodes ) {
  30703. if ( buildStage === 'generate' ) {
  30704. this.flowNode( node );
  30705. } else {
  30706. node.build( this );
  30707. }
  30708. }
  30709. }
  30710. }
  30711. this.setBuildStage( null );
  30712. this.setShaderStage( null );
  30713. // stage 4: build code for a specific output
  30714. this.buildCode();
  30715. this.buildUpdateNodes();
  30716. return this;
  30717. }
  30718. /**
  30719. * Returns a uniform representation which is later used for UBO generation and rendering.
  30720. *
  30721. * @param {NodeUniform} uniformNode - The uniform node.
  30722. * @param {String} type - The requested type.
  30723. * @return {Uniform} The uniform.
  30724. */
  30725. getNodeUniform( uniformNode, type ) {
  30726. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  30727. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  30728. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  30729. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  30730. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  30731. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  30732. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  30733. throw new Error( `Uniform "${type}" not declared.` );
  30734. }
  30735. /**
  30736. * Formats the given shader snippet from a given type into another one. E.g.
  30737. * this method might be used to convert a simple float string `"1.0"` into a
  30738. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  30739. *
  30740. * @param {String} snippet - The shader snippet.
  30741. * @param {String} fromType - The source type.
  30742. * @param {String} toType - The target type.
  30743. * @return {String} The updated shader string.
  30744. */
  30745. format( snippet, fromType, toType ) {
  30746. fromType = this.getVectorType( fromType );
  30747. toType = this.getVectorType( toType );
  30748. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  30749. return snippet;
  30750. }
  30751. const fromTypeLength = this.getTypeLength( fromType );
  30752. const toTypeLength = this.getTypeLength( toType );
  30753. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  30754. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  30755. }
  30756. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  30757. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  30758. }
  30759. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  30760. // @TODO: ignore for now
  30761. return snippet;
  30762. }
  30763. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  30764. // @TODO: ignore for now
  30765. return snippet;
  30766. }
  30767. if ( fromTypeLength === toTypeLength ) {
  30768. return `${ this.getType( toType ) }( ${ snippet } )`;
  30769. }
  30770. if ( fromTypeLength > toTypeLength ) {
  30771. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  30772. }
  30773. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  30774. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  30775. }
  30776. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  30777. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  30778. }
  30779. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  30780. // convert a number value to vector type, e.g:
  30781. // vec3( 1u ) -> vec3( float( 1u ) )
  30782. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  30783. }
  30784. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  30785. }
  30786. /**
  30787. * Returns a signature with the engine's current revision.
  30788. *
  30789. * @return {String} The signature.
  30790. */
  30791. getSignature() {
  30792. return `// Three.js r${ REVISION } - Node System\n`;
  30793. }
  30794. // deprecated
  30795. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  30796. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  30797. }
  30798. }
  30799. /**
  30800. * Management class for updating nodes. The module tracks metrics like
  30801. * the elapsed time, delta time, the render and frame ID to correctly
  30802. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  30803. * and {@link Node#updateAfter} depending on the node's configuration.
  30804. */
  30805. class NodeFrame {
  30806. /**
  30807. * Constructs a new node fame.
  30808. */
  30809. constructor() {
  30810. /**
  30811. * The elapsed time in seconds.
  30812. *
  30813. * @type {Number}
  30814. * @default 0
  30815. */
  30816. this.time = 0;
  30817. /**
  30818. * The delta time in seconds.
  30819. *
  30820. * @type {Number}
  30821. * @default 0
  30822. */
  30823. this.deltaTime = 0;
  30824. /**
  30825. * The frame ID.
  30826. *
  30827. * @type {Number}
  30828. * @default 0
  30829. */
  30830. this.frameId = 0;
  30831. /**
  30832. * The render ID.
  30833. *
  30834. * @type {Number}
  30835. * @default 0
  30836. */
  30837. this.renderId = 0;
  30838. /**
  30839. * Used to control the {@link Node#update} call.
  30840. *
  30841. * @type {WeakMap<Node, Object>}
  30842. */
  30843. this.updateMap = new WeakMap();
  30844. /**
  30845. * Used to control the {@link Node#updateBefore} call.
  30846. *
  30847. * @type {WeakMap<Node, Object>}
  30848. */
  30849. this.updateBeforeMap = new WeakMap();
  30850. /**
  30851. * Used to control the {@link Node#updateAfter} call.
  30852. *
  30853. * @type {WeakMap<Node, Object>}
  30854. */
  30855. this.updateAfterMap = new WeakMap();
  30856. /**
  30857. * A reference to the current renderer.
  30858. *
  30859. * @type {Renderer?}
  30860. * @default null
  30861. */
  30862. this.renderer = null;
  30863. /**
  30864. * A reference to the current material.
  30865. *
  30866. * @type {Material?}
  30867. * @default null
  30868. */
  30869. this.material = null;
  30870. /**
  30871. * A reference to the current camera.
  30872. *
  30873. * @type {Camera?}
  30874. * @default null
  30875. */
  30876. this.camera = null;
  30877. /**
  30878. * A reference to the current 3D object.
  30879. *
  30880. * @type {Object3D?}
  30881. * @default null
  30882. */
  30883. this.object = null;
  30884. /**
  30885. * A reference to the current scene.
  30886. *
  30887. * @type {Scene?}
  30888. * @default null
  30889. */
  30890. this.scene = null;
  30891. }
  30892. /**
  30893. * Returns a dictionary for a given node and update map which
  30894. * is used to correctly call node update methods per frame or render.
  30895. *
  30896. * @private
  30897. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  30898. * @param {Node} nodeRef - The reference to the current node.
  30899. * @return {Object<String,WeakMap>} The dictionary.
  30900. */
  30901. _getMaps( referenceMap, nodeRef ) {
  30902. let maps = referenceMap.get( nodeRef );
  30903. if ( maps === undefined ) {
  30904. maps = {
  30905. renderMap: new WeakMap(),
  30906. frameMap: new WeakMap()
  30907. };
  30908. referenceMap.set( nodeRef, maps );
  30909. }
  30910. return maps;
  30911. }
  30912. /**
  30913. * This method executes the {@link Node#updateBefore} for the given node.
  30914. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  30915. * is only executed once per frame, render or object depending on the update
  30916. * type.
  30917. *
  30918. * @param {Node} node - The node that should be updated.
  30919. */
  30920. updateBeforeNode( node ) {
  30921. const updateType = node.getUpdateBeforeType();
  30922. const reference = node.updateReference( this );
  30923. if ( updateType === NodeUpdateType.FRAME ) {
  30924. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  30925. if ( frameMap.get( reference ) !== this.frameId ) {
  30926. if ( node.updateBefore( this ) !== false ) {
  30927. frameMap.set( reference, this.frameId );
  30928. }
  30929. }
  30930. } else if ( updateType === NodeUpdateType.RENDER ) {
  30931. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  30932. if ( renderMap.get( reference ) !== this.renderId ) {
  30933. if ( node.updateBefore( this ) !== false ) {
  30934. renderMap.set( reference, this.renderId );
  30935. }
  30936. }
  30937. } else if ( updateType === NodeUpdateType.OBJECT ) {
  30938. node.updateBefore( this );
  30939. }
  30940. }
  30941. /**
  30942. * This method executes the {@link Node#updateAfter} for the given node.
  30943. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  30944. * is only executed once per frame, render or object depending on the update
  30945. * type.
  30946. *
  30947. * @param {Node} node - The node that should be updated.
  30948. */
  30949. updateAfterNode( node ) {
  30950. const updateType = node.getUpdateAfterType();
  30951. const reference = node.updateReference( this );
  30952. if ( updateType === NodeUpdateType.FRAME ) {
  30953. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  30954. if ( frameMap.get( reference ) !== this.frameId ) {
  30955. if ( node.updateAfter( this ) !== false ) {
  30956. frameMap.set( reference, this.frameId );
  30957. }
  30958. }
  30959. } else if ( updateType === NodeUpdateType.RENDER ) {
  30960. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  30961. if ( renderMap.get( reference ) !== this.renderId ) {
  30962. if ( node.updateAfter( this ) !== false ) {
  30963. renderMap.set( reference, this.renderId );
  30964. }
  30965. }
  30966. } else if ( updateType === NodeUpdateType.OBJECT ) {
  30967. node.updateAfter( this );
  30968. }
  30969. }
  30970. /**
  30971. * This method executes the {@link Node#update} for the given node.
  30972. * It makes sure {@link Node#updateType} is honored meaning the update
  30973. * is only executed once per frame, render or object depending on the update
  30974. * type.
  30975. *
  30976. * @param {Node} node - The node that should be updated.
  30977. */
  30978. updateNode( node ) {
  30979. const updateType = node.getUpdateType();
  30980. const reference = node.updateReference( this );
  30981. if ( updateType === NodeUpdateType.FRAME ) {
  30982. const { frameMap } = this._getMaps( this.updateMap, reference );
  30983. if ( frameMap.get( reference ) !== this.frameId ) {
  30984. if ( node.update( this ) !== false ) {
  30985. frameMap.set( reference, this.frameId );
  30986. }
  30987. }
  30988. } else if ( updateType === NodeUpdateType.RENDER ) {
  30989. const { renderMap } = this._getMaps( this.updateMap, reference );
  30990. if ( renderMap.get( reference ) !== this.renderId ) {
  30991. if ( node.update( this ) !== false ) {
  30992. renderMap.set( reference, this.renderId );
  30993. }
  30994. }
  30995. } else if ( updateType === NodeUpdateType.OBJECT ) {
  30996. node.update( this );
  30997. }
  30998. }
  30999. /**
  31000. * Updates the internal state of the node frame. This method is
  31001. * called by the renderer in its internal animation loop.
  31002. */
  31003. update() {
  31004. this.frameId ++;
  31005. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31006. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31007. this.lastTime = performance.now();
  31008. this.time += this.deltaTime;
  31009. }
  31010. }
  31011. /**
  31012. * Describes the input of a {@link NodeFunction}.
  31013. */
  31014. class NodeFunctionInput {
  31015. /**
  31016. * Constructs a new node function input.
  31017. *
  31018. * @param {String} type - The input type.
  31019. * @param {String} name - The input name.
  31020. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  31021. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  31022. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  31023. */
  31024. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31025. /**
  31026. * The input type.
  31027. *
  31028. * @type {String}
  31029. */
  31030. this.type = type;
  31031. /**
  31032. * The input name.
  31033. *
  31034. * @type {String}
  31035. */
  31036. this.name = name;
  31037. /**
  31038. * If the input is an Array, count will be the length.
  31039. *
  31040. * @type {Number?}
  31041. * @default null
  31042. */
  31043. this.count = count;
  31044. /**
  31045. *The parameter qualifier (only relevant for GLSL).
  31046. *
  31047. * @type {('in'|'out'|'inout')}
  31048. * @default ''
  31049. */
  31050. this.qualifier = qualifier;
  31051. /**
  31052. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  31053. *
  31054. * @type {Boolean}
  31055. * @default false
  31056. */
  31057. this.isConst = isConst;
  31058. }
  31059. }
  31060. NodeFunctionInput.isNodeFunctionInput = true;
  31061. /**
  31062. * Module for representing directional lights as nodes.
  31063. *
  31064. * @augments AnalyticLightNode
  31065. */
  31066. class DirectionalLightNode extends AnalyticLightNode {
  31067. static get type() {
  31068. return 'DirectionalLightNode';
  31069. }
  31070. /**
  31071. * Constructs a new directional light node.
  31072. *
  31073. * @param {DirectionalLight?} [light=null] - The directional light source.
  31074. */
  31075. constructor( light = null ) {
  31076. super( light );
  31077. }
  31078. setup( builder ) {
  31079. super.setup( builder );
  31080. const lightingModel = builder.context.lightingModel;
  31081. const lightColor = this.colorNode;
  31082. const lightDirection = lightTargetDirection( this.light );
  31083. const reflectedLight = builder.context.reflectedLight;
  31084. lightingModel.direct( {
  31085. lightDirection,
  31086. lightColor,
  31087. reflectedLight
  31088. }, builder.stack, builder );
  31089. }
  31090. }
  31091. const _matrix41 = /*@__PURE__*/ new Matrix4();
  31092. const _matrix42 = /*@__PURE__*/ new Matrix4();
  31093. let _ltcLib = null;
  31094. /**
  31095. * Module for representing rect area lights as nodes.
  31096. *
  31097. * @augments AnalyticLightNode
  31098. */
  31099. class RectAreaLightNode extends AnalyticLightNode {
  31100. static get type() {
  31101. return 'RectAreaLightNode';
  31102. }
  31103. /**
  31104. * Constructs a new rect area light node.
  31105. *
  31106. * @param {RectAreaLight?} [light=null] - The rect area light source.
  31107. */
  31108. constructor( light = null ) {
  31109. super( light );
  31110. /**
  31111. * Uniform node representing the half height of the are light.
  31112. *
  31113. * @type {UniformNode<vec3>}
  31114. */
  31115. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  31116. /**
  31117. * Uniform node representing the half width of the are light.
  31118. *
  31119. * @type {UniformNode<vec3>}
  31120. */
  31121. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  31122. /**
  31123. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  31124. * relies on `viewMatrix` which might vary per render call.
  31125. *
  31126. * @type {String}
  31127. * @default 'render'
  31128. */
  31129. this.updateType = NodeUpdateType.RENDER;
  31130. }
  31131. /**
  31132. * Overwritten to updated rect area light specific uniforms.
  31133. *
  31134. * @param {NodeFrame} frame - A reference to the current node frame.
  31135. */
  31136. update( frame ) {
  31137. super.update( frame );
  31138. const { light } = this;
  31139. const viewMatrix = frame.camera.matrixWorldInverse;
  31140. _matrix42.identity();
  31141. _matrix41.copy( light.matrixWorld );
  31142. _matrix41.premultiply( viewMatrix );
  31143. _matrix42.extractRotation( _matrix41 );
  31144. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31145. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31146. this.halfWidth.value.applyMatrix4( _matrix42 );
  31147. this.halfHeight.value.applyMatrix4( _matrix42 );
  31148. }
  31149. setup( builder ) {
  31150. super.setup( builder );
  31151. let ltc_1, ltc_2;
  31152. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31153. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  31154. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  31155. } else {
  31156. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  31157. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  31158. }
  31159. const { colorNode, light } = this;
  31160. const lightingModel = builder.context.lightingModel;
  31161. const lightPosition = lightViewPosition( light );
  31162. const reflectedLight = builder.context.reflectedLight;
  31163. lightingModel.directRectArea( {
  31164. lightColor: colorNode,
  31165. lightPosition,
  31166. halfWidth: this.halfWidth,
  31167. halfHeight: this.halfHeight,
  31168. reflectedLight,
  31169. ltc_1,
  31170. ltc_2
  31171. }, builder.stack, builder );
  31172. }
  31173. /**
  31174. * Used to configure the internal BRDF approximation texture data.
  31175. *
  31176. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  31177. */
  31178. static setLTC( ltc ) {
  31179. _ltcLib = ltc;
  31180. }
  31181. }
  31182. /**
  31183. * Module for representing spot lights as nodes.
  31184. *
  31185. * @augments AnalyticLightNode
  31186. */
  31187. class SpotLightNode extends AnalyticLightNode {
  31188. static get type() {
  31189. return 'SpotLightNode';
  31190. }
  31191. /**
  31192. * Constructs a new spot light node.
  31193. *
  31194. * @param {SpotLight?} [light=null] - The spot light source.
  31195. */
  31196. constructor( light = null ) {
  31197. super( light );
  31198. /**
  31199. * Uniform node representing the cone cosine.
  31200. *
  31201. * @type {UniformNode<float>}
  31202. */
  31203. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  31204. /**
  31205. * Uniform node representing the penumbra cosine.
  31206. *
  31207. * @type {UniformNode<float>}
  31208. */
  31209. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  31210. /**
  31211. * Uniform node representing the cutoff distance.
  31212. *
  31213. * @type {UniformNode<float>}
  31214. */
  31215. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31216. /**
  31217. * Uniform node representing the decay exponent.
  31218. *
  31219. * @type {UniformNode<float>}
  31220. */
  31221. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  31222. }
  31223. /**
  31224. * Overwritten to updated spot light specific uniforms.
  31225. *
  31226. * @param {NodeFrame} frame - A reference to the current node frame.
  31227. */
  31228. update( frame ) {
  31229. super.update( frame );
  31230. const { light } = this;
  31231. this.coneCosNode.value = Math.cos( light.angle );
  31232. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31233. this.cutoffDistanceNode.value = light.distance;
  31234. this.decayExponentNode.value = light.decay;
  31235. }
  31236. /**
  31237. * Computes the spot attenuation for the given angle.
  31238. *
  31239. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31240. * @return {Node<float>} The spot attenuation.
  31241. */
  31242. getSpotAttenuation( angleCosine ) {
  31243. const { coneCosNode, penumbraCosNode } = this;
  31244. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31245. }
  31246. setup( builder ) {
  31247. super.setup( builder );
  31248. const lightingModel = builder.context.lightingModel;
  31249. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31250. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31251. const lightDirection = lVector.normalize();
  31252. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31253. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31254. const lightDistance = lVector.length();
  31255. const lightAttenuation = getDistanceAttenuation( {
  31256. lightDistance,
  31257. cutoffDistance: cutoffDistanceNode,
  31258. decayExponent: decayExponentNode
  31259. } );
  31260. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31261. if ( light.map ) {
  31262. const spotLightCoord = lightProjectionUV( light );
  31263. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  31264. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  31265. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  31266. }
  31267. const reflectedLight = builder.context.reflectedLight;
  31268. lightingModel.direct( {
  31269. lightDirection,
  31270. lightColor,
  31271. reflectedLight
  31272. }, builder.stack, builder );
  31273. }
  31274. }
  31275. /**
  31276. * An IES version of the default spot light node.
  31277. *
  31278. * @augments SpotLightNode
  31279. */
  31280. class IESSpotLightNode extends SpotLightNode {
  31281. static get type() {
  31282. return 'IESSpotLightNode';
  31283. }
  31284. /**
  31285. * Overwrites the default implementation to compute an IES conform spot attenuation.
  31286. *
  31287. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31288. * @return {Node<float>} The spot attenuation.
  31289. */
  31290. getSpotAttenuation( angleCosine ) {
  31291. const iesMap = this.light.iesMap;
  31292. let spotAttenuation = null;
  31293. if ( iesMap && iesMap.isTexture === true ) {
  31294. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  31295. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  31296. } else {
  31297. spotAttenuation = super.getSpotAttenuation( angleCosine );
  31298. }
  31299. return spotAttenuation;
  31300. }
  31301. }
  31302. /**
  31303. * Module for representing ambient lights as nodes.
  31304. *
  31305. * @augments AnalyticLightNode
  31306. */
  31307. class AmbientLightNode extends AnalyticLightNode {
  31308. static get type() {
  31309. return 'AmbientLightNode';
  31310. }
  31311. /**
  31312. * Constructs a new ambient light node.
  31313. *
  31314. * @param {AmbientLight?} [light=null] - The ambient light source.
  31315. */
  31316. constructor( light = null ) {
  31317. super( light );
  31318. }
  31319. setup( { context } ) {
  31320. context.irradiance.addAssign( this.colorNode );
  31321. }
  31322. }
  31323. /**
  31324. * Module for representing hemisphere lights as nodes.
  31325. *
  31326. * @augments AnalyticLightNode
  31327. */
  31328. class HemisphereLightNode extends AnalyticLightNode {
  31329. static get type() {
  31330. return 'HemisphereLightNode';
  31331. }
  31332. /**
  31333. * Constructs a new hemisphere light node.
  31334. *
  31335. * @param {HemisphereLight?} [light=null] - The hemisphere light source.
  31336. */
  31337. constructor( light = null ) {
  31338. super( light );
  31339. /**
  31340. * Uniform node representing the light's position.
  31341. *
  31342. * @type {UniformNode<vec3>}
  31343. */
  31344. this.lightPositionNode = lightPosition( light );
  31345. /**
  31346. * A node representing the light's direction.
  31347. *
  31348. * @type {Node<vec3>}
  31349. */
  31350. this.lightDirectionNode = this.lightPositionNode.normalize();
  31351. /**
  31352. * Uniform node representing the light's ground color.
  31353. *
  31354. * @type {UniformNode<vec3>}
  31355. */
  31356. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  31357. }
  31358. /**
  31359. * Overwritten to updated hemisphere light specific uniforms.
  31360. *
  31361. * @param {NodeFrame} frame - A reference to the current node frame.
  31362. */
  31363. update( frame ) {
  31364. const { light } = this;
  31365. super.update( frame );
  31366. this.lightPositionNode.object3d = light;
  31367. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  31368. }
  31369. setup( builder ) {
  31370. const { colorNode, groundColorNode, lightDirectionNode } = this;
  31371. const dotNL = normalView.dot( lightDirectionNode );
  31372. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  31373. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  31374. builder.context.irradiance.addAssign( irradiance );
  31375. }
  31376. }
  31377. /**
  31378. * Module for representing light probes as nodes.
  31379. *
  31380. * @augments AnalyticLightNode
  31381. */
  31382. class LightProbeNode extends AnalyticLightNode {
  31383. static get type() {
  31384. return 'LightProbeNode';
  31385. }
  31386. /**
  31387. * Constructs a new light probe node.
  31388. *
  31389. * @param {LightProbe?} [light=null] - The light probe.
  31390. */
  31391. constructor( light = null ) {
  31392. super( light );
  31393. const array = [];
  31394. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  31395. /**
  31396. * Light probe represented as a uniform of spherical harmonics.
  31397. *
  31398. * @type {UniformArrayNode}
  31399. */
  31400. this.lightProbe = uniformArray( array );
  31401. }
  31402. /**
  31403. * Overwritten to updated light probe specific uniforms.
  31404. *
  31405. * @param {NodeFrame} frame - A reference to the current node frame.
  31406. */
  31407. update( frame ) {
  31408. const { light } = this;
  31409. super.update( frame );
  31410. //
  31411. for ( let i = 0; i < 9; i ++ ) {
  31412. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  31413. }
  31414. }
  31415. setup( builder ) {
  31416. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  31417. builder.context.irradiance.addAssign( irradiance );
  31418. }
  31419. }
  31420. /**
  31421. * Base class for node parsers. A derived parser must be implemented
  31422. * for each supported native shader language.
  31423. */
  31424. class NodeParser {
  31425. /**
  31426. * The method parses the given native code an returns a node function.
  31427. *
  31428. * @abstract
  31429. * @param {String} source - The native shader code.
  31430. * @return {NodeFunction} A node function.
  31431. */
  31432. parseFunction( /*source*/ ) {
  31433. console.warn( 'Abstract function.' );
  31434. }
  31435. }
  31436. /**
  31437. * Base class for node functions. A derived module must be implemented
  31438. * for each supported native shader language. Similar to other `Node*` modules,
  31439. * this class is only relevant during the building process and not used
  31440. * in user-level code.
  31441. */
  31442. class NodeFunction {
  31443. /**
  31444. * Constructs a new node function.
  31445. *
  31446. * @param {String} type - The node type. This type is the return type of the node function.
  31447. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  31448. * @param {String} [name=''] - The function's name.
  31449. * @param {String} [precision=''] - The precision qualifier.
  31450. */
  31451. constructor( type, inputs, name = '', precision = '' ) {
  31452. /**
  31453. * The node type. This type is the return type of the node function.
  31454. *
  31455. * @type {String}
  31456. */
  31457. this.type = type;
  31458. /**
  31459. * The function's inputs.
  31460. *
  31461. * @type {Array<NodeFunctionInput>}
  31462. */
  31463. this.inputs = inputs;
  31464. /**
  31465. * The name of the uniform.
  31466. *
  31467. * @type {String}
  31468. * @default ''
  31469. */
  31470. this.name = name;
  31471. /**
  31472. * The precision qualifier.
  31473. *
  31474. * @type {String}
  31475. * @default ''
  31476. */
  31477. this.precision = precision;
  31478. }
  31479. /**
  31480. * This method returns the native code of the node function.
  31481. *
  31482. * @abstract
  31483. * @param {String} name - The function's name.
  31484. * @return {String} A shader code.
  31485. */
  31486. getCode( /*name = this.name*/ ) {
  31487. console.warn( 'Abstract function.' );
  31488. }
  31489. }
  31490. NodeFunction.isNodeFunction = true;
  31491. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  31492. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  31493. const pragmaMain = '#pragma main';
  31494. const parse$1 = ( source ) => {
  31495. source = source.trim();
  31496. const pragmaMainIndex = source.indexOf( pragmaMain );
  31497. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  31498. const declaration = mainCode.match( declarationRegexp$1 );
  31499. if ( declaration !== null && declaration.length === 5 ) {
  31500. // tokenizer
  31501. const inputsCode = declaration[ 4 ];
  31502. const propsMatches = [];
  31503. let nameMatch = null;
  31504. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  31505. propsMatches.push( nameMatch );
  31506. }
  31507. // parser
  31508. const inputs = [];
  31509. let i = 0;
  31510. while ( i < propsMatches.length ) {
  31511. const isConst = propsMatches[ i ][ 0 ] === 'const';
  31512. if ( isConst === true ) {
  31513. i ++;
  31514. }
  31515. let qualifier = propsMatches[ i ][ 0 ];
  31516. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  31517. i ++;
  31518. } else {
  31519. qualifier = '';
  31520. }
  31521. const type = propsMatches[ i ++ ][ 0 ];
  31522. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  31523. if ( Number.isNaN( count ) === false ) i ++;
  31524. else count = null;
  31525. const name = propsMatches[ i ++ ][ 0 ];
  31526. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  31527. }
  31528. //
  31529. const blockCode = mainCode.substring( declaration[ 0 ].length );
  31530. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  31531. const type = declaration[ 2 ];
  31532. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  31533. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  31534. return {
  31535. type,
  31536. inputs,
  31537. name,
  31538. precision,
  31539. inputsCode,
  31540. blockCode,
  31541. headerCode
  31542. };
  31543. } else {
  31544. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  31545. }
  31546. };
  31547. /**
  31548. * This class represents a GLSL node function.
  31549. *
  31550. * @augments NodeFunction
  31551. */
  31552. class GLSLNodeFunction extends NodeFunction {
  31553. /**
  31554. * Constructs a new GLSL node function.
  31555. *
  31556. * @param {String} source - The GLSL source.
  31557. */
  31558. constructor( source ) {
  31559. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  31560. super( type, inputs, name, precision );
  31561. this.inputsCode = inputsCode;
  31562. this.blockCode = blockCode;
  31563. this.headerCode = headerCode;
  31564. }
  31565. /**
  31566. * This method returns the GLSL code of the node function.
  31567. *
  31568. * @param {String} [name=this.name] - The function's name.
  31569. * @return {String} The shader code.
  31570. */
  31571. getCode( name = this.name ) {
  31572. let code;
  31573. const blockCode = this.blockCode;
  31574. if ( blockCode !== '' ) {
  31575. const { type, inputsCode, headerCode, precision } = this;
  31576. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  31577. if ( precision !== '' ) {
  31578. declarationCode = `${ precision } ${ declarationCode }`;
  31579. }
  31580. code = headerCode + declarationCode + blockCode;
  31581. } else {
  31582. // interface function
  31583. code = '';
  31584. }
  31585. return code;
  31586. }
  31587. }
  31588. /**
  31589. * A GLSL node parser.
  31590. *
  31591. * @augments NodeParser
  31592. */
  31593. class GLSLNodeParser extends NodeParser {
  31594. /**
  31595. * The method parses the given GLSL code an returns a node function.
  31596. *
  31597. * @param {String} source - The GLSL code.
  31598. * @return {GLSLNodeFunction} A node function.
  31599. */
  31600. parseFunction( source ) {
  31601. return new GLSLNodeFunction( source );
  31602. }
  31603. }
  31604. const _outputNodeMap = new WeakMap();
  31605. /**
  31606. * This renderer module manages node-related objects and is the
  31607. * primary interface between the renderer and the node system.
  31608. *
  31609. * @private
  31610. * @augments DataMap
  31611. */
  31612. class Nodes extends DataMap {
  31613. /**
  31614. * Constructs a new nodes management component.
  31615. *
  31616. * @param {Renderer} renderer - The renderer.
  31617. * @param {Backend} backend - The renderer's backend.
  31618. */
  31619. constructor( renderer, backend ) {
  31620. super();
  31621. /**
  31622. * The renderer.
  31623. *
  31624. * @type {Renderer}
  31625. */
  31626. this.renderer = renderer;
  31627. /**
  31628. * The renderer's backend.
  31629. *
  31630. * @type {Backend}
  31631. */
  31632. this.backend = backend;
  31633. /**
  31634. * The node frame.
  31635. *
  31636. * @type {Renderer}
  31637. */
  31638. this.nodeFrame = new NodeFrame();
  31639. /**
  31640. * A cache for managing node builder states.
  31641. *
  31642. * @type {Map<Number,NodeBuilderState>}
  31643. */
  31644. this.nodeBuilderCache = new Map();
  31645. /**
  31646. * A cache for managing data cache key data.
  31647. *
  31648. * @type {ChainMap}
  31649. */
  31650. this.callHashCache = new ChainMap();
  31651. /**
  31652. * A cache for managing node uniforms group data.
  31653. *
  31654. * @type {ChainMap}
  31655. */
  31656. this.groupsData = new ChainMap();
  31657. /**
  31658. * A cache for managing node objects of
  31659. * scene properties like fog or environments.
  31660. *
  31661. * @type {Object<String,WeakMap>}
  31662. */
  31663. this.cacheLib = {};
  31664. }
  31665. /**
  31666. * Returns `true` if the given node uniforms group must be updated or not.
  31667. *
  31668. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  31669. * @return {Boolean} Whether the node uniforms group requires an update or not.
  31670. */
  31671. updateGroup( nodeUniformsGroup ) {
  31672. const groupNode = nodeUniformsGroup.groupNode;
  31673. const name = groupNode.name;
  31674. // objectGroup is always updated
  31675. if ( name === objectGroup.name ) return true;
  31676. // renderGroup is updated once per render/compute call
  31677. if ( name === renderGroup.name ) {
  31678. const uniformsGroupData = this.get( nodeUniformsGroup );
  31679. const renderId = this.nodeFrame.renderId;
  31680. if ( uniformsGroupData.renderId !== renderId ) {
  31681. uniformsGroupData.renderId = renderId;
  31682. return true;
  31683. }
  31684. return false;
  31685. }
  31686. // frameGroup is updated once per frame
  31687. if ( name === frameGroup.name ) {
  31688. const uniformsGroupData = this.get( nodeUniformsGroup );
  31689. const frameId = this.nodeFrame.frameId;
  31690. if ( uniformsGroupData.frameId !== frameId ) {
  31691. uniformsGroupData.frameId = frameId;
  31692. return true;
  31693. }
  31694. return false;
  31695. }
  31696. // other groups are updated just when groupNode.needsUpdate is true
  31697. const groupChain = [ groupNode, nodeUniformsGroup ];
  31698. let groupData = this.groupsData.get( groupChain );
  31699. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  31700. if ( groupData.version !== groupNode.version ) {
  31701. groupData.version = groupNode.version;
  31702. return true;
  31703. }
  31704. return false;
  31705. }
  31706. /**
  31707. * Returns the cache key for the given render object.
  31708. *
  31709. * @param {RenderObject} renderObject - The render object.
  31710. * @return {Number} The cache key.
  31711. */
  31712. getForRenderCacheKey( renderObject ) {
  31713. return renderObject.initialCacheKey;
  31714. }
  31715. /**
  31716. * Returns a node builder state for the given render object.
  31717. *
  31718. * @param {RenderObject} renderObject - The render object.
  31719. * @return {NodeBuilderState} The node builder state.
  31720. */
  31721. getForRender( renderObject ) {
  31722. const renderObjectData = this.get( renderObject );
  31723. let nodeBuilderState = renderObjectData.nodeBuilderState;
  31724. if ( nodeBuilderState === undefined ) {
  31725. const { nodeBuilderCache } = this;
  31726. const cacheKey = this.getForRenderCacheKey( renderObject );
  31727. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  31728. if ( nodeBuilderState === undefined ) {
  31729. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  31730. nodeBuilder.scene = renderObject.scene;
  31731. nodeBuilder.material = renderObject.material;
  31732. nodeBuilder.camera = renderObject.camera;
  31733. nodeBuilder.context.material = renderObject.material;
  31734. nodeBuilder.lightsNode = renderObject.lightsNode;
  31735. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  31736. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  31737. nodeBuilder.clippingContext = renderObject.clippingContext;
  31738. nodeBuilder.build();
  31739. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  31740. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  31741. }
  31742. nodeBuilderState.usedTimes ++;
  31743. renderObjectData.nodeBuilderState = nodeBuilderState;
  31744. }
  31745. return nodeBuilderState;
  31746. }
  31747. /**
  31748. * Deletes the given object from the internal data map
  31749. *
  31750. * @param {Any} object - The object to delete.
  31751. * @return {Object?} The deleted dictionary.
  31752. */
  31753. delete( object ) {
  31754. if ( object.isRenderObject ) {
  31755. const nodeBuilderState = this.get( object ).nodeBuilderState;
  31756. nodeBuilderState.usedTimes --;
  31757. if ( nodeBuilderState.usedTimes === 0 ) {
  31758. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  31759. }
  31760. }
  31761. return super.delete( object );
  31762. }
  31763. /**
  31764. * Returns a node builder state for the given compute node.
  31765. *
  31766. * @param {Node} computeNode - The compute node.
  31767. * @return {NodeBuilderState} The node builder state.
  31768. */
  31769. getForCompute( computeNode ) {
  31770. const computeData = this.get( computeNode );
  31771. let nodeBuilderState = computeData.nodeBuilderState;
  31772. if ( nodeBuilderState === undefined ) {
  31773. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  31774. nodeBuilder.build();
  31775. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  31776. computeData.nodeBuilderState = nodeBuilderState;
  31777. }
  31778. return nodeBuilderState;
  31779. }
  31780. /**
  31781. * Creates a node builder state for the given node builder.
  31782. *
  31783. * @private
  31784. * @param {NodeBuilder} nodeBuilder - The node builder.
  31785. * @return {NodeBuilderState} The node builder state.
  31786. */
  31787. _createNodeBuilderState( nodeBuilder ) {
  31788. return new NodeBuilderState(
  31789. nodeBuilder.vertexShader,
  31790. nodeBuilder.fragmentShader,
  31791. nodeBuilder.computeShader,
  31792. nodeBuilder.getAttributesArray(),
  31793. nodeBuilder.getBindings(),
  31794. nodeBuilder.updateNodes,
  31795. nodeBuilder.updateBeforeNodes,
  31796. nodeBuilder.updateAfterNodes,
  31797. nodeBuilder.monitor,
  31798. nodeBuilder.transforms
  31799. );
  31800. }
  31801. /**
  31802. * Returns an environment node for the current configured
  31803. * scene environment.
  31804. *
  31805. * @param {Scene} scene - The scene.
  31806. * @return {Node} A node representing the current scene environment.
  31807. */
  31808. getEnvironmentNode( scene ) {
  31809. this.updateEnvironment( scene );
  31810. let environmentNode = null;
  31811. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  31812. environmentNode = scene.environmentNode;
  31813. } else {
  31814. const sceneData = this.get( scene );
  31815. if ( sceneData.environmentNode ) {
  31816. environmentNode = sceneData.environmentNode;
  31817. }
  31818. }
  31819. return environmentNode;
  31820. }
  31821. /**
  31822. * Returns a background node for the current configured
  31823. * scene background.
  31824. *
  31825. * @param {Scene} scene - The scene.
  31826. * @return {Node} A node representing the current scene background.
  31827. */
  31828. getBackgroundNode( scene ) {
  31829. this.updateBackground( scene );
  31830. let backgroundNode = null;
  31831. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  31832. backgroundNode = scene.backgroundNode;
  31833. } else {
  31834. const sceneData = this.get( scene );
  31835. if ( sceneData.backgroundNode ) {
  31836. backgroundNode = sceneData.backgroundNode;
  31837. }
  31838. }
  31839. return backgroundNode;
  31840. }
  31841. /**
  31842. * Returns a fog node for the current configured scene fog.
  31843. *
  31844. * @param {Scene} scene - The scene.
  31845. * @return {Node} A node representing the current scene fog.
  31846. */
  31847. getFogNode( scene ) {
  31848. this.updateFog( scene );
  31849. return scene.fogNode || this.get( scene ).fogNode || null;
  31850. }
  31851. /**
  31852. * Returns a cache key for the given scene and lights node.
  31853. * This key is used by `RenderObject` as a part of the dynamic
  31854. * cache key (a key that must be checked every time the render
  31855. * objects is drawn).
  31856. *
  31857. * @param {Scene} scene - The scene.
  31858. * @param {LightsNode} lightsNode - The lights node.
  31859. * @return {Number} The cache key.
  31860. */
  31861. getCacheKey( scene, lightsNode ) {
  31862. const chain = [ scene, lightsNode ];
  31863. const callId = this.renderer.info.calls;
  31864. let cacheKeyData = this.callHashCache.get( chain );
  31865. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  31866. const environmentNode = this.getEnvironmentNode( scene );
  31867. const fogNode = this.getFogNode( scene );
  31868. const values = [];
  31869. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  31870. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  31871. if ( fogNode ) values.push( fogNode.getCacheKey() );
  31872. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  31873. cacheKeyData = {
  31874. callId,
  31875. cacheKey: hashArray( values )
  31876. };
  31877. this.callHashCache.set( chain, cacheKeyData );
  31878. }
  31879. return cacheKeyData.cacheKey;
  31880. }
  31881. /**
  31882. * A boolean that indicates whether tone mapping should be enabled
  31883. * or not.
  31884. *
  31885. * @type {Boolean}
  31886. */
  31887. get isToneMappingState() {
  31888. return this.renderer.getRenderTarget() ? false : true;
  31889. }
  31890. /**
  31891. * If a scene background is configured, this method makes sure to
  31892. * represent the background with a corresponding node-based implementation.
  31893. *
  31894. * @param {Scene} scene - The scene.
  31895. */
  31896. updateBackground( scene ) {
  31897. const sceneData = this.get( scene );
  31898. const background = scene.background;
  31899. if ( background ) {
  31900. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  31901. if ( sceneData.background !== background || forceUpdate ) {
  31902. const backgroundNode = this.getCacheNode( 'background', background, () => {
  31903. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  31904. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  31905. return pmremTexture( background );
  31906. } else {
  31907. let envMap;
  31908. if ( background.isCubeTexture === true ) {
  31909. envMap = cubeTexture( background );
  31910. } else {
  31911. envMap = texture( background );
  31912. }
  31913. return cubeMapNode( envMap );
  31914. }
  31915. } else if ( background.isTexture === true ) {
  31916. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  31917. } else if ( background.isColor !== true ) {
  31918. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  31919. }
  31920. }, forceUpdate );
  31921. sceneData.backgroundNode = backgroundNode;
  31922. sceneData.background = background;
  31923. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  31924. }
  31925. } else if ( sceneData.backgroundNode ) {
  31926. delete sceneData.backgroundNode;
  31927. delete sceneData.background;
  31928. }
  31929. }
  31930. /**
  31931. * This method is part of the caching of nodes which are used to represents the
  31932. * scene's background, fog or environment.
  31933. *
  31934. * @param {String} type - The type of object to cache.
  31935. * @param {Object} object - The object.
  31936. * @param {Function} callback - A callback that produces a node representation for the given object.
  31937. * @param {Boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  31938. * @return {Node} The node representation.
  31939. */
  31940. getCacheNode( type, object, callback, forceUpdate = false ) {
  31941. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  31942. let node = nodeCache.get( object );
  31943. if ( node === undefined || forceUpdate ) {
  31944. node = callback();
  31945. nodeCache.set( object, node );
  31946. }
  31947. return node;
  31948. }
  31949. /**
  31950. * If a scene fog is configured, this method makes sure to
  31951. * represent the fog with a corresponding node-based implementation.
  31952. *
  31953. * @param {Scene} scene - The scene.
  31954. */
  31955. updateFog( scene ) {
  31956. const sceneData = this.get( scene );
  31957. const sceneFog = scene.fog;
  31958. if ( sceneFog ) {
  31959. if ( sceneData.fog !== sceneFog ) {
  31960. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  31961. if ( sceneFog.isFogExp2 ) {
  31962. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  31963. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  31964. return fog( color, densityFogFactor( density ) );
  31965. } else if ( sceneFog.isFog ) {
  31966. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  31967. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  31968. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  31969. return fog( color, rangeFogFactor( near, far ) );
  31970. } else {
  31971. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  31972. }
  31973. } );
  31974. sceneData.fogNode = fogNode;
  31975. sceneData.fog = sceneFog;
  31976. }
  31977. } else {
  31978. delete sceneData.fogNode;
  31979. delete sceneData.fog;
  31980. }
  31981. }
  31982. /**
  31983. * If a scene environment is configured, this method makes sure to
  31984. * represent the environment with a corresponding node-based implementation.
  31985. *
  31986. * @param {Scene} scene - The scene.
  31987. */
  31988. updateEnvironment( scene ) {
  31989. const sceneData = this.get( scene );
  31990. const environment = scene.environment;
  31991. if ( environment ) {
  31992. if ( sceneData.environment !== environment ) {
  31993. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  31994. if ( environment.isCubeTexture === true ) {
  31995. return cubeTexture( environment );
  31996. } else if ( environment.isTexture === true ) {
  31997. return texture( environment );
  31998. } else {
  31999. console.error( 'Nodes: Unsupported environment configuration.', environment );
  32000. }
  32001. } );
  32002. sceneData.environmentNode = environmentNode;
  32003. sceneData.environment = environment;
  32004. }
  32005. } else if ( sceneData.environmentNode ) {
  32006. delete sceneData.environmentNode;
  32007. delete sceneData.environment;
  32008. }
  32009. }
  32010. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  32011. const nodeFrame = this.nodeFrame;
  32012. nodeFrame.renderer = renderer;
  32013. nodeFrame.scene = scene;
  32014. nodeFrame.object = object;
  32015. nodeFrame.camera = camera;
  32016. nodeFrame.material = material;
  32017. return nodeFrame;
  32018. }
  32019. getNodeFrameForRender( renderObject ) {
  32020. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  32021. }
  32022. /**
  32023. * Returns the current output cache key.
  32024. *
  32025. * @return {String} The output cache key.
  32026. */
  32027. getOutputCacheKey() {
  32028. const renderer = this.renderer;
  32029. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  32030. }
  32031. /**
  32032. * Checks if the output configuration (tone mapping and color space) for
  32033. * the given target has changed.
  32034. *
  32035. * @param {Texture} outputTarget - The output target.
  32036. * @return {Boolean} Whether the output configuration has changed or not.
  32037. */
  32038. hasOutputChange( outputTarget ) {
  32039. const cacheKey = _outputNodeMap.get( outputTarget );
  32040. return cacheKey !== this.getOutputCacheKey();
  32041. }
  32042. /**
  32043. * Returns a node that represents the output configuration (tone mapping and
  32044. * color space) for the current target.
  32045. *
  32046. * @param {Texture} outputTarget - The output target.
  32047. * @return {Node} The output node.
  32048. */
  32049. getOutputNode( outputTarget ) {
  32050. const renderer = this.renderer;
  32051. const cacheKey = this.getOutputCacheKey();
  32052. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  32053. _outputNodeMap.set( outputTarget, cacheKey );
  32054. return output;
  32055. }
  32056. /**
  32057. * Triggers the call of `updateBefore()` methods
  32058. * for all nodes of the given render object.
  32059. *
  32060. * @param {RenderObject} renderObject - The render object.
  32061. */
  32062. updateBefore( renderObject ) {
  32063. const nodeBuilder = renderObject.getNodeBuilderState();
  32064. for ( const node of nodeBuilder.updateBeforeNodes ) {
  32065. // update frame state for each node
  32066. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  32067. }
  32068. }
  32069. /**
  32070. * Triggers the call of `updateAfter()` methods
  32071. * for all nodes of the given render object.
  32072. *
  32073. * @param {RenderObject} renderObject - The render object.
  32074. */
  32075. updateAfter( renderObject ) {
  32076. const nodeBuilder = renderObject.getNodeBuilderState();
  32077. for ( const node of nodeBuilder.updateAfterNodes ) {
  32078. // update frame state for each node
  32079. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  32080. }
  32081. }
  32082. /**
  32083. * Triggers the call of `update()` methods
  32084. * for all nodes of the given compute node.
  32085. *
  32086. * @param {Node} computeNode - The compute node.
  32087. */
  32088. updateForCompute( computeNode ) {
  32089. const nodeFrame = this.getNodeFrame();
  32090. const nodeBuilder = this.getForCompute( computeNode );
  32091. for ( const node of nodeBuilder.updateNodes ) {
  32092. nodeFrame.updateNode( node );
  32093. }
  32094. }
  32095. /**
  32096. * Triggers the call of `update()` methods
  32097. * for all nodes of the given compute node.
  32098. *
  32099. * @param {RenderObject} renderObject - The render object.
  32100. */
  32101. updateForRender( renderObject ) {
  32102. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32103. const nodeBuilder = renderObject.getNodeBuilderState();
  32104. for ( const node of nodeBuilder.updateNodes ) {
  32105. nodeFrame.updateNode( node );
  32106. }
  32107. }
  32108. /**
  32109. * Returns `true` if the given render object requires a refresh.
  32110. *
  32111. * @param {RenderObject} renderObject - The render object.
  32112. * @return {Boolean} Whether the given render object requires a refresh or not.
  32113. */
  32114. needsRefresh( renderObject ) {
  32115. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32116. const monitor = renderObject.getMonitor();
  32117. return monitor.needsRefresh( renderObject, nodeFrame );
  32118. }
  32119. /**
  32120. * Frees the intenral resources.
  32121. */
  32122. dispose() {
  32123. super.dispose();
  32124. this.nodeFrame = new NodeFrame();
  32125. this.nodeBuilderCache = new Map();
  32126. this.cacheLib = {};
  32127. }
  32128. }
  32129. const _plane = /*@__PURE__*/ new Plane();
  32130. /**
  32131. * Represents the state that is used to perform clipping via clipping planes.
  32132. * There is a default clipping context for each render context. When the
  32133. * scene holds instances of `ClippingGroup`, there will be a context for each
  32134. * group.
  32135. *
  32136. * @private
  32137. */
  32138. class ClippingContext {
  32139. /**
  32140. * Constructs a new clipping context.
  32141. *
  32142. * @param {ClippingContext?} [parentContext=null] - A reference to the parent clipping context.
  32143. */
  32144. constructor( parentContext = null ) {
  32145. /**
  32146. * The clipping context's version.
  32147. *
  32148. * @type {Number}
  32149. * @readonly
  32150. */
  32151. this.version = 0;
  32152. /**
  32153. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  32154. *
  32155. * @type {Boolean?}
  32156. * @default null
  32157. */
  32158. this.clipIntersection = null;
  32159. /**
  32160. * The clipping context's cache key.
  32161. *
  32162. * @type {String}
  32163. */
  32164. this.cacheKey = '';
  32165. /**
  32166. * Whether the shadow pass is active or not.
  32167. *
  32168. * @type {Boolean}
  32169. * @default false
  32170. */
  32171. this.shadowPass = false;
  32172. /**
  32173. * The view normal matrix.
  32174. *
  32175. * @type {Matrix3}
  32176. */
  32177. this.viewNormalMatrix = new Matrix3();
  32178. /**
  32179. * Internal cache for maintaining clipping contexts.
  32180. *
  32181. * @type {WeakMap<ClippingGroup,ClippingContext>}
  32182. */
  32183. this.clippingGroupContexts = new WeakMap();
  32184. /**
  32185. * The intersection planes.
  32186. *
  32187. * @type {Array<Vector4>}
  32188. */
  32189. this.intersectionPlanes = [];
  32190. /**
  32191. * The intersection planes.
  32192. *
  32193. * @type {Array<Vector4>}
  32194. */
  32195. this.unionPlanes = [];
  32196. /**
  32197. * The version of the clipping context's parent context.
  32198. *
  32199. * @type {Number?}
  32200. * @readonly
  32201. */
  32202. this.parentVersion = null;
  32203. if ( parentContext !== null ) {
  32204. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  32205. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  32206. this.shadowPass = parentContext.shadowPass;
  32207. this.viewMatrix = parentContext.viewMatrix;
  32208. }
  32209. }
  32210. /**
  32211. * Projects the given source clipping planes and writes the result into the
  32212. * destination array.
  32213. *
  32214. * @param {Array<Plane>} source - The source clipping planes.
  32215. * @param {Array<Vector4>} destination - The destination.
  32216. * @param {Number} offset - The offset.
  32217. */
  32218. projectPlanes( source, destination, offset ) {
  32219. const l = source.length;
  32220. for ( let i = 0; i < l; i ++ ) {
  32221. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  32222. const v = destination[ offset + i ];
  32223. const normal = _plane.normal;
  32224. v.x = - normal.x;
  32225. v.y = - normal.y;
  32226. v.z = - normal.z;
  32227. v.w = _plane.constant;
  32228. }
  32229. }
  32230. /**
  32231. * Updates the root clipping context of a scene.
  32232. *
  32233. * @param {Scene} scene - The scene.
  32234. * @param {Camera} camera - The camera that is used to render the scene.
  32235. */
  32236. updateGlobal( scene, camera ) {
  32237. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  32238. this.viewMatrix = camera.matrixWorldInverse;
  32239. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  32240. }
  32241. /**
  32242. * Updates the clipping context.
  32243. *
  32244. * @param {ClippingContext} parentContext - The parent context.
  32245. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  32246. */
  32247. update( parentContext, clippingGroup ) {
  32248. let update = false;
  32249. if ( parentContext.version !== this.parentVersion ) {
  32250. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  32251. this.unionPlanes = Array.from( parentContext.unionPlanes );
  32252. this.parentVersion = parentContext.version;
  32253. }
  32254. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  32255. this.clipIntersection = clippingGroup.clipIntersection;
  32256. if ( this.clipIntersection ) {
  32257. this.unionPlanes.length = parentContext.unionPlanes.length;
  32258. } else {
  32259. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  32260. }
  32261. }
  32262. const srcClippingPlanes = clippingGroup.clippingPlanes;
  32263. const l = srcClippingPlanes.length;
  32264. let dstClippingPlanes;
  32265. let offset;
  32266. if ( this.clipIntersection ) {
  32267. dstClippingPlanes = this.intersectionPlanes;
  32268. offset = parentContext.intersectionPlanes.length;
  32269. } else {
  32270. dstClippingPlanes = this.unionPlanes;
  32271. offset = parentContext.unionPlanes.length;
  32272. }
  32273. if ( dstClippingPlanes.length !== offset + l ) {
  32274. dstClippingPlanes.length = offset + l;
  32275. for ( let i = 0; i < l; i ++ ) {
  32276. dstClippingPlanes[ offset + i ] = new Vector4();
  32277. }
  32278. update = true;
  32279. }
  32280. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  32281. if ( update ) {
  32282. this.version ++;
  32283. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  32284. }
  32285. }
  32286. /**
  32287. * Returns a clipping context for the given clipping group.
  32288. *
  32289. * @param {ClippingGroup} clippingGroup - The clipping group.
  32290. * @return {ClippingContext} The clipping context.
  32291. */
  32292. getGroupContext( clippingGroup ) {
  32293. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  32294. let context = this.clippingGroupContexts.get( clippingGroup );
  32295. if ( context === undefined ) {
  32296. context = new ClippingContext( this );
  32297. this.clippingGroupContexts.set( clippingGroup, context );
  32298. }
  32299. context.update( this, clippingGroup );
  32300. return context;
  32301. }
  32302. /**
  32303. * The count of union clipping planes.
  32304. *
  32305. * @type {Number}
  32306. * @readonly
  32307. */
  32308. get unionClippingCount() {
  32309. return this.unionPlanes.length;
  32310. }
  32311. }
  32312. /**
  32313. * This module is used to represent render bundles inside the renderer
  32314. * for further processing.
  32315. *
  32316. * @private
  32317. */
  32318. class RenderBundle {
  32319. /**
  32320. * Constructs a new bundle group.
  32321. *
  32322. * @param {BundleGroup} bundleGroup - The bundle group.
  32323. * @param {Camera} camera - The camera the bundle group is rendered with.
  32324. */
  32325. constructor( bundleGroup, camera ) {
  32326. this.bundleGroup = bundleGroup;
  32327. this.camera = camera;
  32328. }
  32329. }
  32330. /**
  32331. * This renderer module manages render bundles.
  32332. *
  32333. * @private
  32334. */
  32335. class RenderBundles {
  32336. /**
  32337. * Constructs a new render bundle management component.
  32338. */
  32339. constructor() {
  32340. /**
  32341. * A chain map for maintaining the render bundles.
  32342. *
  32343. * @type {ChainMap}
  32344. */
  32345. this.bundles = new ChainMap();
  32346. }
  32347. /**
  32348. * Returns a render bundle for the given bundle group and camera.
  32349. *
  32350. * @param {BundleGroup} bundleGroup - The bundle group.
  32351. * @param {Camera} camera - The camera the bundle group is rendered with.
  32352. * @return {RenderBundle} The render bundle.
  32353. */
  32354. get( bundleGroup, camera ) {
  32355. const bundles = this.bundles;
  32356. const keys = [ bundleGroup, camera ];
  32357. let bundle = bundles.get( keys );
  32358. if ( bundle === undefined ) {
  32359. bundle = new RenderBundle( bundleGroup, camera );
  32360. bundles.set( keys, bundle );
  32361. }
  32362. return bundle;
  32363. }
  32364. /**
  32365. * Frees all internal resources.
  32366. */
  32367. dispose() {
  32368. this.bundles = new ChainMap();
  32369. }
  32370. }
  32371. /**
  32372. * The purpose of a node library is to assign node implementations
  32373. * to existing library features. In `WebGPURenderer` lights, materials
  32374. * which are not based on `NodeMaterial` as well as tone mapping techniques
  32375. * are implemented with node-based modules.
  32376. *
  32377. * @private
  32378. */
  32379. class NodeLibrary {
  32380. /**
  32381. * Constructs a new node library.
  32382. */
  32383. constructor() {
  32384. /**
  32385. * A weak map that maps lights to light nodes.
  32386. *
  32387. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  32388. */
  32389. this.lightNodes = new WeakMap();
  32390. /**
  32391. * A map that maps materials to node materials.
  32392. *
  32393. * @type {WeakMap<String,NodeMaterial.constructor>}
  32394. */
  32395. this.materialNodes = new Map();
  32396. /**
  32397. * A map that maps tone mapping techniques (constants)
  32398. * to tone mapping node functions.
  32399. *
  32400. * @type {WeakMap<Number,Function>}
  32401. */
  32402. this.toneMappingNodes = new Map();
  32403. }
  32404. /**
  32405. * Returns a matching node material instance for the given material object.
  32406. *
  32407. * This method also assigns/copies the properties of the given material object
  32408. * to the node material. This is done to make sure the current material
  32409. * configuration carries over to the node version.
  32410. *
  32411. * @param {Material} material - A material.
  32412. * @return {NodeMaterial} The corresponding node material.
  32413. */
  32414. fromMaterial( material ) {
  32415. if ( material.isNodeMaterial ) return material;
  32416. let nodeMaterial = null;
  32417. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  32418. if ( nodeMaterialClass !== null ) {
  32419. nodeMaterial = new nodeMaterialClass();
  32420. for ( const key in material ) {
  32421. nodeMaterial[ key ] = material[ key ];
  32422. }
  32423. }
  32424. return nodeMaterial;
  32425. }
  32426. /**
  32427. * Adds a tone mapping node function for a tone mapping technique (constant).
  32428. *
  32429. * @param {Function} toneMappingNode - The tone mapping node function.
  32430. * @param {Number} toneMapping - The tone mapping.
  32431. */
  32432. addToneMapping( toneMappingNode, toneMapping ) {
  32433. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  32434. }
  32435. /**
  32436. * Returns a tone mapping node function for a tone mapping technique (constant).
  32437. *
  32438. * @param {Number} toneMapping - The tone mapping.
  32439. * @return {Function?} The tone mapping node function. Returns `null` if no node function is found.
  32440. */
  32441. getToneMappingFunction( toneMapping ) {
  32442. return this.toneMappingNodes.get( toneMapping ) || null;
  32443. }
  32444. /**
  32445. * Returns a node material class definition for a material type.
  32446. *
  32447. * @param {Sring} materialType - The material type.
  32448. * @return {NodeMaterial.constructor?} The node material class definition. Returns `null` if no node material is found.
  32449. */
  32450. getMaterialNodeClass( materialType ) {
  32451. return this.materialNodes.get( materialType ) || null;
  32452. }
  32453. /**
  32454. * Adds a node material class definition for a given material type.
  32455. *
  32456. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  32457. * @param {Sring} materialClassType - The material type.
  32458. */
  32459. addMaterial( materialNodeClass, materialClassType ) {
  32460. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  32461. }
  32462. /**
  32463. * Returns a light node class definition for a light class definition.
  32464. *
  32465. * @param {Light.constructor} light - The light class definition.
  32466. * @return {AnalyticLightNode.constructor?} The light node class definition. Returns `null` if no light node is found.
  32467. */
  32468. getLightNodeClass( light ) {
  32469. return this.lightNodes.get( light ) || null;
  32470. }
  32471. /**
  32472. * Adds a light node class definition for a given light class definition.
  32473. *
  32474. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  32475. * @param {Light.constructor} lightClass - The light class definition.
  32476. */
  32477. addLight( lightNodeClass, lightClass ) {
  32478. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  32479. }
  32480. /**
  32481. * Adds a node class definition for the given type to the provided type library.
  32482. *
  32483. * @param {Any} nodeClass - The node class definition.
  32484. * @param {String} type - The object type.
  32485. * @param {Map} library - The type library.
  32486. */
  32487. addType( nodeClass, type, library ) {
  32488. if ( library.has( type ) ) {
  32489. console.warn( `Redefinition of node ${ type }` );
  32490. return;
  32491. }
  32492. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32493. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  32494. library.set( type, nodeClass );
  32495. }
  32496. /**
  32497. * Adds a node class definition for the given class definition to the provided type library.
  32498. *
  32499. * @param {Any} nodeClass - The node class definition.
  32500. * @param {Any} baseClass - The class definition.
  32501. * @param {WeakMap} library - The type library.
  32502. */
  32503. addClass( nodeClass, baseClass, library ) {
  32504. if ( library.has( baseClass ) ) {
  32505. console.warn( `Redefinition of node ${ baseClass.name }` );
  32506. return;
  32507. }
  32508. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32509. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  32510. library.set( baseClass, nodeClass );
  32511. }
  32512. }
  32513. const _defaultLights = /*@__PURE__*/ new LightsNode();
  32514. /**
  32515. * This renderer module manages the lights nodes which are unique
  32516. * per scene and camera combination.
  32517. *
  32518. * The lights node itself is later configured in the render list
  32519. * with the actual lights from the scene.
  32520. *
  32521. * @private
  32522. * @augments ChainMap
  32523. */
  32524. class Lighting extends ChainMap {
  32525. /**
  32526. * Constructs a lighting management component.
  32527. */
  32528. constructor() {
  32529. super();
  32530. }
  32531. /**
  32532. * Creates a new lights node for the given array of lights.
  32533. *
  32534. * @param {Array<Light>} lights - The render object.
  32535. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  32536. */
  32537. createNode( lights = [] ) {
  32538. return new LightsNode().setLights( lights );
  32539. }
  32540. /**
  32541. * Returns a lights node for the given scene and camera.
  32542. *
  32543. * @param {Scene} scene - The scene.
  32544. * @param {Camera} camera - The camera.
  32545. * @return {LightsNode} The lights node.
  32546. */
  32547. getNode( scene, camera ) {
  32548. // ignore post-processing
  32549. if ( scene.isQuadMesh ) return _defaultLights;
  32550. // tiled lighting
  32551. const keys = [ scene, camera ];
  32552. let node = this.get( keys );
  32553. if ( node === undefined ) {
  32554. node = this.createNode();
  32555. this.set( keys, node );
  32556. }
  32557. return node;
  32558. }
  32559. }
  32560. /** @module Renderer **/
  32561. const _scene = /*@__PURE__*/ new Scene();
  32562. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  32563. const _screen = /*@__PURE__*/ new Vector4();
  32564. const _frustum = /*@__PURE__*/ new Frustum();
  32565. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  32566. const _vector4 = /*@__PURE__*/ new Vector4();
  32567. /**
  32568. * Base class for renderers.
  32569. */
  32570. class Renderer {
  32571. /**
  32572. * Constructs a new renderer.
  32573. *
  32574. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  32575. * @param {Object} parameters - The configuration parameter.
  32576. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  32577. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  32578. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  32579. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  32580. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  32581. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  32582. * to overwrite the default.
  32583. * @param {Function?} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  32584. */
  32585. constructor( backend, parameters = {} ) {
  32586. /**
  32587. * This flag can be used for type testing.
  32588. *
  32589. * @type {Boolean}
  32590. * @readonly
  32591. * @default true
  32592. */
  32593. this.isRenderer = true;
  32594. //
  32595. const {
  32596. logarithmicDepthBuffer = false,
  32597. alpha = true,
  32598. depth = true,
  32599. stencil = false,
  32600. antialias = false,
  32601. samples = 0,
  32602. getFallback = null
  32603. } = parameters;
  32604. /**
  32605. * A reference to the canvas element the renderer is drawing to.
  32606. * This value of this property will automatically be created by
  32607. * the renderer.
  32608. *
  32609. * @type {HTMLCanvasElement|OffscreenCanvas}
  32610. */
  32611. this.domElement = backend.getDomElement();
  32612. /**
  32613. * A reference to the current backend.
  32614. *
  32615. * @type {Backend}
  32616. */
  32617. this.backend = backend;
  32618. /**
  32619. * The number of MSAA samples.
  32620. *
  32621. * @type {Number}
  32622. * @default 0
  32623. */
  32624. this.samples = samples || ( antialias === true ) ? 4 : 0;
  32625. /**
  32626. * Whether the renderer should automatically clear the current rendering target
  32627. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  32628. * or the current bound render target (custom framebuffer).
  32629. *
  32630. * @type {Boolean}
  32631. * @default true
  32632. */
  32633. this.autoClear = true;
  32634. /**
  32635. * When `autoClear` is set to `true`, this property defines whether the renderer
  32636. * should clear the color buffer.
  32637. *
  32638. * @type {Boolean}
  32639. * @default true
  32640. */
  32641. this.autoClearColor = true;
  32642. /**
  32643. * When `autoClear` is set to `true`, this property defines whether the renderer
  32644. * should clear the depth buffer.
  32645. *
  32646. * @type {Boolean}
  32647. * @default true
  32648. */
  32649. this.autoClearDepth = true;
  32650. /**
  32651. * When `autoClear` is set to `true`, this property defines whether the renderer
  32652. * should clear the stencil buffer.
  32653. *
  32654. * @type {Boolean}
  32655. * @default true
  32656. */
  32657. this.autoClearStencil = true;
  32658. /**
  32659. * Whether the default framebuffer should be transparent or opaque.
  32660. *
  32661. * @type {Boolean}
  32662. * @default true
  32663. */
  32664. this.alpha = alpha;
  32665. /**
  32666. * Whether logarithmic depth buffer is enabled or not.
  32667. *
  32668. * @type {Boolean}
  32669. * @default false
  32670. */
  32671. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  32672. /**
  32673. * Defines the output color space of the renderer.
  32674. *
  32675. * @type {String}
  32676. * @default SRGBColorSpace
  32677. */
  32678. this.outputColorSpace = SRGBColorSpace;
  32679. /**
  32680. * Defines the tone mapping of the renderer.
  32681. *
  32682. * @type {Number}
  32683. * @default NoToneMapping
  32684. */
  32685. this.toneMapping = NoToneMapping;
  32686. /**
  32687. * Defines the tone mapping exposure.
  32688. *
  32689. * @type {Number}
  32690. * @default 1
  32691. */
  32692. this.toneMappingExposure = 1.0;
  32693. /**
  32694. * Whether the renderer should sort its render lists or not.
  32695. *
  32696. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  32697. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  32698. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  32699. * e.g. manually determining each object's rendering order.
  32700. *
  32701. * @type {Boolean}
  32702. * @default true
  32703. */
  32704. this.sortObjects = true;
  32705. /**
  32706. * Whether the default framebuffer should have a depth buffer or not.
  32707. *
  32708. * @type {Boolean}
  32709. * @default true
  32710. */
  32711. this.depth = depth;
  32712. /**
  32713. * Whether the default framebuffer should have a stencil buffer or not.
  32714. *
  32715. * @type {Boolean}
  32716. * @default false
  32717. */
  32718. this.stencil = stencil;
  32719. /**
  32720. * Holds a series of statistical information about the GPU memory
  32721. * and the rendering process. Useful for debugging and monitoring.
  32722. *
  32723. * @type {Boolean}
  32724. */
  32725. this.info = new Info();
  32726. this.nodes = {
  32727. modelViewMatrix: null,
  32728. modelNormalViewMatrix: null
  32729. };
  32730. /**
  32731. * The node library defines how certain library objects like materials, lights
  32732. * or tone mapping functions are mapped to node types. This is required since
  32733. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  32734. * be part of the scene graph, they are internally represented as nodes for
  32735. * further processing.
  32736. *
  32737. * @type {NodeLibrary}
  32738. */
  32739. this.library = new NodeLibrary();
  32740. /**
  32741. * A map-like data structure for managing lights.
  32742. *
  32743. * @type {Lighting}
  32744. */
  32745. this.lighting = new Lighting();
  32746. // internals
  32747. /**
  32748. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  32749. *
  32750. * @private
  32751. * @type {Function}
  32752. */
  32753. this._getFallback = getFallback;
  32754. /**
  32755. * The renderer's pixel ration.
  32756. *
  32757. * @private
  32758. * @type {Number}
  32759. * @default 1
  32760. */
  32761. this._pixelRatio = 1;
  32762. /**
  32763. * The width of the renderer's default framebuffer in logical pixel unit.
  32764. *
  32765. * @private
  32766. * @type {Number}
  32767. */
  32768. this._width = this.domElement.width;
  32769. /**
  32770. * The height of the renderer's default framebuffer in logical pixel unit.
  32771. *
  32772. * @private
  32773. * @type {Number}
  32774. */
  32775. this._height = this.domElement.height;
  32776. /**
  32777. * The viewport of the renderer in logical pixel unit.
  32778. *
  32779. * @private
  32780. * @type {Vector4}
  32781. */
  32782. this._viewport = new Vector4( 0, 0, this._width, this._height );
  32783. /**
  32784. * The scissor rectangle of the renderer in logical pixel unit.
  32785. *
  32786. * @private
  32787. * @type {Vector4}
  32788. */
  32789. this._scissor = new Vector4( 0, 0, this._width, this._height );
  32790. /**
  32791. * Whether the scissor test should be enabled or not.
  32792. *
  32793. * @private
  32794. * @type {Vector4}
  32795. */
  32796. this._scissorTest = false;
  32797. /**
  32798. * A reference to a renderer module for managing shader attributes.
  32799. *
  32800. * @private
  32801. * @type {Attributes?}
  32802. * @default null
  32803. */
  32804. this._attributes = null;
  32805. /**
  32806. * A reference to a renderer module for managing geometries.
  32807. *
  32808. * @private
  32809. * @type {Geometries?}
  32810. * @default null
  32811. */
  32812. this._geometries = null;
  32813. /**
  32814. * A reference to a renderer module for managing node related logic.
  32815. *
  32816. * @private
  32817. * @type {Nodes?}
  32818. * @default null
  32819. */
  32820. this._nodes = null;
  32821. /**
  32822. * A reference to a renderer module for managing the internal animation loop.
  32823. *
  32824. * @private
  32825. * @type {Animation?}
  32826. * @default null
  32827. */
  32828. this._animation = null;
  32829. /**
  32830. * A reference to a renderer module for managing shader program bindings.
  32831. *
  32832. * @private
  32833. * @type {Bindings?}
  32834. * @default null
  32835. */
  32836. this._bindings = null;
  32837. /**
  32838. * A reference to a renderer module for managing render objects.
  32839. *
  32840. * @private
  32841. * @type {RenderObjects?}
  32842. * @default null
  32843. */
  32844. this._objects = null;
  32845. /**
  32846. * A reference to a renderer module for managing render and cmopute pipelines.
  32847. *
  32848. * @private
  32849. * @type {Pipelines?}
  32850. * @default null
  32851. */
  32852. this._pipelines = null;
  32853. /**
  32854. * A reference to a renderer module for managing render bundles.
  32855. *
  32856. * @private
  32857. * @type {RenderBundles?}
  32858. * @default null
  32859. */
  32860. this._bundles = null;
  32861. /**
  32862. * A reference to a renderer module for managing render lists.
  32863. *
  32864. * @private
  32865. * @type {RenderLists?}
  32866. * @default null
  32867. */
  32868. this._renderLists = null;
  32869. /**
  32870. * A reference to a renderer module for managing render contexts.
  32871. *
  32872. * @private
  32873. * @type {RenderContexts?}
  32874. * @default null
  32875. */
  32876. this._renderContexts = null;
  32877. /**
  32878. * A reference to a renderer module for managing textures.
  32879. *
  32880. * @private
  32881. * @type {Textures?}
  32882. * @default null
  32883. */
  32884. this._textures = null;
  32885. /**
  32886. * A reference to a renderer module for backgrounds.
  32887. *
  32888. * @private
  32889. * @type {Background?}
  32890. * @default null
  32891. */
  32892. this._background = null;
  32893. /**
  32894. * This fullscreen quad is used for internal render passes
  32895. * like the tone mapping and color space output pass.
  32896. *
  32897. * @private
  32898. * @type {QuadMesh}
  32899. */
  32900. this._quad = new QuadMesh( new NodeMaterial() );
  32901. this._quad.material.name = 'Renderer_output';
  32902. /**
  32903. * A reference to the current render context.
  32904. *
  32905. * @private
  32906. * @type {RenderContext?}
  32907. * @default null
  32908. */
  32909. this._currentRenderContext = null;
  32910. /**
  32911. * A custom sort function for the opaque render list.
  32912. *
  32913. * @private
  32914. * @type {Function?}
  32915. * @default null
  32916. */
  32917. this._opaqueSort = null;
  32918. /**
  32919. * A custom sort function for the transparent render list.
  32920. *
  32921. * @private
  32922. * @type {Function?}
  32923. * @default null
  32924. */
  32925. this._transparentSort = null;
  32926. /**
  32927. * The framebuffer target.
  32928. *
  32929. * @private
  32930. * @type {RenderTarget?}
  32931. * @default null
  32932. */
  32933. this._frameBufferTarget = null;
  32934. const alphaClear = this.alpha === true ? 0 : 1;
  32935. /**
  32936. * The clear color value.
  32937. *
  32938. * @private
  32939. * @type {Color4}
  32940. */
  32941. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  32942. /**
  32943. * The clear depth value.
  32944. *
  32945. * @private
  32946. * @type {Number}
  32947. * @default 1
  32948. */
  32949. this._clearDepth = 1;
  32950. /**
  32951. * The clear stencil value.
  32952. *
  32953. * @private
  32954. * @type {Number}
  32955. * @default 0
  32956. */
  32957. this._clearStencil = 0;
  32958. /**
  32959. * The current render target.
  32960. *
  32961. * @private
  32962. * @type {RenderTarget?}
  32963. * @default null
  32964. */
  32965. this._renderTarget = null;
  32966. /**
  32967. * The active cube face.
  32968. *
  32969. * @private
  32970. * @type {Number}
  32971. * @default 0
  32972. */
  32973. this._activeCubeFace = 0;
  32974. /**
  32975. * The active mipmap level.
  32976. *
  32977. * @private
  32978. * @type {Number}
  32979. * @default 0
  32980. */
  32981. this._activeMipmapLevel = 0;
  32982. /**
  32983. * The MRT setting.
  32984. *
  32985. * @private
  32986. * @type {MRTNode?}
  32987. * @default null
  32988. */
  32989. this._mrt = null;
  32990. /**
  32991. * This function defines how a render object is going
  32992. * to be rendered.
  32993. *
  32994. * @private
  32995. * @type {Function?}
  32996. * @default null
  32997. */
  32998. this._renderObjectFunction = null;
  32999. /**
  33000. * Used to keep track of the current render object function.
  33001. *
  33002. * @private
  33003. * @type {Function?}
  33004. * @default null
  33005. */
  33006. this._currentRenderObjectFunction = null;
  33007. /**
  33008. * Used to keep track of the current render bundle.
  33009. *
  33010. * @private
  33011. * @type {RenderBundle?}
  33012. * @default null
  33013. */
  33014. this._currentRenderBundle = null;
  33015. /**
  33016. * Next to `_renderObjectFunction()`, this function provides another hook
  33017. * for influening the render process of a render object. It is meant for internal
  33018. * use and only relevant for `compileAsync()` right now. Instead of using
  33019. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  33020. * a different function might be used which performs no draw but just the node
  33021. * and pipeline updates.
  33022. *
  33023. * @private
  33024. * @type {Function?}
  33025. * @default null
  33026. */
  33027. this._handleObjectFunction = this._renderObjectDirect;
  33028. /**
  33029. * Indicates whether the device has been lost or not. In WebGL terms, the device
  33030. * lost is considered as a context lost. When this is set to `true`, rendering
  33031. * isn't possible anymore.
  33032. *
  33033. * @private
  33034. * @type {Boolean}
  33035. * @default false
  33036. */
  33037. this._isDeviceLost = false;
  33038. /**
  33039. * A callback function that defines what should happen when a device/context lost occurs.
  33040. *
  33041. * @type {Function}
  33042. */
  33043. this.onDeviceLost = this._onDeviceLost;
  33044. /**
  33045. * Whether the renderer has been initialized or not.
  33046. *
  33047. * @private
  33048. * @type {Boolean}
  33049. * @default false
  33050. */
  33051. this._initialized = false;
  33052. /**
  33053. * A reference to the promise which initializes the renderer.
  33054. *
  33055. * @private
  33056. * @type {Promise?}
  33057. * @default null
  33058. */
  33059. this._initPromise = null;
  33060. /**
  33061. * An array of compilation promises which are used in `compileAsync()`.
  33062. *
  33063. * @private
  33064. * @type {Array<Promise>?}
  33065. * @default null
  33066. */
  33067. this._compilationPromises = null;
  33068. /**
  33069. * Whether the renderer should render transparent render objects or not.
  33070. *
  33071. * @type {Boolean}
  33072. * @default true
  33073. */
  33074. this.transparent = true;
  33075. /**
  33076. * Whether the renderer should render opaque render objects or not.
  33077. *
  33078. * @type {Boolean}
  33079. * @default true
  33080. */
  33081. this.opaque = true;
  33082. /**
  33083. * Shadow map configuration
  33084. * @typedef {Object} ShadowMapConfig
  33085. * @property {Boolean} enabled - Whether to globally enable shadows or not.
  33086. * @property {Number} type - The shadow map type.
  33087. */
  33088. /**
  33089. * The renderer's shadow configuration.
  33090. *
  33091. * @type {module:Renderer~ShadowMapConfig}
  33092. */
  33093. this.shadowMap = {
  33094. enabled: false,
  33095. type: PCFShadowMap
  33096. };
  33097. /**
  33098. * XR configuration.
  33099. * @typedef {Object} XRConfig
  33100. * @property {Boolean} enabled - Whether to globally enable XR or not.
  33101. */
  33102. /**
  33103. * The renderer's XR configuration.
  33104. *
  33105. * @type {module:Renderer~XRConfig}
  33106. */
  33107. this.xr = {
  33108. enabled: false
  33109. };
  33110. /**
  33111. * Debug configuration.
  33112. * @typedef {Object} DebugConfig
  33113. * @property {Boolean} checkShaderErrors - Whether shader errors should be checked or not.
  33114. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  33115. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camerea and 3D object.
  33116. */
  33117. /**
  33118. * The renderer's debug configuration.
  33119. *
  33120. * @type {module:Renderer~DebugConfig}
  33121. */
  33122. this.debug = {
  33123. checkShaderErrors: true,
  33124. onShaderError: null,
  33125. getShaderAsync: async ( scene, camera, object ) => {
  33126. await this.compileAsync( scene, camera );
  33127. const renderList = this._renderLists.get( scene, camera );
  33128. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  33129. const material = scene.overrideMaterial || object.material;
  33130. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  33131. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  33132. return { fragmentShader, vertexShader };
  33133. }
  33134. };
  33135. }
  33136. /**
  33137. * Initializes the renderer so it is ready for usage.
  33138. *
  33139. * @async
  33140. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  33141. */
  33142. async init() {
  33143. if ( this._initialized ) {
  33144. throw new Error( 'Renderer: Backend has already been initialized.' );
  33145. }
  33146. if ( this._initPromise !== null ) {
  33147. return this._initPromise;
  33148. }
  33149. this._initPromise = new Promise( async ( resolve, reject ) => {
  33150. let backend = this.backend;
  33151. try {
  33152. await backend.init( this );
  33153. } catch ( error ) {
  33154. if ( this._getFallback !== null ) {
  33155. // try the fallback
  33156. try {
  33157. this.backend = backend = this._getFallback( error );
  33158. await backend.init( this );
  33159. } catch ( error ) {
  33160. reject( error );
  33161. return;
  33162. }
  33163. } else {
  33164. reject( error );
  33165. return;
  33166. }
  33167. }
  33168. this._nodes = new Nodes( this, backend );
  33169. this._animation = new Animation( this._nodes, this.info );
  33170. this._attributes = new Attributes( backend );
  33171. this._background = new Background( this, this._nodes );
  33172. this._geometries = new Geometries( this._attributes, this.info );
  33173. this._textures = new Textures( this, backend, this.info );
  33174. this._pipelines = new Pipelines( backend, this._nodes );
  33175. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  33176. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  33177. this._renderLists = new RenderLists( this.lighting );
  33178. this._bundles = new RenderBundles();
  33179. this._renderContexts = new RenderContexts();
  33180. //
  33181. this._animation.start();
  33182. this._initialized = true;
  33183. resolve();
  33184. } );
  33185. return this._initPromise;
  33186. }
  33187. /**
  33188. * The coordinate system of the renderer. The value of this property
  33189. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  33190. * `THREE.WebGPUCoordinateSystem`.
  33191. *
  33192. * @readonly
  33193. * @type {Number}
  33194. */
  33195. get coordinateSystem() {
  33196. return this.backend.coordinateSystem;
  33197. }
  33198. /**
  33199. * Compiles all materials in the given scene. This can be useful to avoid a
  33200. * phenomenon which is called "shader compilation stutter", which occurs when
  33201. * rendering an object with a new shader for the first time.
  33202. *
  33203. * If you want to add a 3D object to an existing scene, use the third optional
  33204. * parameter for applying the target scene. Note that the (target) scene's lighting
  33205. * and environment must be configured before calling this method.
  33206. *
  33207. * @async
  33208. * @param {Object3D} scene - The scene or 3D object to precompile.
  33209. * @param {Camera} camera - The camera that is used to render the scene.
  33210. * @param {Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  33211. * @return {Promise} A Promise that resolves when the compile has been finished.
  33212. */
  33213. async compileAsync( scene, camera, targetScene = null ) {
  33214. if ( this._isDeviceLost === true ) return;
  33215. if ( this._initialized === false ) await this.init();
  33216. // preserve render tree
  33217. const nodeFrame = this._nodes.nodeFrame;
  33218. const previousRenderId = nodeFrame.renderId;
  33219. const previousRenderContext = this._currentRenderContext;
  33220. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  33221. const previousCompilationPromises = this._compilationPromises;
  33222. //
  33223. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  33224. if ( targetScene === null ) targetScene = scene;
  33225. const renderTarget = this._renderTarget;
  33226. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  33227. const activeMipmapLevel = this._activeMipmapLevel;
  33228. const compilationPromises = [];
  33229. this._currentRenderContext = renderContext;
  33230. this._currentRenderObjectFunction = this.renderObject;
  33231. this._handleObjectFunction = this._createObjectPipeline;
  33232. this._compilationPromises = compilationPromises;
  33233. nodeFrame.renderId ++;
  33234. //
  33235. nodeFrame.update();
  33236. //
  33237. renderContext.depth = this.depth;
  33238. renderContext.stencil = this.stencil;
  33239. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  33240. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  33241. //
  33242. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  33243. //
  33244. const renderList = this._renderLists.get( scene, camera );
  33245. renderList.begin();
  33246. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  33247. // include lights from target scene
  33248. if ( targetScene !== scene ) {
  33249. targetScene.traverseVisible( function ( object ) {
  33250. if ( object.isLight && object.layers.test( camera.layers ) ) {
  33251. renderList.pushLight( object );
  33252. }
  33253. } );
  33254. }
  33255. renderList.finish();
  33256. //
  33257. if ( renderTarget !== null ) {
  33258. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  33259. const renderTargetData = this._textures.get( renderTarget );
  33260. renderContext.textures = renderTargetData.textures;
  33261. renderContext.depthTexture = renderTargetData.depthTexture;
  33262. } else {
  33263. renderContext.textures = null;
  33264. renderContext.depthTexture = null;
  33265. }
  33266. //
  33267. this._background.update( sceneRef, renderList, renderContext );
  33268. // process render lists
  33269. const opaqueObjects = renderList.opaque;
  33270. const transparentObjects = renderList.transparent;
  33271. const transparentDoublePassObjects = renderList.transparentDoublePass;
  33272. const lightsNode = renderList.lightsNode;
  33273. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  33274. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  33275. // restore render tree
  33276. nodeFrame.renderId = previousRenderId;
  33277. this._currentRenderContext = previousRenderContext;
  33278. this._currentRenderObjectFunction = previousRenderObjectFunction;
  33279. this._compilationPromises = previousCompilationPromises;
  33280. this._handleObjectFunction = this._renderObjectDirect;
  33281. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  33282. await Promise.all( compilationPromises );
  33283. }
  33284. /**
  33285. * Renders the scene in an async fashion.
  33286. *
  33287. * @async
  33288. * @param {Object3D} scene - The scene or 3D object to render.
  33289. * @param {Camera} camera - The camera.
  33290. * @return {Promise} A Promise that resolves when the render has been finished.
  33291. */
  33292. async renderAsync( scene, camera ) {
  33293. if ( this._initialized === false ) await this.init();
  33294. const renderContext = this._renderScene( scene, camera );
  33295. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  33296. }
  33297. /**
  33298. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  33299. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  33300. *
  33301. * @async
  33302. * @return {Promise} A Promise that resolves when synchronization has been finished.
  33303. */
  33304. async waitForGPU() {
  33305. await this.backend.waitForGPU();
  33306. }
  33307. /**
  33308. * Sets the given MRT configuration.
  33309. *
  33310. * @param {MRTNode} mrt - The MRT node to set.
  33311. * @return {Renderer} A reference to this renderer.
  33312. */
  33313. setMRT( mrt ) {
  33314. this._mrt = mrt;
  33315. return this;
  33316. }
  33317. /**
  33318. * Returns the MRT configuration.
  33319. *
  33320. * @return {MRTNode} The MRT configuration.
  33321. */
  33322. getMRT() {
  33323. return this._mrt;
  33324. }
  33325. /**
  33326. * Default implementation of the device lost callback.
  33327. *
  33328. * @private
  33329. * @param {Object} info - Information about the context lost.
  33330. */
  33331. _onDeviceLost( info ) {
  33332. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  33333. if ( info.reason ) {
  33334. errorMessage += `\nReason: ${info.reason}`;
  33335. }
  33336. console.error( errorMessage );
  33337. this._isDeviceLost = true;
  33338. }
  33339. /**
  33340. * Renders the given render bundle.
  33341. *
  33342. * @private
  33343. * @param {Object} bundle - Render bundle data.
  33344. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  33345. * @param {LightsNode} lightsNode - The current lights node.
  33346. */
  33347. _renderBundle( bundle, sceneRef, lightsNode ) {
  33348. const { bundleGroup, camera, renderList } = bundle;
  33349. const renderContext = this._currentRenderContext;
  33350. //
  33351. const renderBundle = this._bundles.get( bundleGroup, camera );
  33352. const renderBundleData = this.backend.get( renderBundle );
  33353. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  33354. //
  33355. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  33356. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  33357. renderBundleData.renderContexts.add( renderContext );
  33358. if ( renderBundleNeedsUpdate ) {
  33359. this.backend.beginBundle( renderContext );
  33360. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  33361. renderBundleData.renderObjects = [];
  33362. }
  33363. this._currentRenderBundle = renderBundle;
  33364. const opaqueObjects = renderList.opaque;
  33365. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  33366. this._currentRenderBundle = null;
  33367. //
  33368. this.backend.finishBundle( renderContext, renderBundle );
  33369. renderBundleData.version = bundleGroup.version;
  33370. } else {
  33371. const { renderObjects } = renderBundleData;
  33372. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  33373. const renderObject = renderObjects[ i ];
  33374. if ( this._nodes.needsRefresh( renderObject ) ) {
  33375. this._nodes.updateBefore( renderObject );
  33376. this._nodes.updateForRender( renderObject );
  33377. this._bindings.updateForRender( renderObject );
  33378. this._nodes.updateAfter( renderObject );
  33379. }
  33380. }
  33381. }
  33382. this.backend.addBundle( renderContext, renderBundle );
  33383. }
  33384. /**
  33385. * Renders the scene or 3D object with the given camera. This method can only be called
  33386. * if the renderer has been initialized.
  33387. *
  33388. * The target of the method is the default framebuffer (meaning the canvas)
  33389. * or alternatively a render target when specified via `setRenderTarget()`.
  33390. *
  33391. * @param {Object3D} scene - The scene or 3D object to render.
  33392. * @param {Camera} camera - The camera to render the scene with.
  33393. * @return {Promise?} A Promise that resolve when the scene has been rendered.
  33394. * Only returned when the renderer has not been initialized.
  33395. */
  33396. render( scene, camera ) {
  33397. if ( this._initialized === false ) {
  33398. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  33399. return this.renderAsync( scene, camera );
  33400. }
  33401. this._renderScene( scene, camera );
  33402. }
  33403. /**
  33404. * Returns an internal render target which is used when computing the output tone mapping
  33405. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  33406. * pass and not inline to achieve more correct results.
  33407. *
  33408. * @private
  33409. * @return {RenderTarget?} The render target. The method returns `null` if no output conversion should be applied.
  33410. */
  33411. _getFrameBufferTarget() {
  33412. const { currentToneMapping, currentColorSpace } = this;
  33413. const useToneMapping = currentToneMapping !== NoToneMapping;
  33414. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  33415. if ( useToneMapping === false && useColorSpace === false ) return null;
  33416. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  33417. const { depth, stencil } = this;
  33418. let frameBufferTarget = this._frameBufferTarget;
  33419. if ( frameBufferTarget === null ) {
  33420. frameBufferTarget = new RenderTarget( width, height, {
  33421. depthBuffer: depth,
  33422. stencilBuffer: stencil,
  33423. type: HalfFloatType, // FloatType
  33424. format: RGBAFormat,
  33425. colorSpace: LinearSRGBColorSpace,
  33426. generateMipmaps: false,
  33427. minFilter: LinearFilter,
  33428. magFilter: LinearFilter,
  33429. samples: this.samples
  33430. } );
  33431. frameBufferTarget.isPostProcessingRenderTarget = true;
  33432. this._frameBufferTarget = frameBufferTarget;
  33433. }
  33434. frameBufferTarget.depthBuffer = depth;
  33435. frameBufferTarget.stencilBuffer = stencil;
  33436. frameBufferTarget.setSize( width, height );
  33437. frameBufferTarget.viewport.copy( this._viewport );
  33438. frameBufferTarget.scissor.copy( this._scissor );
  33439. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  33440. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  33441. frameBufferTarget.scissorTest = this._scissorTest;
  33442. return frameBufferTarget;
  33443. }
  33444. /**
  33445. * Renders the scene or 3D object with the given camera.
  33446. *
  33447. * @private
  33448. * @param {Object3D} scene - The scene or 3D object to render.
  33449. * @param {Camera} camera - The camera to render the scene with.
  33450. * @param {Boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  33451. * @return {RenderContext} The current render context.
  33452. */
  33453. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  33454. if ( this._isDeviceLost === true ) return;
  33455. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  33456. // preserve render tree
  33457. const nodeFrame = this._nodes.nodeFrame;
  33458. const previousRenderId = nodeFrame.renderId;
  33459. const previousRenderContext = this._currentRenderContext;
  33460. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  33461. //
  33462. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  33463. const outputRenderTarget = this._renderTarget;
  33464. const activeCubeFace = this._activeCubeFace;
  33465. const activeMipmapLevel = this._activeMipmapLevel;
  33466. //
  33467. let renderTarget;
  33468. if ( frameBufferTarget !== null ) {
  33469. renderTarget = frameBufferTarget;
  33470. this.setRenderTarget( renderTarget );
  33471. } else {
  33472. renderTarget = outputRenderTarget;
  33473. }
  33474. //
  33475. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  33476. this._currentRenderContext = renderContext;
  33477. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  33478. //
  33479. this.info.calls ++;
  33480. this.info.render.calls ++;
  33481. this.info.render.frameCalls ++;
  33482. nodeFrame.renderId = this.info.calls;
  33483. //
  33484. const coordinateSystem = this.coordinateSystem;
  33485. if ( camera.coordinateSystem !== coordinateSystem ) {
  33486. camera.coordinateSystem = coordinateSystem;
  33487. camera.updateProjectionMatrix();
  33488. }
  33489. //
  33490. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  33491. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  33492. //
  33493. let viewport = this._viewport;
  33494. let scissor = this._scissor;
  33495. let pixelRatio = this._pixelRatio;
  33496. if ( renderTarget !== null ) {
  33497. viewport = renderTarget.viewport;
  33498. scissor = renderTarget.scissor;
  33499. pixelRatio = 1;
  33500. }
  33501. this.getDrawingBufferSize( _drawingBufferSize );
  33502. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  33503. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  33504. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  33505. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  33506. renderContext.viewportValue.width >>= activeMipmapLevel;
  33507. renderContext.viewportValue.height >>= activeMipmapLevel;
  33508. renderContext.viewportValue.minDepth = minDepth;
  33509. renderContext.viewportValue.maxDepth = maxDepth;
  33510. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  33511. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  33512. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  33513. renderContext.scissorValue.width >>= activeMipmapLevel;
  33514. renderContext.scissorValue.height >>= activeMipmapLevel;
  33515. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  33516. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  33517. //
  33518. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  33519. //
  33520. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33521. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  33522. const renderList = this._renderLists.get( scene, camera );
  33523. renderList.begin();
  33524. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  33525. renderList.finish();
  33526. if ( this.sortObjects === true ) {
  33527. renderList.sort( this._opaqueSort, this._transparentSort );
  33528. }
  33529. //
  33530. if ( renderTarget !== null ) {
  33531. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  33532. const renderTargetData = this._textures.get( renderTarget );
  33533. renderContext.textures = renderTargetData.textures;
  33534. renderContext.depthTexture = renderTargetData.depthTexture;
  33535. renderContext.width = renderTargetData.width;
  33536. renderContext.height = renderTargetData.height;
  33537. renderContext.renderTarget = renderTarget;
  33538. renderContext.depth = renderTarget.depthBuffer;
  33539. renderContext.stencil = renderTarget.stencilBuffer;
  33540. } else {
  33541. renderContext.textures = null;
  33542. renderContext.depthTexture = null;
  33543. renderContext.width = this.domElement.width;
  33544. renderContext.height = this.domElement.height;
  33545. renderContext.depth = this.depth;
  33546. renderContext.stencil = this.stencil;
  33547. }
  33548. renderContext.width >>= activeMipmapLevel;
  33549. renderContext.height >>= activeMipmapLevel;
  33550. renderContext.activeCubeFace = activeCubeFace;
  33551. renderContext.activeMipmapLevel = activeMipmapLevel;
  33552. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  33553. //
  33554. this._background.update( sceneRef, renderList, renderContext );
  33555. //
  33556. this.backend.beginRender( renderContext );
  33557. // process render lists
  33558. const {
  33559. bundles,
  33560. lightsNode,
  33561. transparentDoublePass: transparentDoublePassObjects,
  33562. transparent: transparentObjects,
  33563. opaque: opaqueObjects
  33564. } = renderList;
  33565. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  33566. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  33567. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  33568. // finish render pass
  33569. this.backend.finishRender( renderContext );
  33570. // restore render tree
  33571. nodeFrame.renderId = previousRenderId;
  33572. this._currentRenderContext = previousRenderContext;
  33573. this._currentRenderObjectFunction = previousRenderObjectFunction;
  33574. //
  33575. if ( frameBufferTarget !== null ) {
  33576. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  33577. const quad = this._quad;
  33578. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  33579. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  33580. quad.material.needsUpdate = true;
  33581. }
  33582. this._renderScene( quad, quad.camera, false );
  33583. }
  33584. //
  33585. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  33586. //
  33587. return renderContext;
  33588. }
  33589. /**
  33590. * Returns the maximum available anisotropy for texture filtering.
  33591. *
  33592. * @return {Number} The maximum available anisotropy.
  33593. */
  33594. getMaxAnisotropy() {
  33595. return this.backend.getMaxAnisotropy();
  33596. }
  33597. /**
  33598. * Returns the active cube face.
  33599. *
  33600. * @return {Number} The active cube face.
  33601. */
  33602. getActiveCubeFace() {
  33603. return this._activeCubeFace;
  33604. }
  33605. /**
  33606. * Returns the active mipmap level.
  33607. *
  33608. * @return {Number} The active mipmap level.
  33609. */
  33610. getActiveMipmapLevel() {
  33611. return this._activeMipmapLevel;
  33612. }
  33613. /**
  33614. * Applications are advised to always define the animation loop
  33615. * with this method and not manually with `requestAnimationFrame()`
  33616. * for best compatibility.
  33617. *
  33618. * @async
  33619. * @param {Function} callback - The application's animation loop.
  33620. * @return {Promise} A Promise that resolves when the set has been exeucted.
  33621. */
  33622. async setAnimationLoop( callback ) {
  33623. if ( this._initialized === false ) await this.init();
  33624. this._animation.setAnimationLoop( callback );
  33625. }
  33626. /**
  33627. * Can be used to transfer buffer data from a storage buffer attribute
  33628. * from the GPU to the CPU in context of compute shaders.
  33629. *
  33630. * @async
  33631. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  33632. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  33633. */
  33634. async getArrayBufferAsync( attribute ) {
  33635. return await this.backend.getArrayBufferAsync( attribute );
  33636. }
  33637. /**
  33638. * Returns the rendering context.
  33639. *
  33640. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  33641. */
  33642. getContext() {
  33643. return this.backend.getContext();
  33644. }
  33645. /**
  33646. * Returns the pixel ratio.
  33647. *
  33648. * @return {Number} The pixel ratio.
  33649. */
  33650. getPixelRatio() {
  33651. return this._pixelRatio;
  33652. }
  33653. /**
  33654. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  33655. *
  33656. * @param {Vector2} target - The method writes the result in this target object.
  33657. * @return {Vector2} The drawing buffer size.
  33658. */
  33659. getDrawingBufferSize( target ) {
  33660. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  33661. }
  33662. /**
  33663. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  33664. *
  33665. * @param {Vector2} target - The method writes the result in this target object.
  33666. * @return {Vector2} The drawing buffer size.
  33667. */
  33668. getSize( target ) {
  33669. return target.set( this._width, this._height );
  33670. }
  33671. /**
  33672. * Sets the given pixel ration and resizes the canvas if necessary.
  33673. *
  33674. * @param {Number} [value=1] - The pixel ratio.
  33675. */
  33676. setPixelRatio( value = 1 ) {
  33677. if ( this._pixelRatio === value ) return;
  33678. this._pixelRatio = value;
  33679. this.setSize( this._width, this._height, false );
  33680. }
  33681. /**
  33682. * This method allows to define the drawing buffer size by specifying
  33683. * width, height and pixel ratio all at once. The size of the drawing
  33684. * buffer is computed with this formula:
  33685. * ````
  33686. * size.x = width * pixelRatio;
  33687. * size.y = height * pixelRatio;
  33688. *```
  33689. *
  33690. * @param {Number} width - The width in logical pixels.
  33691. * @param {Number} height - The height in logical pixels.
  33692. * @param {Number} pixelRatio - The pixel ratio.
  33693. */
  33694. setDrawingBufferSize( width, height, pixelRatio ) {
  33695. this._width = width;
  33696. this._height = height;
  33697. this._pixelRatio = pixelRatio;
  33698. this.domElement.width = Math.floor( width * pixelRatio );
  33699. this.domElement.height = Math.floor( height * pixelRatio );
  33700. this.setViewport( 0, 0, width, height );
  33701. if ( this._initialized ) this.backend.updateSize();
  33702. }
  33703. /**
  33704. * Sets the size of the renderer.
  33705. *
  33706. * @param {Number} width - The width in logical pixels.
  33707. * @param {Number} height - The height in logical pixels.
  33708. * @param {Boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  33709. */
  33710. setSize( width, height, updateStyle = true ) {
  33711. this._width = width;
  33712. this._height = height;
  33713. this.domElement.width = Math.floor( width * this._pixelRatio );
  33714. this.domElement.height = Math.floor( height * this._pixelRatio );
  33715. if ( updateStyle === true ) {
  33716. this.domElement.style.width = width + 'px';
  33717. this.domElement.style.height = height + 'px';
  33718. }
  33719. this.setViewport( 0, 0, width, height );
  33720. if ( this._initialized ) this.backend.updateSize();
  33721. }
  33722. /**
  33723. * Defines a manual sort function for the opaque render list.
  33724. * Pass `null` to use the default sort.
  33725. *
  33726. * @param {Function} method - The sort function.
  33727. */
  33728. setOpaqueSort( method ) {
  33729. this._opaqueSort = method;
  33730. }
  33731. /**
  33732. * Defines a manual sort function for the transparent render list.
  33733. * Pass `null` to use the default sort.
  33734. *
  33735. * @param {Function} method - The sort function.
  33736. */
  33737. setTransparentSort( method ) {
  33738. this._transparentSort = method;
  33739. }
  33740. /**
  33741. * Returns the scissor rectangle.
  33742. *
  33743. * @param {Vector4} target - The method writes the result in this target object.
  33744. * @return {Vector4} The scissor rectangle.
  33745. */
  33746. getScissor( target ) {
  33747. const scissor = this._scissor;
  33748. target.x = scissor.x;
  33749. target.y = scissor.y;
  33750. target.width = scissor.width;
  33751. target.height = scissor.height;
  33752. return target;
  33753. }
  33754. /**
  33755. * Defines the scissor rectangle.
  33756. *
  33757. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  33758. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  33759. * @param {Number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  33760. * @param {Number} width - The width of the scissor box in logical pixel unit.
  33761. * @param {Number} height - The height of the scissor box in logical pixel unit.
  33762. */
  33763. setScissor( x, y, width, height ) {
  33764. const scissor = this._scissor;
  33765. if ( x.isVector4 ) {
  33766. scissor.copy( x );
  33767. } else {
  33768. scissor.set( x, y, width, height );
  33769. }
  33770. }
  33771. /**
  33772. * Returns the scissor test value.
  33773. *
  33774. * @return {Boolean} Whether the scissor test should be enabled or not.
  33775. */
  33776. getScissorTest() {
  33777. return this._scissorTest;
  33778. }
  33779. /**
  33780. * Defines the scissor test.
  33781. *
  33782. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  33783. */
  33784. setScissorTest( boolean ) {
  33785. this._scissorTest = boolean;
  33786. this.backend.setScissorTest( boolean );
  33787. }
  33788. /**
  33789. * Returns the viewport definition.
  33790. *
  33791. * @param {Vector4} target - The method writes the result in this target object.
  33792. * @return {Vector4} The viewport definition.
  33793. */
  33794. getViewport( target ) {
  33795. return target.copy( this._viewport );
  33796. }
  33797. /**
  33798. * Defines the viewport.
  33799. *
  33800. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  33801. * @param {Number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  33802. * @param {Number} width - The width of the viewport in logical pixel unit.
  33803. * @param {Number} height - The height of the viewport in logical pixel unit.
  33804. * @param {Number} minDepth - The minimum depth value of the viewport. WebGPU only.
  33805. * @param {Number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  33806. */
  33807. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  33808. const viewport = this._viewport;
  33809. if ( x.isVector4 ) {
  33810. viewport.copy( x );
  33811. } else {
  33812. viewport.set( x, y, width, height );
  33813. }
  33814. viewport.minDepth = minDepth;
  33815. viewport.maxDepth = maxDepth;
  33816. }
  33817. /**
  33818. * Returns the clear color.
  33819. *
  33820. * @param {Color} target - The method writes the result in this target object.
  33821. * @return {Color} The clear color.
  33822. */
  33823. getClearColor( target ) {
  33824. return target.copy( this._clearColor );
  33825. }
  33826. /**
  33827. * Defines the clear color and optionally the clear alpha.
  33828. *
  33829. * @param {Color} color - The clear color.
  33830. * @param {Number} [alpha=1] - The clear alpha.
  33831. */
  33832. setClearColor( color, alpha = 1 ) {
  33833. this._clearColor.set( color );
  33834. this._clearColor.a = alpha;
  33835. }
  33836. /**
  33837. * Returns the clear alpha.
  33838. *
  33839. * @return {Number} The clear alpha.
  33840. */
  33841. getClearAlpha() {
  33842. return this._clearColor.a;
  33843. }
  33844. /**
  33845. * Defines the clear alpha.
  33846. *
  33847. * @param {Number} alpha - The clear alpha.
  33848. */
  33849. setClearAlpha( alpha ) {
  33850. this._clearColor.a = alpha;
  33851. }
  33852. /**
  33853. * Returns the clear depth.
  33854. *
  33855. * @return {Number} The clear depth.
  33856. */
  33857. getClearDepth() {
  33858. return this._clearDepth;
  33859. }
  33860. /**
  33861. * Defines the clear depth.
  33862. *
  33863. * @param {Number} depth - The clear depth.
  33864. */
  33865. setClearDepth( depth ) {
  33866. this._clearDepth = depth;
  33867. }
  33868. /**
  33869. * Returns the clear stencil.
  33870. *
  33871. * @return {Number} The clear stencil.
  33872. */
  33873. getClearStencil() {
  33874. return this._clearStencil;
  33875. }
  33876. /**
  33877. * Defines the clear stencil.
  33878. *
  33879. * @param {Number} stencil - The clear stencil.
  33880. */
  33881. setClearStencil( stencil ) {
  33882. this._clearStencil = stencil;
  33883. }
  33884. /**
  33885. * This method performs an occlusion query for the given 3D object.
  33886. * It returns `true` if the given 3D object is fully occluded by other
  33887. * 3D objects in the scene.
  33888. *
  33889. * @param {Object3D} object - The 3D object to test.
  33890. * @return {Boolean} Whether the 3D object is fully occluded or not.
  33891. */
  33892. isOccluded( object ) {
  33893. const renderContext = this._currentRenderContext;
  33894. return renderContext && this.backend.isOccluded( renderContext, object );
  33895. }
  33896. /**
  33897. * Performs a manual clear operation. This method ignores `autoClear` properties.
  33898. *
  33899. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  33900. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  33901. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  33902. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33903. * Only returned when the renderer has not been initialized.
  33904. */
  33905. clear( color = true, depth = true, stencil = true ) {
  33906. if ( this._initialized === false ) {
  33907. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  33908. return this.clearAsync( color, depth, stencil );
  33909. }
  33910. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  33911. let renderContext = null;
  33912. if ( renderTarget !== null ) {
  33913. this._textures.updateRenderTarget( renderTarget );
  33914. const renderTargetData = this._textures.get( renderTarget );
  33915. renderContext = this._renderContexts.get( null, null, renderTarget );
  33916. renderContext.textures = renderTargetData.textures;
  33917. renderContext.depthTexture = renderTargetData.depthTexture;
  33918. renderContext.width = renderTargetData.width;
  33919. renderContext.height = renderTargetData.height;
  33920. renderContext.renderTarget = renderTarget;
  33921. renderContext.depth = renderTarget.depthBuffer;
  33922. renderContext.stencil = renderTarget.stencilBuffer;
  33923. }
  33924. this.backend.clear( color, depth, stencil, renderContext );
  33925. if ( renderTarget !== null && this._renderTarget === null ) {
  33926. // If a color space transform or tone mapping is required,
  33927. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  33928. const quad = this._quad;
  33929. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  33930. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  33931. quad.material.needsUpdate = true;
  33932. }
  33933. this._renderScene( quad, quad.camera, false );
  33934. }
  33935. }
  33936. /**
  33937. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  33938. *
  33939. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33940. * Only returned when the renderer has not been initialized.
  33941. */
  33942. clearColor() {
  33943. return this.clear( true, false, false );
  33944. }
  33945. /**
  33946. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  33947. *
  33948. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33949. * Only returned when the renderer has not been initialized.
  33950. */
  33951. clearDepth() {
  33952. return this.clear( false, true, false );
  33953. }
  33954. /**
  33955. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  33956. *
  33957. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33958. * Only returned when the renderer has not been initialized.
  33959. */
  33960. clearStencil() {
  33961. return this.clear( false, false, true );
  33962. }
  33963. /**
  33964. * Async version of {@link module:Renderer~Renderer#clear}.
  33965. *
  33966. * @async
  33967. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  33968. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  33969. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  33970. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33971. */
  33972. async clearAsync( color = true, depth = true, stencil = true ) {
  33973. if ( this._initialized === false ) await this.init();
  33974. this.clear( color, depth, stencil );
  33975. }
  33976. /**
  33977. * Async version of {@link module:Renderer~Renderer#clearColor}.
  33978. *
  33979. * @async
  33980. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33981. */
  33982. async clearColorAsync() {
  33983. this.clearAsync( true, false, false );
  33984. }
  33985. /**
  33986. * Async version of {@link module:Renderer~Renderer#clearDepth}.
  33987. *
  33988. * @async
  33989. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33990. */
  33991. async clearDepthAsync() {
  33992. this.clearAsync( false, true, false );
  33993. }
  33994. /**
  33995. * Async version of {@link module:Renderer~Renderer#clearStencil}.
  33996. *
  33997. * @async
  33998. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  33999. */
  34000. async clearStencilAsync() {
  34001. this.clearAsync( false, false, true );
  34002. }
  34003. /**
  34004. * The current output tone mapping of the renderer. When a render target is set,
  34005. * the output tone mapping is always `NoToneMapping`.
  34006. *
  34007. * @type {Number}
  34008. */
  34009. get currentToneMapping() {
  34010. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  34011. }
  34012. /**
  34013. * The current output color space of the renderer. When a render target is set,
  34014. * the output color space is always `LinearSRGBColorSpace`.
  34015. *
  34016. * @type {String}
  34017. */
  34018. get currentColorSpace() {
  34019. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  34020. }
  34021. /**
  34022. * Frees all internal resources of the renderer. Call this method if the renderer
  34023. * is no longer in use by your app.
  34024. */
  34025. dispose() {
  34026. this.info.dispose();
  34027. this.backend.dispose();
  34028. this._animation.dispose();
  34029. this._objects.dispose();
  34030. this._pipelines.dispose();
  34031. this._nodes.dispose();
  34032. this._bindings.dispose();
  34033. this._renderLists.dispose();
  34034. this._renderContexts.dispose();
  34035. this._textures.dispose();
  34036. this.setRenderTarget( null );
  34037. this.setAnimationLoop( null );
  34038. }
  34039. /**
  34040. * Sets the given render target. Calling this method means the renderer does not
  34041. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  34042. * Use `null` as the first argument to reset the state.
  34043. *
  34044. * @param {RenderTarget?} renderTarget - The render target to set.
  34045. * @param {Number} [activeCubeFace=0] - The active cube face.
  34046. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  34047. */
  34048. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  34049. this._renderTarget = renderTarget;
  34050. this._activeCubeFace = activeCubeFace;
  34051. this._activeMipmapLevel = activeMipmapLevel;
  34052. }
  34053. /**
  34054. * Returns the current render target.
  34055. *
  34056. * @return {RenderTarget?} The render target. Returns `null` if no render target is set.
  34057. */
  34058. getRenderTarget() {
  34059. return this._renderTarget;
  34060. }
  34061. /**
  34062. * Callback for {@link module:Renderer~Renderer#setRenderObjectFunction}.
  34063. *
  34064. * @callback renderObjectFunction
  34065. * @param {Object3D} object - The 3D object.
  34066. * @param {Scene} scene - The scene the 3D object belongs to.
  34067. * @param {Camera} camera - The camera the object should be rendered with.
  34068. * @param {BufferGeometry} geometry - The object's geometry.
  34069. * @param {Material} material - The object's material.
  34070. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34071. * @param {LightsNode} lightsNode - The current lights node.
  34072. * @param {ClippingContext} clippingContext - The clipping context.
  34073. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34074. */
  34075. /**
  34076. * Sets the given render object function. Calling this method overwrites the default implementation
  34077. * which is {@link module:Renderer~Renderer#renderObject}. Defining a custom function can be useful
  34078. * if you want to modify the way objects are rendered. For example you can define things like "every
  34079. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  34080. * The custom function must always call `renderObject()` in its implementation.
  34081. *
  34082. * Use `null` as the first argument to reset the state.
  34083. *
  34084. * @param {module:Renderer~renderObjectFunction?} renderObjectFunction - The render object function.
  34085. */
  34086. setRenderObjectFunction( renderObjectFunction ) {
  34087. this._renderObjectFunction = renderObjectFunction;
  34088. }
  34089. /**
  34090. * Returns the current render object function.
  34091. *
  34092. * @return {Function?} The current render object function. Returns `null` if no function is set.
  34093. */
  34094. getRenderObjectFunction() {
  34095. return this._renderObjectFunction;
  34096. }
  34097. /**
  34098. * Execute a single or an array of compute nodes. This method can only be called
  34099. * if the renderer has been initialized.
  34100. *
  34101. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  34102. * @return {Promise?} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  34103. */
  34104. compute( computeNodes ) {
  34105. if ( this.isDeviceLost === true ) return;
  34106. if ( this._initialized === false ) {
  34107. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  34108. return this.computeAsync( computeNodes );
  34109. }
  34110. //
  34111. const nodeFrame = this._nodes.nodeFrame;
  34112. const previousRenderId = nodeFrame.renderId;
  34113. //
  34114. this.info.calls ++;
  34115. this.info.compute.calls ++;
  34116. this.info.compute.frameCalls ++;
  34117. nodeFrame.renderId = this.info.calls;
  34118. //
  34119. const backend = this.backend;
  34120. const pipelines = this._pipelines;
  34121. const bindings = this._bindings;
  34122. const nodes = this._nodes;
  34123. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  34124. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  34125. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  34126. }
  34127. backend.beginCompute( computeNodes );
  34128. for ( const computeNode of computeList ) {
  34129. // onInit
  34130. if ( pipelines.has( computeNode ) === false ) {
  34131. const dispose = () => {
  34132. computeNode.removeEventListener( 'dispose', dispose );
  34133. pipelines.delete( computeNode );
  34134. bindings.delete( computeNode );
  34135. nodes.delete( computeNode );
  34136. };
  34137. computeNode.addEventListener( 'dispose', dispose );
  34138. //
  34139. const onInitFn = computeNode.onInitFunction;
  34140. if ( onInitFn !== null ) {
  34141. onInitFn.call( computeNode, { renderer: this } );
  34142. }
  34143. }
  34144. nodes.updateForCompute( computeNode );
  34145. bindings.updateForCompute( computeNode );
  34146. const computeBindings = bindings.getForCompute( computeNode );
  34147. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  34148. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  34149. }
  34150. backend.finishCompute( computeNodes );
  34151. //
  34152. nodeFrame.renderId = previousRenderId;
  34153. }
  34154. /**
  34155. * Execute a single or an array of compute nodes.
  34156. *
  34157. * @async
  34158. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  34159. * @return {Promise?} A Promise that resolve when the compute has finished.
  34160. */
  34161. async computeAsync( computeNodes ) {
  34162. if ( this._initialized === false ) await this.init();
  34163. this.compute( computeNodes );
  34164. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  34165. }
  34166. /**
  34167. * Checks if the given feature is supported by the selected backend.
  34168. *
  34169. * @async
  34170. * @param {String} name - The feature's name.
  34171. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  34172. */
  34173. async hasFeatureAsync( name ) {
  34174. if ( this._initialized === false ) await this.init();
  34175. return this.backend.hasFeature( name );
  34176. }
  34177. /**
  34178. * Checks if the given feature is supported by the selected backend. If the
  34179. * renderer has not been initialized, this method always returns `false`.
  34180. *
  34181. * @param {String} name - The feature's name.
  34182. * @return {Boolean} Whether the feature is supported or not.
  34183. */
  34184. hasFeature( name ) {
  34185. if ( this._initialized === false ) {
  34186. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  34187. return false;
  34188. }
  34189. return this.backend.hasFeature( name );
  34190. }
  34191. /**
  34192. * Returns `true` when the renderer has been initialized.
  34193. *
  34194. * @return {Boolean} Whether the renderer has been initialized or not.
  34195. */
  34196. hasInitialized() {
  34197. return this._initialized;
  34198. }
  34199. /**
  34200. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  34201. * (which can cause noticeable lags due to decode and GPU upload overhead).
  34202. *
  34203. * @async
  34204. * @param {Texture} texture - The texture.
  34205. * @return {Promise} A Promise that resolves when the texture has been initialized.
  34206. */
  34207. async initTextureAsync( texture ) {
  34208. if ( this._initialized === false ) await this.init();
  34209. this._textures.updateTexture( texture );
  34210. }
  34211. /**
  34212. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  34213. * (which can cause noticeable lags due to decode and GPU upload overhead).
  34214. *
  34215. * This method can only be used if the renderer has been initialized.
  34216. *
  34217. * @param {Texture} texture - The texture.
  34218. */
  34219. initTexture( texture ) {
  34220. if ( this._initialized === false ) {
  34221. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  34222. }
  34223. this._textures.updateTexture( texture );
  34224. }
  34225. /**
  34226. * Copies the current bound framebuffer into the given texture.
  34227. *
  34228. * @param {FramebufferTexture} framebufferTexture - The texture.
  34229. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  34230. */
  34231. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  34232. if ( rectangle !== null ) {
  34233. if ( rectangle.isVector2 ) {
  34234. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  34235. } else if ( rectangle.isVector4 ) {
  34236. rectangle = _vector4.copy( rectangle ).floor();
  34237. } else {
  34238. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  34239. return;
  34240. }
  34241. } else {
  34242. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  34243. }
  34244. //
  34245. let renderContext = this._currentRenderContext;
  34246. let renderTarget;
  34247. if ( renderContext !== null ) {
  34248. renderTarget = renderContext.renderTarget;
  34249. } else {
  34250. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  34251. if ( renderTarget !== null ) {
  34252. this._textures.updateRenderTarget( renderTarget );
  34253. renderContext = this._textures.get( renderTarget );
  34254. }
  34255. }
  34256. //
  34257. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  34258. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  34259. }
  34260. /**
  34261. * Copies data of source texture into a destination texture.
  34262. *
  34263. * @param {Texture} srcTexture - The source texture.
  34264. * @param {Texture} dstTexture - The destination texture.
  34265. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  34266. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  34267. * @param {Number} level - The mipmap level to copy.
  34268. */
  34269. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  34270. this._textures.updateTexture( srcTexture );
  34271. this._textures.updateTexture( dstTexture );
  34272. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  34273. }
  34274. /**
  34275. * Reads pixel data from the given render target.
  34276. *
  34277. * @async
  34278. * @param {RenderTarget} renderTarget - The render target to read from.
  34279. * @param {Number} x - The `x` coordinate of the copy region's origin.
  34280. * @param {Number} y - The `y` coordinate of the copy region's origin.
  34281. * @param {Number} width - The width of the copy region.
  34282. * @param {Number} height - The height of the copy region.
  34283. * @param {Number} [textureIndex=0] - The texture index of a MRT render target.
  34284. * @param {Number} [faceIndex=0] - The active cube face index.
  34285. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  34286. */
  34287. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  34288. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  34289. }
  34290. /**
  34291. * Analyzes the given 3D object's hierarchy and builds render lists from the
  34292. * processed hierarchy.
  34293. *
  34294. * @param {Object3D} object - The 3D object to process (usually a scene).
  34295. * @param {Camera} camera - The camera the object is rendered with.
  34296. * @param {Number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  34297. * @param {RenderList} renderList - The current render list.
  34298. * @param {ClippingContext} clippingContext - The current clipping context.
  34299. */
  34300. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  34301. if ( object.visible === false ) return;
  34302. const visible = object.layers.test( camera.layers );
  34303. if ( visible ) {
  34304. if ( object.isGroup ) {
  34305. groupOrder = object.renderOrder;
  34306. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  34307. } else if ( object.isLOD ) {
  34308. if ( object.autoUpdate === true ) object.update( camera );
  34309. } else if ( object.isLight ) {
  34310. renderList.pushLight( object );
  34311. } else if ( object.isSprite ) {
  34312. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  34313. if ( this.sortObjects === true ) {
  34314. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  34315. }
  34316. const { geometry, material } = object;
  34317. if ( material.visible ) {
  34318. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  34319. }
  34320. }
  34321. } else if ( object.isLineLoop ) {
  34322. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  34323. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  34324. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  34325. const { geometry, material } = object;
  34326. if ( this.sortObjects === true ) {
  34327. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  34328. _vector4
  34329. .copy( geometry.boundingSphere.center )
  34330. .applyMatrix4( object.matrixWorld )
  34331. .applyMatrix4( _projScreenMatrix );
  34332. }
  34333. if ( Array.isArray( material ) ) {
  34334. const groups = geometry.groups;
  34335. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  34336. const group = groups[ i ];
  34337. const groupMaterial = material[ group.materialIndex ];
  34338. if ( groupMaterial && groupMaterial.visible ) {
  34339. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  34340. }
  34341. }
  34342. } else if ( material.visible ) {
  34343. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  34344. }
  34345. }
  34346. }
  34347. }
  34348. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  34349. const baseRenderList = renderList;
  34350. // replace render list
  34351. renderList = this._renderLists.get( object, camera );
  34352. renderList.begin();
  34353. baseRenderList.pushBundle( {
  34354. bundleGroup: object,
  34355. camera,
  34356. renderList,
  34357. } );
  34358. renderList.finish();
  34359. }
  34360. const children = object.children;
  34361. for ( let i = 0, l = children.length; i < l; i ++ ) {
  34362. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  34363. }
  34364. }
  34365. /**
  34366. * Renders the given render bundles.
  34367. *
  34368. * @private
  34369. * @param {Array<Object>} bundles - Array with render bundle data.
  34370. * @param {Scene} sceneRef - The scene the render bundles belong to.
  34371. * @param {LightsNode} lightsNode - The current lights node.
  34372. */
  34373. _renderBundles( bundles, sceneRef, lightsNode ) {
  34374. for ( const bundle of bundles ) {
  34375. this._renderBundle( bundle, sceneRef, lightsNode );
  34376. }
  34377. }
  34378. /**
  34379. * Renders the transparent objects from the given render lists.
  34380. *
  34381. * @private
  34382. * @param {Array<Object>} renderList - The transparent render list.
  34383. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  34384. * @param {Camera} camera - The camera the render list should be rendered with.
  34385. * @param {Scene} scene - The scene the render list belongs to.
  34386. * @param {LightsNode} lightsNode - The current lights node.
  34387. */
  34388. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  34389. if ( doublePassList.length > 0 ) {
  34390. // render back side
  34391. for ( const { material } of doublePassList ) {
  34392. material.side = BackSide;
  34393. }
  34394. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  34395. // render front side
  34396. for ( const { material } of doublePassList ) {
  34397. material.side = FrontSide;
  34398. }
  34399. this._renderObjects( renderList, camera, scene, lightsNode );
  34400. // restore
  34401. for ( const { material } of doublePassList ) {
  34402. material.side = DoubleSide;
  34403. }
  34404. } else {
  34405. this._renderObjects( renderList, camera, scene, lightsNode );
  34406. }
  34407. }
  34408. /**
  34409. * Renders the objects from the given render list.
  34410. *
  34411. * @private
  34412. * @param {Array<Object>} renderList - The render list.
  34413. * @param {Camera} camera - The camera the render list should be rendered with.
  34414. * @param {Scene} scene - The scene the render list belongs to.
  34415. * @param {LightsNode} lightsNode - The current lights node.
  34416. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34417. */
  34418. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  34419. // process renderable objects
  34420. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  34421. const renderItem = renderList[ i ];
  34422. // @TODO: Add support for multiple materials per object. This will require to extract
  34423. // the material from the renderItem object and pass it with its group data to renderObject().
  34424. const { object, geometry, material, group, clippingContext } = renderItem;
  34425. if ( camera.isArrayCamera ) {
  34426. const cameras = camera.cameras;
  34427. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  34428. const camera2 = cameras[ j ];
  34429. if ( object.layers.test( camera2.layers ) ) {
  34430. const vp = camera2.viewport;
  34431. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  34432. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  34433. const viewportValue = this._currentRenderContext.viewportValue;
  34434. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  34435. viewportValue.minDepth = minDepth;
  34436. viewportValue.maxDepth = maxDepth;
  34437. this.backend.updateViewport( this._currentRenderContext );
  34438. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  34439. }
  34440. }
  34441. } else {
  34442. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  34443. }
  34444. }
  34445. }
  34446. /**
  34447. * This method represents the default render object function that manages the render lifecycle
  34448. * of the object.
  34449. *
  34450. * @param {Object3D} object - The 3D object.
  34451. * @param {Scene} scene - The scene the 3D object belongs to.
  34452. * @param {Camera} camera - The camera the object should be rendered with.
  34453. * @param {BufferGeometry} geometry - The object's geometry.
  34454. * @param {Material} material - The object's material.
  34455. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34456. * @param {LightsNode} lightsNode - The current lights node.
  34457. * @param {ClippingContext} clippingContext - The clipping context.
  34458. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34459. */
  34460. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  34461. let overridePositionNode;
  34462. let overrideColorNode;
  34463. let overrideDepthNode;
  34464. //
  34465. object.onBeforeRender( this, scene, camera, geometry, material, group );
  34466. //
  34467. if ( scene.overrideMaterial !== null ) {
  34468. const overrideMaterial = scene.overrideMaterial;
  34469. if ( material.positionNode && material.positionNode.isNode ) {
  34470. overridePositionNode = overrideMaterial.positionNode;
  34471. overrideMaterial.positionNode = material.positionNode;
  34472. }
  34473. overrideMaterial.alphaTest = material.alphaTest;
  34474. overrideMaterial.alphaMap = material.alphaMap;
  34475. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  34476. if ( overrideMaterial.isShadowNodeMaterial ) {
  34477. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  34478. if ( material.depthNode && material.depthNode.isNode ) {
  34479. overrideDepthNode = overrideMaterial.depthNode;
  34480. overrideMaterial.depthNode = material.depthNode;
  34481. }
  34482. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  34483. overrideColorNode = overrideMaterial.colorNode;
  34484. overrideMaterial.colorNode = material.castShadowNode;
  34485. }
  34486. }
  34487. material = overrideMaterial;
  34488. }
  34489. //
  34490. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  34491. material.side = BackSide;
  34492. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  34493. material.side = FrontSide;
  34494. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  34495. material.side = DoubleSide;
  34496. } else {
  34497. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  34498. }
  34499. //
  34500. if ( overridePositionNode !== undefined ) {
  34501. scene.overrideMaterial.positionNode = overridePositionNode;
  34502. }
  34503. if ( overrideDepthNode !== undefined ) {
  34504. scene.overrideMaterial.depthNode = overrideDepthNode;
  34505. }
  34506. if ( overrideColorNode !== undefined ) {
  34507. scene.overrideMaterial.colorNode = overrideColorNode;
  34508. }
  34509. //
  34510. object.onAfterRender( this, scene, camera, geometry, material, group );
  34511. }
  34512. /**
  34513. * This method represents the default `_handleObjectFunction` implementation which creates
  34514. * a render object from the given data and performs the draw command with the selected backend.
  34515. *
  34516. * @private
  34517. * @param {Object3D} object - The 3D object.
  34518. * @param {Material} material - The object's material.
  34519. * @param {Scene} scene - The scene the 3D object belongs to.
  34520. * @param {Camera} camera - The camera the object should be rendered with.
  34521. * @param {LightsNode} lightsNode - The current lights node.
  34522. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34523. * @param {ClippingContext} clippingContext - The clipping context.
  34524. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34525. */
  34526. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  34527. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  34528. renderObject.drawRange = object.geometry.drawRange;
  34529. renderObject.group = group;
  34530. //
  34531. const needsRefresh = this._nodes.needsRefresh( renderObject );
  34532. if ( needsRefresh ) {
  34533. this._nodes.updateBefore( renderObject );
  34534. this._geometries.updateForRender( renderObject );
  34535. this._nodes.updateForRender( renderObject );
  34536. this._bindings.updateForRender( renderObject );
  34537. }
  34538. this._pipelines.updateForRender( renderObject );
  34539. //
  34540. if ( this._currentRenderBundle !== null ) {
  34541. const renderBundleData = this.backend.get( this._currentRenderBundle );
  34542. renderBundleData.renderObjects.push( renderObject );
  34543. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  34544. }
  34545. this.backend.draw( renderObject, this.info );
  34546. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  34547. }
  34548. /**
  34549. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  34550. * Used in `compileAsync()`.
  34551. *
  34552. * @private
  34553. * @param {Object3D} object - The 3D object.
  34554. * @param {Material} material - The object's material.
  34555. * @param {Scene} scene - The scene the 3D object belongs to.
  34556. * @param {Camera} camera - The camera the object should be rendered with.
  34557. * @param {LightsNode} lightsNode - The current lights node.
  34558. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  34559. * @param {ClippingContext} clippingContext - The clipping context.
  34560. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  34561. */
  34562. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  34563. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  34564. renderObject.drawRange = object.geometry.drawRange;
  34565. renderObject.group = group;
  34566. //
  34567. this._nodes.updateBefore( renderObject );
  34568. this._geometries.updateForRender( renderObject );
  34569. this._nodes.updateForRender( renderObject );
  34570. this._bindings.updateForRender( renderObject );
  34571. this._pipelines.getForRender( renderObject, this._compilationPromises );
  34572. this._nodes.updateAfter( renderObject );
  34573. }
  34574. /**
  34575. * Alias for `compileAsync()`.
  34576. *
  34577. * @method
  34578. * @param {Object3D} scene - The scene or 3D object to precompile.
  34579. * @param {Camera} camera - The camera that is used to render the scene.
  34580. * @param {Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  34581. * @return {Promise} A Promise that resolves when the compile has been finished.
  34582. */
  34583. get compile() {
  34584. return this.compileAsync;
  34585. }
  34586. }
  34587. /**
  34588. * A binding represents the connection between a resource (like a texture, sampler
  34589. * or uniform buffer) and the resource definition in a shader stage.
  34590. *
  34591. * This module is an abstract base class for all concrete bindings types.
  34592. *
  34593. * @abstract
  34594. * @private
  34595. */
  34596. class Binding {
  34597. /**
  34598. * Constructs a new binding.
  34599. *
  34600. * @param {String} [name=''] - The binding's name.
  34601. */
  34602. constructor( name = '' ) {
  34603. /**
  34604. * The binding's name.
  34605. *
  34606. * @type {String}
  34607. */
  34608. this.name = name;
  34609. /**
  34610. * A bitmask that defines in what shader stages the
  34611. * binding's resource is accessible.
  34612. *
  34613. * @type {String}
  34614. */
  34615. this.visibility = 0;
  34616. }
  34617. /**
  34618. * Makes sure binding's resource is visible for the given shader stage.
  34619. *
  34620. * @param {Number} visibility - The shader stage.
  34621. */
  34622. setVisibility( visibility ) {
  34623. this.visibility |= visibility;
  34624. }
  34625. /**
  34626. * Clones the binding.
  34627. *
  34628. * @return {Binding} The cloned binding.
  34629. */
  34630. clone() {
  34631. return Object.assign( new this.constructor(), this );
  34632. }
  34633. }
  34634. /** @module BufferUtils **/
  34635. /**
  34636. * This function is usually called with the length in bytes of an array buffer.
  34637. * It returns an padded value whic ensure chunk size alignment according to STD140 layout.
  34638. *
  34639. * @function
  34640. * @param {Number} floatLength - The buffer length.
  34641. * @return {Number} The padded length.
  34642. */
  34643. function getFloatLength( floatLength ) {
  34644. // ensure chunk size alignment (STD140 layout)
  34645. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  34646. }
  34647. /**
  34648. * Represents a buffer binding type.
  34649. *
  34650. * @private
  34651. * @abstract
  34652. * @augments Binding
  34653. */
  34654. class Buffer extends Binding {
  34655. /**
  34656. * Constructs a new buffer.
  34657. *
  34658. * @param {String} name - The buffer's name.
  34659. * @param {TypedArray} [buffer=null] - The buffer.
  34660. */
  34661. constructor( name, buffer = null ) {
  34662. super( name );
  34663. /**
  34664. * This flag can be used for type testing.
  34665. *
  34666. * @type {Boolean}
  34667. * @readonly
  34668. * @default true
  34669. */
  34670. this.isBuffer = true;
  34671. /**
  34672. * The bytes per element.
  34673. *
  34674. * @type {Number}
  34675. */
  34676. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  34677. /**
  34678. * A reference to the internal buffer.
  34679. *
  34680. * @private
  34681. * @type {TypedArray}
  34682. */
  34683. this._buffer = buffer;
  34684. }
  34685. /**
  34686. * The buffer's byte length.
  34687. *
  34688. * @type {Number}
  34689. * @readonly
  34690. */
  34691. get byteLength() {
  34692. return getFloatLength( this._buffer.byteLength );
  34693. }
  34694. /**
  34695. * A reference to the internal buffer.
  34696. *
  34697. * @type {Float32Array}
  34698. * @readonly
  34699. */
  34700. get buffer() {
  34701. return this._buffer;
  34702. }
  34703. /**
  34704. * Updates the binding.
  34705. *
  34706. * @return {Boolean} Whether the buffer has been updated and must be
  34707. * uploaded to the GPU.
  34708. */
  34709. update() {
  34710. return true;
  34711. }
  34712. }
  34713. /**
  34714. * Represents a uniform buffer binding type.
  34715. *
  34716. * @private
  34717. * @augments Buffer
  34718. */
  34719. class UniformBuffer extends Buffer {
  34720. /**
  34721. * Constructs a new uniform buffer.
  34722. *
  34723. * @param {String} name - The buffer's name.
  34724. * @param {TypedArray} [buffer=null] - The buffer.
  34725. */
  34726. constructor( name, buffer = null ) {
  34727. super( name, buffer );
  34728. /**
  34729. * This flag can be used for type testing.
  34730. *
  34731. * @type {Boolean}
  34732. * @readonly
  34733. * @default true
  34734. */
  34735. this.isUniformBuffer = true;
  34736. }
  34737. }
  34738. let _id$4 = 0;
  34739. /**
  34740. * A special form of uniform buffer binding type.
  34741. * It's buffer value is managed by a node object.
  34742. *
  34743. * @private
  34744. * @augments UniformBuffer
  34745. */
  34746. class NodeUniformBuffer extends UniformBuffer {
  34747. /**
  34748. * Constructs a new node-based uniform buffer.
  34749. *
  34750. * @param {BufferNode} nodeUniform - The uniform buffer node.
  34751. * @param {UniformGroupNode} groupNode - The uniform group node.
  34752. */
  34753. constructor( nodeUniform, groupNode ) {
  34754. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  34755. /**
  34756. * The uniform buffer node.
  34757. *
  34758. * @type {BufferNode}
  34759. */
  34760. this.nodeUniform = nodeUniform;
  34761. /**
  34762. * The uniform group node.
  34763. *
  34764. * @type {UniformGroupNode}
  34765. */
  34766. this.groupNode = groupNode;
  34767. }
  34768. /**
  34769. * The uniform buffer.
  34770. *
  34771. * @type {Float32Array}
  34772. */
  34773. get buffer() {
  34774. return this.nodeUniform.value;
  34775. }
  34776. }
  34777. /**
  34778. * This class represents a uniform buffer binding but with
  34779. * an API that allows to maintain individual uniform objects.
  34780. *
  34781. * @private
  34782. * @augments UniformBuffer
  34783. */
  34784. class UniformsGroup extends UniformBuffer {
  34785. /**
  34786. * Constructs a new uniforms group.
  34787. *
  34788. * @param {String} name - The group's name.
  34789. */
  34790. constructor( name ) {
  34791. super( name );
  34792. /**
  34793. * This flag can be used for type testing.
  34794. *
  34795. * @type {Boolean}
  34796. * @readonly
  34797. * @default true
  34798. */
  34799. this.isUniformsGroup = true;
  34800. /**
  34801. * An array with the raw uniform values.
  34802. *
  34803. * @private
  34804. * @type {Array<Number>?}
  34805. * @default null
  34806. */
  34807. this._values = null;
  34808. /**
  34809. * An array of uniform objects.
  34810. *
  34811. * The order of uniforms in this array must match the order of uniforms in the shader.
  34812. *
  34813. * @type {Array<Uniform>}
  34814. */
  34815. this.uniforms = [];
  34816. }
  34817. /**
  34818. * Adds a uniform to this group.
  34819. *
  34820. * @param {Uniform} uniform - The uniform to add.
  34821. * @return {UniformsGroup} A reference to this group.
  34822. */
  34823. addUniform( uniform ) {
  34824. this.uniforms.push( uniform );
  34825. return this;
  34826. }
  34827. /**
  34828. * Removes a uniform from this group.
  34829. *
  34830. * @param {Uniform} uniform - The uniform to remove.
  34831. * @return {UniformsGroup} A reference to this group.
  34832. */
  34833. removeUniform( uniform ) {
  34834. const index = this.uniforms.indexOf( uniform );
  34835. if ( index !== - 1 ) {
  34836. this.uniforms.splice( index, 1 );
  34837. }
  34838. return this;
  34839. }
  34840. /**
  34841. * An array with the raw uniform values.
  34842. *
  34843. * @type {Array<Number>}
  34844. */
  34845. get values() {
  34846. if ( this._values === null ) {
  34847. this._values = Array.from( this.buffer );
  34848. }
  34849. return this._values;
  34850. }
  34851. /**
  34852. * A Float32 array buffer with the uniform values.
  34853. *
  34854. * @type {Float32Array}
  34855. */
  34856. get buffer() {
  34857. let buffer = this._buffer;
  34858. if ( buffer === null ) {
  34859. const byteLength = this.byteLength;
  34860. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  34861. this._buffer = buffer;
  34862. }
  34863. return buffer;
  34864. }
  34865. /**
  34866. * The byte length of the buffer with correct buffer alignment.
  34867. *
  34868. * @type {Number}
  34869. */
  34870. get byteLength() {
  34871. let offset = 0; // global buffer offset in bytes
  34872. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  34873. const uniform = this.uniforms[ i ];
  34874. const { boundary, itemSize } = uniform;
  34875. // offset within a single chunk in bytes
  34876. const chunkOffset = offset % GPU_CHUNK_BYTES;
  34877. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  34878. // conformance tests
  34879. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  34880. // check for chunk overflow
  34881. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  34882. } else if ( chunkOffset % boundary !== 0 ) {
  34883. // check for correct alignment
  34884. offset += ( chunkOffset % boundary );
  34885. }
  34886. uniform.offset = ( offset / this.bytesPerElement );
  34887. offset += ( itemSize * this.bytesPerElement );
  34888. }
  34889. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  34890. }
  34891. /**
  34892. * Updates this group by updating each uniform object of
  34893. * the internal uniform list. The uniform objects check if their
  34894. * values has actually changed so this method only returns
  34895. * `true` if there is a real value change.
  34896. *
  34897. * @return {Boolean} Whether the uniforms have been updated and
  34898. * must be uploaded to the GPU.
  34899. */
  34900. update() {
  34901. let updated = false;
  34902. for ( const uniform of this.uniforms ) {
  34903. if ( this.updateByType( uniform ) === true ) {
  34904. updated = true;
  34905. }
  34906. }
  34907. return updated;
  34908. }
  34909. /**
  34910. * Updates a given uniform by calling an update method matching
  34911. * the uniforms type.
  34912. *
  34913. * @param {Uniform} uniform - The uniform to update.
  34914. * @return {Boolean} Whether the uniform has been updated or not.
  34915. */
  34916. updateByType( uniform ) {
  34917. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  34918. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  34919. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  34920. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  34921. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  34922. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  34923. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  34924. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  34925. }
  34926. /**
  34927. * Updates a given Number uniform.
  34928. *
  34929. * @param {NumberUniform} uniform - The Number uniform.
  34930. * @return {Boolean} Whether the uniform has been updated or not.
  34931. */
  34932. updateNumber( uniform ) {
  34933. let updated = false;
  34934. const a = this.values;
  34935. const v = uniform.getValue();
  34936. const offset = uniform.offset;
  34937. const type = uniform.getType();
  34938. if ( a[ offset ] !== v ) {
  34939. const b = this._getBufferForType( type );
  34940. b[ offset ] = a[ offset ] = v;
  34941. updated = true;
  34942. }
  34943. return updated;
  34944. }
  34945. /**
  34946. * Updates a given Vector2 uniform.
  34947. *
  34948. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  34949. * @return {Boolean} Whether the uniform has been updated or not.
  34950. */
  34951. updateVector2( uniform ) {
  34952. let updated = false;
  34953. const a = this.values;
  34954. const v = uniform.getValue();
  34955. const offset = uniform.offset;
  34956. const type = uniform.getType();
  34957. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  34958. const b = this._getBufferForType( type );
  34959. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  34960. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  34961. updated = true;
  34962. }
  34963. return updated;
  34964. }
  34965. /**
  34966. * Updates a given Vector3 uniform.
  34967. *
  34968. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  34969. * @return {Boolean} Whether the uniform has been updated or not.
  34970. */
  34971. updateVector3( uniform ) {
  34972. let updated = false;
  34973. const a = this.values;
  34974. const v = uniform.getValue();
  34975. const offset = uniform.offset;
  34976. const type = uniform.getType();
  34977. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  34978. const b = this._getBufferForType( type );
  34979. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  34980. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  34981. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  34982. updated = true;
  34983. }
  34984. return updated;
  34985. }
  34986. /**
  34987. * Updates a given Vector4 uniform.
  34988. *
  34989. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  34990. * @return {Boolean} Whether the uniform has been updated or not.
  34991. */
  34992. updateVector4( uniform ) {
  34993. let updated = false;
  34994. const a = this.values;
  34995. const v = uniform.getValue();
  34996. const offset = uniform.offset;
  34997. const type = uniform.getType();
  34998. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  34999. const b = this._getBufferForType( type );
  35000. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  35001. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  35002. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  35003. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  35004. updated = true;
  35005. }
  35006. return updated;
  35007. }
  35008. /**
  35009. * Updates a given Color uniform.
  35010. *
  35011. * @param {ColorUniform} uniform - The Color uniform.
  35012. * @return {Boolean} Whether the uniform has been updated or not.
  35013. */
  35014. updateColor( uniform ) {
  35015. let updated = false;
  35016. const a = this.values;
  35017. const c = uniform.getValue();
  35018. const offset = uniform.offset;
  35019. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  35020. const b = this.buffer;
  35021. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  35022. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  35023. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  35024. updated = true;
  35025. }
  35026. return updated;
  35027. }
  35028. /**
  35029. * Updates a given Matrix3 uniform.
  35030. *
  35031. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  35032. * @return {Boolean} Whether the uniform has been updated or not.
  35033. */
  35034. updateMatrix3( uniform ) {
  35035. let updated = false;
  35036. const a = this.values;
  35037. const e = uniform.getValue().elements;
  35038. const offset = uniform.offset;
  35039. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  35040. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  35041. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  35042. const b = this.buffer;
  35043. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  35044. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  35045. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  35046. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  35047. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  35048. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  35049. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  35050. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  35051. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  35052. updated = true;
  35053. }
  35054. return updated;
  35055. }
  35056. /**
  35057. * Updates a given Matrix4 uniform.
  35058. *
  35059. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  35060. * @return {Boolean} Whether the uniform has been updated or not.
  35061. */
  35062. updateMatrix4( uniform ) {
  35063. let updated = false;
  35064. const a = this.values;
  35065. const e = uniform.getValue().elements;
  35066. const offset = uniform.offset;
  35067. if ( arraysEqual( a, e, offset ) === false ) {
  35068. const b = this.buffer;
  35069. b.set( e, offset );
  35070. setArray( a, e, offset );
  35071. updated = true;
  35072. }
  35073. return updated;
  35074. }
  35075. /**
  35076. * Returns a typed array that matches the given data type.
  35077. *
  35078. * @param {String} type - The data type.
  35079. * @return {TypedArray} The typed array.
  35080. */
  35081. _getBufferForType( type ) {
  35082. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  35083. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  35084. return this.buffer;
  35085. }
  35086. }
  35087. /**
  35088. * Sets the values of the second array to the first array.
  35089. *
  35090. * @param {TypedArray} a - The first array.
  35091. * @param {TypedArray} b - The second array.
  35092. * @param {Number} offset - An index offset for the first array.
  35093. */
  35094. function setArray( a, b, offset ) {
  35095. for ( let i = 0, l = b.length; i < l; i ++ ) {
  35096. a[ offset + i ] = b[ i ];
  35097. }
  35098. }
  35099. /**
  35100. * Returns `true` if the given arrays are equal.
  35101. *
  35102. * @param {TypedArray} a - The first array.
  35103. * @param {TypedArray} b - The second array.
  35104. * @param {Number} offset - An index offset for the first array.
  35105. * @return {Boolean} Whether the given arrays are equal or not.
  35106. */
  35107. function arraysEqual( a, b, offset ) {
  35108. for ( let i = 0, l = b.length; i < l; i ++ ) {
  35109. if ( a[ offset + i ] !== b[ i ] ) return false;
  35110. }
  35111. return true;
  35112. }
  35113. let _id$3 = 0;
  35114. /**
  35115. * A special form of uniforms group that represents
  35116. * the individual uniforms as node-based uniforms.
  35117. *
  35118. * @private
  35119. * @augments UniformsGroup
  35120. */
  35121. class NodeUniformsGroup extends UniformsGroup {
  35122. /**
  35123. * Constructs a new node-based uniforms group.
  35124. *
  35125. * @param {String} name - The group's name.
  35126. * @param {UniformGroupNode} groupNode - The uniform group node.
  35127. */
  35128. constructor( name, groupNode ) {
  35129. super( name );
  35130. /**
  35131. * The group's ID.
  35132. *
  35133. * @type {Number}
  35134. */
  35135. this.id = _id$3 ++;
  35136. /**
  35137. * The uniform group node.
  35138. *
  35139. * @type {UniformGroupNode}
  35140. */
  35141. this.groupNode = groupNode;
  35142. /**
  35143. * This flag can be used for type testing.
  35144. *
  35145. * @type {Boolean}
  35146. * @readonly
  35147. * @default true
  35148. */
  35149. this.isNodeUniformsGroup = true;
  35150. }
  35151. }
  35152. let _id$2 = 0;
  35153. /**
  35154. * Represents a sampled texture binding type.
  35155. *
  35156. * @private
  35157. * @augments Binding
  35158. */
  35159. class SampledTexture extends Binding {
  35160. /**
  35161. * Constructs a new sampled texture.
  35162. *
  35163. * @param {String} name - The sampled texture's name.
  35164. * @param {Texture?} texture - The texture this binding is referring to.
  35165. */
  35166. constructor( name, texture ) {
  35167. super( name );
  35168. /**
  35169. * This identifier.
  35170. *
  35171. * @type {Number}
  35172. */
  35173. this.id = _id$2 ++;
  35174. /**
  35175. * The texture this binding is referring to.
  35176. *
  35177. * @type {Texture?}
  35178. */
  35179. this.texture = texture;
  35180. /**
  35181. * The binding's version.
  35182. *
  35183. * @type {Number}
  35184. */
  35185. this.version = texture ? texture.version : 0;
  35186. /**
  35187. * Whether the texture is a storage texture or not.
  35188. *
  35189. * @type {Boolean}
  35190. * @default false
  35191. */
  35192. this.store = false;
  35193. /**
  35194. * The binding's generation which is an additional version
  35195. * qualifier.
  35196. *
  35197. * @type {Number?}
  35198. * @default null
  35199. */
  35200. this.generation = null;
  35201. /**
  35202. * This flag can be used for type testing.
  35203. *
  35204. * @type {Boolean}
  35205. * @readonly
  35206. * @default true
  35207. */
  35208. this.isSampledTexture = true;
  35209. }
  35210. /**
  35211. * Returns `true` whether this binding requires an update for the
  35212. * given generation.
  35213. *
  35214. * @param {Number} generation - The generation.
  35215. * @return {Boolean} Whether an update is required or not.
  35216. */
  35217. needsBindingsUpdate( generation ) {
  35218. const { texture } = this;
  35219. if ( generation !== this.generation ) {
  35220. this.generation = generation;
  35221. return true;
  35222. }
  35223. return texture.isVideoTexture;
  35224. }
  35225. /**
  35226. * Updates the binding.
  35227. *
  35228. * @param {Number} generation - The generation.
  35229. * @return {Boolean} Whether the texture has been updated and must be
  35230. * uploaded to the GPU.
  35231. */
  35232. update() {
  35233. const { texture, version } = this;
  35234. if ( version !== texture.version ) {
  35235. this.version = texture.version;
  35236. return true;
  35237. }
  35238. return false;
  35239. }
  35240. }
  35241. /**
  35242. * A special form of sampled texture binding type.
  35243. * It's texture value is managed by a node object.
  35244. *
  35245. * @private
  35246. * @augments SampledTexture
  35247. */
  35248. class NodeSampledTexture extends SampledTexture {
  35249. /**
  35250. * Constructs a new node-based sampled texture.
  35251. *
  35252. * @param {String} name - The textures's name.
  35253. * @param {TextureNode} textureNode - The texture node.
  35254. * @param {UniformGroupNode} groupNode - The uniform group node.
  35255. * @param {String?} [access=null] - The access type.
  35256. */
  35257. constructor( name, textureNode, groupNode, access = null ) {
  35258. super( name, textureNode ? textureNode.value : null );
  35259. /**
  35260. * The texture node.
  35261. *
  35262. * @type {TextureNode}
  35263. */
  35264. this.textureNode = textureNode;
  35265. /**
  35266. * The uniform group node.
  35267. *
  35268. * @type {UniformGroupNode}
  35269. */
  35270. this.groupNode = groupNode;
  35271. /**
  35272. * The access type.
  35273. *
  35274. * @type {String?}
  35275. * @default null
  35276. */
  35277. this.access = access;
  35278. }
  35279. /**
  35280. * Overwrites the default to additionally check if the node value has changed.
  35281. *
  35282. * @param {Number} generation - The generation.
  35283. * @return {Boolean} Whether an update is required or not.
  35284. */
  35285. needsBindingsUpdate( generation ) {
  35286. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  35287. }
  35288. /**
  35289. * Updates the binding.
  35290. *
  35291. * @param {Number} generation - The generation.
  35292. * @return {Boolean} Whether the texture has been updated and must be
  35293. * uploaded to the GPU.
  35294. */
  35295. update() {
  35296. const { textureNode } = this;
  35297. if ( this.texture !== textureNode.value ) {
  35298. this.texture = textureNode.value;
  35299. return true;
  35300. }
  35301. return super.update();
  35302. }
  35303. }
  35304. /**
  35305. * A special form of sampled cube texture binding type.
  35306. * It's texture value is managed by a node object.
  35307. *
  35308. * @private
  35309. * @augments NodeSampledTexture
  35310. */
  35311. class NodeSampledCubeTexture extends NodeSampledTexture {
  35312. /**
  35313. * Constructs a new node-based sampled cube texture.
  35314. *
  35315. * @param {String} name - The textures's name.
  35316. * @param {TextureNode} textureNode - The texture node.
  35317. * @param {UniformGroupNode} groupNode - The uniform group node.
  35318. * @param {String?} [access=null] - The access type.
  35319. */
  35320. constructor( name, textureNode, groupNode, access = null ) {
  35321. super( name, textureNode, groupNode, access );
  35322. /**
  35323. * This flag can be used for type testing.
  35324. *
  35325. * @type {Boolean}
  35326. * @readonly
  35327. * @default true
  35328. */
  35329. this.isSampledCubeTexture = true;
  35330. }
  35331. }
  35332. /**
  35333. * A special form of sampled 3D texture binding type.
  35334. * It's texture value is managed by a node object.
  35335. *
  35336. * @private
  35337. * @augments NodeSampledTexture
  35338. */
  35339. class NodeSampledTexture3D extends NodeSampledTexture {
  35340. /**
  35341. * Constructs a new node-based sampled 3D texture.
  35342. *
  35343. * @param {String} name - The textures's name.
  35344. * @param {TextureNode} textureNode - The texture node.
  35345. * @param {UniformGroupNode} groupNode - The uniform group node.
  35346. * @param {String?} [access=null] - The access type.
  35347. */
  35348. constructor( name, textureNode, groupNode, access = null ) {
  35349. super( name, textureNode, groupNode, access );
  35350. /**
  35351. * This flag can be used for type testing.
  35352. *
  35353. * @type {Boolean}
  35354. * @readonly
  35355. * @default true
  35356. */
  35357. this.isSampledTexture3D = true;
  35358. }
  35359. }
  35360. const glslMethods = {
  35361. textureDimensions: 'textureSize',
  35362. equals: 'equal'
  35363. };
  35364. const precisionLib = {
  35365. low: 'lowp',
  35366. medium: 'mediump',
  35367. high: 'highp'
  35368. };
  35369. const supports$1 = {
  35370. swizzleAssign: true,
  35371. storageBuffer: false
  35372. };
  35373. const defaultPrecisions = `
  35374. precision highp float;
  35375. precision highp int;
  35376. precision highp sampler2D;
  35377. precision highp sampler3D;
  35378. precision highp samplerCube;
  35379. precision highp sampler2DArray;
  35380. precision highp usampler2D;
  35381. precision highp usampler3D;
  35382. precision highp usamplerCube;
  35383. precision highp usampler2DArray;
  35384. precision highp isampler2D;
  35385. precision highp isampler3D;
  35386. precision highp isamplerCube;
  35387. precision highp isampler2DArray;
  35388. precision lowp sampler2DShadow;
  35389. `;
  35390. class GLSLNodeBuilder extends NodeBuilder {
  35391. constructor( object, renderer ) {
  35392. super( object, renderer, new GLSLNodeParser() );
  35393. this.uniformGroups = {};
  35394. this.transforms = [];
  35395. this.extensions = {};
  35396. this.builtins = { vertex: [], fragment: [], compute: [] };
  35397. this.useComparisonMethod = true;
  35398. }
  35399. needsToWorkingColorSpace( texture ) {
  35400. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  35401. }
  35402. getMethod( method ) {
  35403. return glslMethods[ method ] || method;
  35404. }
  35405. getOutputStructName() {
  35406. return '';
  35407. }
  35408. buildFunctionCode( shaderNode ) {
  35409. const layout = shaderNode.layout;
  35410. const flowData = this.flowShaderNode( shaderNode );
  35411. const parameters = [];
  35412. for ( const input of layout.inputs ) {
  35413. parameters.push( this.getType( input.type ) + ' ' + input.name );
  35414. }
  35415. //
  35416. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  35417. ${ flowData.vars }
  35418. ${ flowData.code }
  35419. return ${ flowData.result };
  35420. }`;
  35421. //
  35422. return code;
  35423. }
  35424. setupPBO( storageBufferNode ) {
  35425. const attribute = storageBufferNode.value;
  35426. if ( attribute.pbo === undefined ) {
  35427. const originalArray = attribute.array;
  35428. const numElements = attribute.count * attribute.itemSize;
  35429. const { itemSize } = attribute;
  35430. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  35431. let format = isInteger ? RedIntegerFormat : RedFormat;
  35432. if ( itemSize === 2 ) {
  35433. format = isInteger ? RGIntegerFormat : RGFormat;
  35434. } else if ( itemSize === 3 ) {
  35435. format = isInteger ? RGBIntegerFormat : RGBFormat;
  35436. } else if ( itemSize === 4 ) {
  35437. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  35438. }
  35439. const typeMap = {
  35440. Float32Array: FloatType,
  35441. Uint8Array: UnsignedByteType,
  35442. Uint16Array: UnsignedShortType,
  35443. Uint32Array: UnsignedIntType,
  35444. Int8Array: ByteType,
  35445. Int16Array: ShortType,
  35446. Int32Array: IntType,
  35447. Uint8ClampedArray: UnsignedByteType,
  35448. };
  35449. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  35450. let height = Math.ceil( ( numElements / itemSize ) / width );
  35451. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  35452. const newSize = width * height * itemSize;
  35453. const newArray = new originalArray.constructor( newSize );
  35454. newArray.set( originalArray, 0 );
  35455. attribute.array = newArray;
  35456. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  35457. pboTexture.needsUpdate = true;
  35458. pboTexture.isPBOTexture = true;
  35459. const pbo = new TextureNode( pboTexture, null, null );
  35460. pbo.setPrecision( 'high' );
  35461. attribute.pboNode = pbo;
  35462. attribute.pbo = pbo.value;
  35463. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  35464. }
  35465. }
  35466. getPropertyName( node, shaderStage = this.shaderStage ) {
  35467. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  35468. return shaderStage.charAt( 0 ) + '_' + node.name;
  35469. }
  35470. return super.getPropertyName( node, shaderStage );
  35471. }
  35472. generatePBO( storageArrayElementNode ) {
  35473. const { node, indexNode } = storageArrayElementNode;
  35474. const attribute = node.value;
  35475. if ( this.renderer.backend.has( attribute ) ) {
  35476. const attributeData = this.renderer.backend.get( attribute );
  35477. attributeData.pbo = attribute.pbo;
  35478. }
  35479. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  35480. const textureName = this.getPropertyName( nodeUniform );
  35481. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  35482. const indexSnippet = indexNode.build( this, 'uint' );
  35483. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  35484. let propertyName = elementNodeData.propertyName;
  35485. if ( propertyName === undefined ) {
  35486. // property element
  35487. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  35488. propertyName = this.getPropertyName( nodeVar );
  35489. // property size
  35490. const bufferNodeData = this.getDataFromNode( node );
  35491. let propertySizeName = bufferNodeData.propertySizeName;
  35492. if ( propertySizeName === undefined ) {
  35493. propertySizeName = propertyName + 'Size';
  35494. this.getVarFromNode( node, propertySizeName, 'uint' );
  35495. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  35496. bufferNodeData.propertySizeName = propertySizeName;
  35497. }
  35498. //
  35499. const { itemSize } = attribute;
  35500. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  35501. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  35502. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  35503. //
  35504. let prefix = 'vec4';
  35505. if ( attribute.pbo.type === UnsignedIntType ) {
  35506. prefix = 'uvec4';
  35507. } else if ( attribute.pbo.type === IntType ) {
  35508. prefix = 'ivec4';
  35509. }
  35510. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  35511. elementNodeData.propertyName = propertyName;
  35512. }
  35513. return propertyName;
  35514. }
  35515. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  35516. if ( depthSnippet ) {
  35517. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  35518. } else {
  35519. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  35520. }
  35521. }
  35522. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  35523. if ( texture.isDepthTexture ) {
  35524. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  35525. } else {
  35526. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  35527. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  35528. }
  35529. }
  35530. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  35531. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  35532. }
  35533. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  35534. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  35535. }
  35536. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  35537. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  35538. }
  35539. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  35540. if ( shaderStage === 'fragment' ) {
  35541. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  35542. } else {
  35543. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  35544. }
  35545. }
  35546. getVars( shaderStage ) {
  35547. const snippets = [];
  35548. const vars = this.vars[ shaderStage ];
  35549. if ( vars !== undefined ) {
  35550. for ( const variable of vars ) {
  35551. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  35552. }
  35553. }
  35554. return snippets.join( '\n\t' );
  35555. }
  35556. getUniforms( shaderStage ) {
  35557. const uniforms = this.uniforms[ shaderStage ];
  35558. const bindingSnippets = [];
  35559. const uniformGroups = {};
  35560. for ( const uniform of uniforms ) {
  35561. let snippet = null;
  35562. let group = false;
  35563. if ( uniform.type === 'texture' ) {
  35564. const texture = uniform.node.value;
  35565. let typePrefix = '';
  35566. if ( texture.isDataTexture === true ) {
  35567. if ( texture.type === UnsignedIntType ) {
  35568. typePrefix = 'u';
  35569. } else if ( texture.type === IntType ) {
  35570. typePrefix = 'i';
  35571. }
  35572. }
  35573. if ( texture.compareFunction ) {
  35574. snippet = `sampler2DShadow ${ uniform.name };`;
  35575. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  35576. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  35577. } else {
  35578. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  35579. }
  35580. } else if ( uniform.type === 'cubeTexture' ) {
  35581. snippet = `samplerCube ${ uniform.name };`;
  35582. } else if ( uniform.type === 'texture3D' ) {
  35583. snippet = `sampler3D ${ uniform.name };`;
  35584. } else if ( uniform.type === 'buffer' ) {
  35585. const bufferNode = uniform.node;
  35586. const bufferType = this.getType( bufferNode.bufferType );
  35587. const bufferCount = bufferNode.bufferCount;
  35588. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  35589. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  35590. } else {
  35591. const vectorType = this.getVectorType( uniform.type );
  35592. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  35593. group = true;
  35594. }
  35595. const precision = uniform.node.precision;
  35596. if ( precision !== null ) {
  35597. snippet = precisionLib[ precision ] + ' ' + snippet;
  35598. }
  35599. if ( group ) {
  35600. snippet = '\t' + snippet;
  35601. const groupName = uniform.groupNode.name;
  35602. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  35603. groupSnippets.push( snippet );
  35604. } else {
  35605. snippet = 'uniform ' + snippet;
  35606. bindingSnippets.push( snippet );
  35607. }
  35608. }
  35609. let output = '';
  35610. for ( const name in uniformGroups ) {
  35611. const groupSnippets = uniformGroups[ name ];
  35612. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  35613. }
  35614. output += bindingSnippets.join( '\n' );
  35615. return output;
  35616. }
  35617. getTypeFromAttribute( attribute ) {
  35618. let nodeType = super.getTypeFromAttribute( attribute );
  35619. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  35620. let dataAttribute = attribute;
  35621. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  35622. const array = dataAttribute.array;
  35623. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  35624. nodeType = nodeType.slice( 1 );
  35625. }
  35626. }
  35627. return nodeType;
  35628. }
  35629. getAttributes( shaderStage ) {
  35630. let snippet = '';
  35631. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  35632. const attributes = this.getAttributesArray();
  35633. let location = 0;
  35634. for ( const attribute of attributes ) {
  35635. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  35636. }
  35637. }
  35638. return snippet;
  35639. }
  35640. getStructMembers( struct ) {
  35641. const snippets = [];
  35642. const members = struct.getMemberTypes();
  35643. for ( let i = 0; i < members.length; i ++ ) {
  35644. const member = members[ i ];
  35645. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  35646. }
  35647. return snippets.join( '\n' );
  35648. }
  35649. getStructs( shaderStage ) {
  35650. const snippets = [];
  35651. const structs = this.structs[ shaderStage ];
  35652. if ( structs.length === 0 ) {
  35653. return 'layout( location = 0 ) out vec4 fragColor;\n';
  35654. }
  35655. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  35656. const struct = structs[ index ];
  35657. let snippet = '\n';
  35658. snippet += this.getStructMembers( struct );
  35659. snippet += '\n';
  35660. snippets.push( snippet );
  35661. }
  35662. return snippets.join( '\n\n' );
  35663. }
  35664. getVaryings( shaderStage ) {
  35665. let snippet = '';
  35666. const varyings = this.varyings;
  35667. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  35668. for ( const varying of varyings ) {
  35669. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  35670. const type = this.getType( varying.type );
  35671. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  35672. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  35673. }
  35674. } else if ( shaderStage === 'fragment' ) {
  35675. for ( const varying of varyings ) {
  35676. if ( varying.needsInterpolation ) {
  35677. const type = this.getType( varying.type );
  35678. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  35679. snippet += `${flat}in ${type} ${varying.name};\n`;
  35680. }
  35681. }
  35682. }
  35683. for ( const builtin of this.builtins[ shaderStage ] ) {
  35684. snippet += `${builtin};\n`;
  35685. }
  35686. return snippet;
  35687. }
  35688. getVertexIndex() {
  35689. return 'uint( gl_VertexID )';
  35690. }
  35691. getInstanceIndex() {
  35692. return 'uint( gl_InstanceID )';
  35693. }
  35694. getInvocationLocalIndex() {
  35695. const workgroupSize = this.object.workgroupSize;
  35696. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  35697. return `uint( gl_InstanceID ) % ${size}u`;
  35698. }
  35699. getDrawIndex() {
  35700. const extensions = this.renderer.backend.extensions;
  35701. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  35702. return 'uint( gl_DrawID )';
  35703. }
  35704. return null;
  35705. }
  35706. getFrontFacing() {
  35707. return 'gl_FrontFacing';
  35708. }
  35709. getFragCoord() {
  35710. return 'gl_FragCoord.xy';
  35711. }
  35712. getFragDepth() {
  35713. return 'gl_FragDepth';
  35714. }
  35715. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  35716. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  35717. if ( map.has( name ) === false ) {
  35718. map.set( name, {
  35719. name,
  35720. behavior
  35721. } );
  35722. }
  35723. }
  35724. getExtensions( shaderStage ) {
  35725. const snippets = [];
  35726. if ( shaderStage === 'vertex' ) {
  35727. const ext = this.renderer.backend.extensions;
  35728. const isBatchedMesh = this.object.isBatchedMesh;
  35729. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  35730. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  35731. }
  35732. }
  35733. const extensions = this.extensions[ shaderStage ];
  35734. if ( extensions !== undefined ) {
  35735. for ( const { name, behavior } of extensions.values() ) {
  35736. snippets.push( `#extension ${name} : ${behavior}` );
  35737. }
  35738. }
  35739. return snippets.join( '\n' );
  35740. }
  35741. getClipDistance() {
  35742. return 'gl_ClipDistance';
  35743. }
  35744. isAvailable( name ) {
  35745. let result = supports$1[ name ];
  35746. if ( result === undefined ) {
  35747. let extensionName;
  35748. result = false;
  35749. switch ( name ) {
  35750. case 'float32Filterable':
  35751. extensionName = 'OES_texture_float_linear';
  35752. break;
  35753. case 'clipDistance':
  35754. extensionName = 'WEBGL_clip_cull_distance';
  35755. break;
  35756. }
  35757. if ( extensionName !== undefined ) {
  35758. const extensions = this.renderer.backend.extensions;
  35759. if ( extensions.has( extensionName ) ) {
  35760. extensions.get( extensionName );
  35761. result = true;
  35762. }
  35763. }
  35764. supports$1[ name ] = result;
  35765. }
  35766. return result;
  35767. }
  35768. isFlipY() {
  35769. return true;
  35770. }
  35771. enableHardwareClipping( planeCount ) {
  35772. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  35773. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  35774. }
  35775. registerTransform( varyingName, attributeNode ) {
  35776. this.transforms.push( { varyingName, attributeNode } );
  35777. }
  35778. getTransforms( /* shaderStage */ ) {
  35779. const transforms = this.transforms;
  35780. let snippet = '';
  35781. for ( let i = 0; i < transforms.length; i ++ ) {
  35782. const transform = transforms[ i ];
  35783. const attributeName = this.getPropertyName( transform.attributeNode );
  35784. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  35785. }
  35786. return snippet;
  35787. }
  35788. _getGLSLUniformStruct( name, vars ) {
  35789. return `
  35790. layout( std140 ) uniform ${name} {
  35791. ${vars}
  35792. };`;
  35793. }
  35794. _getGLSLVertexCode( shaderData ) {
  35795. return `#version 300 es
  35796. ${ this.getSignature() }
  35797. // extensions
  35798. ${shaderData.extensions}
  35799. // precision
  35800. ${ defaultPrecisions }
  35801. // uniforms
  35802. ${shaderData.uniforms}
  35803. // varyings
  35804. ${shaderData.varyings}
  35805. // attributes
  35806. ${shaderData.attributes}
  35807. // codes
  35808. ${shaderData.codes}
  35809. void main() {
  35810. // vars
  35811. ${shaderData.vars}
  35812. // transforms
  35813. ${shaderData.transforms}
  35814. // flow
  35815. ${shaderData.flow}
  35816. gl_PointSize = 1.0;
  35817. }
  35818. `;
  35819. }
  35820. _getGLSLFragmentCode( shaderData ) {
  35821. return `#version 300 es
  35822. ${ this.getSignature() }
  35823. // precision
  35824. ${ defaultPrecisions }
  35825. // uniforms
  35826. ${shaderData.uniforms}
  35827. // varyings
  35828. ${shaderData.varyings}
  35829. // codes
  35830. ${shaderData.codes}
  35831. ${shaderData.structs}
  35832. void main() {
  35833. // vars
  35834. ${shaderData.vars}
  35835. // flow
  35836. ${shaderData.flow}
  35837. }
  35838. `;
  35839. }
  35840. buildCode() {
  35841. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  35842. this.sortBindingGroups();
  35843. for ( const shaderStage in shadersData ) {
  35844. let flow = '// code\n\n';
  35845. flow += this.flowCode[ shaderStage ];
  35846. const flowNodes = this.flowNodes[ shaderStage ];
  35847. const mainNode = flowNodes[ flowNodes.length - 1 ];
  35848. for ( const node of flowNodes ) {
  35849. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  35850. const slotName = node.name;
  35851. if ( slotName ) {
  35852. if ( flow.length > 0 ) flow += '\n';
  35853. flow += `\t// flow -> ${ slotName }\n\t`;
  35854. }
  35855. flow += `${ flowSlotData.code }\n\t`;
  35856. if ( node === mainNode && shaderStage !== 'compute' ) {
  35857. flow += '// result\n\t';
  35858. if ( shaderStage === 'vertex' ) {
  35859. flow += 'gl_Position = ';
  35860. flow += `${ flowSlotData.result };`;
  35861. } else if ( shaderStage === 'fragment' ) {
  35862. if ( ! node.outputNode.isOutputStructNode ) {
  35863. flow += 'fragColor = ';
  35864. flow += `${ flowSlotData.result };`;
  35865. }
  35866. }
  35867. }
  35868. }
  35869. const stageData = shadersData[ shaderStage ];
  35870. stageData.extensions = this.getExtensions( shaderStage );
  35871. stageData.uniforms = this.getUniforms( shaderStage );
  35872. stageData.attributes = this.getAttributes( shaderStage );
  35873. stageData.varyings = this.getVaryings( shaderStage );
  35874. stageData.vars = this.getVars( shaderStage );
  35875. stageData.structs = this.getStructs( shaderStage );
  35876. stageData.codes = this.getCodes( shaderStage );
  35877. stageData.transforms = this.getTransforms( shaderStage );
  35878. stageData.flow = flow;
  35879. }
  35880. if ( this.material !== null ) {
  35881. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  35882. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  35883. } else {
  35884. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  35885. }
  35886. }
  35887. getUniformFromNode( node, type, shaderStage, name = null ) {
  35888. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  35889. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  35890. let uniformGPU = nodeData.uniformGPU;
  35891. if ( uniformGPU === undefined ) {
  35892. const group = node.groupNode;
  35893. const groupName = group.name;
  35894. const bindings = this.getBindGroupArray( groupName, shaderStage );
  35895. if ( type === 'texture' ) {
  35896. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  35897. bindings.push( uniformGPU );
  35898. } else if ( type === 'cubeTexture' ) {
  35899. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  35900. bindings.push( uniformGPU );
  35901. } else if ( type === 'texture3D' ) {
  35902. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  35903. bindings.push( uniformGPU );
  35904. } else if ( type === 'buffer' ) {
  35905. node.name = `NodeBuffer_${ node.id }`;
  35906. uniformNode.name = `buffer${ node.id }`;
  35907. const buffer = new NodeUniformBuffer( node, group );
  35908. buffer.name = node.name;
  35909. bindings.push( buffer );
  35910. uniformGPU = buffer;
  35911. } else {
  35912. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  35913. let uniformsGroup = uniformsStage[ groupName ];
  35914. if ( uniformsGroup === undefined ) {
  35915. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  35916. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  35917. uniformsStage[ groupName ] = uniformsGroup;
  35918. bindings.push( uniformsGroup );
  35919. }
  35920. uniformGPU = this.getNodeUniform( uniformNode, type );
  35921. uniformsGroup.addUniform( uniformGPU );
  35922. }
  35923. nodeData.uniformGPU = uniformGPU;
  35924. }
  35925. return uniformNode;
  35926. }
  35927. }
  35928. let _vector2 = null;
  35929. let _color4 = null;
  35930. /**
  35931. * Most of the rendering related logic is implemented in the
  35932. * {@link module:Renderer} module and related management components.
  35933. * Sometimes it is required though to execute commands which are
  35934. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  35935. * This abstract base class defines an interface that encapsulates
  35936. * all backend-related logic. Derived classes for each backend must
  35937. * implement the interface.
  35938. *
  35939. * @abstract
  35940. * @private
  35941. */
  35942. class Backend {
  35943. /**
  35944. * Constructs a new backend.
  35945. *
  35946. * @param {Object} parameters - An object holding parameters for the backend.
  35947. */
  35948. constructor( parameters = {} ) {
  35949. /**
  35950. * The parameters of the backend.
  35951. *
  35952. * @type {Object}
  35953. */
  35954. this.parameters = Object.assign( {}, parameters );
  35955. /**
  35956. * This weak map holds backend-specific data of objects
  35957. * like textures, attributes or render targets.
  35958. *
  35959. * @type {WeakMap}
  35960. */
  35961. this.data = new WeakMap();
  35962. /**
  35963. * A reference to the renderer.
  35964. *
  35965. * @type {Renderer?}
  35966. * @default null
  35967. */
  35968. this.renderer = null;
  35969. /**
  35970. * A reference to the canvas element the renderer is drawing to.
  35971. *
  35972. * @type {(HTMLCanvasElement|OffscreenCanvas)?}
  35973. * @default null
  35974. */
  35975. this.domElement = null;
  35976. }
  35977. /**
  35978. * Initializes the backend so it is ready for usage. Concrete backends
  35979. * are supposed to implement their rendering context creation and related
  35980. * operations in this method.
  35981. *
  35982. * @async
  35983. * @param {Renderer} renderer - The renderer.
  35984. * @return {Promise} A Promise that resolves when the backend has been initialized.
  35985. */
  35986. async init( renderer ) {
  35987. this.renderer = renderer;
  35988. }
  35989. /**
  35990. * The coordinate system of the backend.
  35991. *
  35992. * @abstract
  35993. * @type {Number}
  35994. * @readonly
  35995. */
  35996. get coordinateSystem() {}
  35997. // render context
  35998. /**
  35999. * This method is executed at the beginning of a render call and
  36000. * can be used by the backend to prepare the state for upcoming
  36001. * draw calls.
  36002. *
  36003. * @abstract
  36004. * @param {RenderContext} renderContext - The render context.
  36005. */
  36006. beginRender( /*renderContext*/ ) {}
  36007. /**
  36008. * This method is executed at the end of a render call and
  36009. * can be used by the backend to finalize work after draw
  36010. * calls.
  36011. *
  36012. * @abstract
  36013. * @param {RenderContext} renderContext - The render context.
  36014. */
  36015. finishRender( /*renderContext*/ ) {}
  36016. /**
  36017. * This method is executed at the beginning of a compute call and
  36018. * can be used by the backend to prepare the state for upcoming
  36019. * compute tasks.
  36020. *
  36021. * @abstract
  36022. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  36023. */
  36024. beginCompute( /*computeGroup*/ ) {}
  36025. /**
  36026. * This method is executed at the end of a compute call and
  36027. * can be used by the backend to finalize work after compute
  36028. * tasks.
  36029. *
  36030. * @abstract
  36031. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  36032. */
  36033. finishCompute( /*computeGroup*/ ) {}
  36034. // render object
  36035. /**
  36036. * Executes a draw command for the given render object.
  36037. *
  36038. * @abstract
  36039. * @param {RenderObject} renderObject - The render object to draw.
  36040. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  36041. */
  36042. draw( /*renderObject, info*/ ) { }
  36043. // compute node
  36044. /**
  36045. * Executes a compute command for the given compute node.
  36046. *
  36047. * @abstract
  36048. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  36049. * @param {Node} computeNode - The compute node.
  36050. * @param {Array<BindGroup>} bindings - The bindings.
  36051. * @param {ComputePipeline} computePipeline - The compute pipeline.
  36052. */
  36053. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  36054. // program
  36055. /**
  36056. * Creates a shader program from the given programmable stage.
  36057. *
  36058. * @abstract
  36059. * @param {ProgrammableStage} program - The programmable stage.
  36060. */
  36061. createProgram( /*program*/ ) { }
  36062. /**
  36063. * Destroys the shader program of the given programmable stage.
  36064. *
  36065. * @abstract
  36066. * @param {ProgrammableStage} program - The programmable stage.
  36067. */
  36068. destroyProgram( /*program*/ ) { }
  36069. // bindings
  36070. /**
  36071. * Creates bindings from the given bind group definition.
  36072. *
  36073. * @abstract
  36074. * @param {BindGroup} bindGroup - The bind group.
  36075. * @param {Array<BindGroup>} bindings - Array of bind groups.
  36076. * @param {Number} cacheIndex - The cache index.
  36077. * @param {Number} version - The version.
  36078. */
  36079. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  36080. /**
  36081. * Updates the given bind group definition.
  36082. *
  36083. * @abstract
  36084. * @param {BindGroup} bindGroup - The bind group.
  36085. * @param {Array<BindGroup>} bindings - Array of bind groups.
  36086. * @param {Number} cacheIndex - The cache index.
  36087. * @param {Number} version - The version.
  36088. */
  36089. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  36090. /**
  36091. * Updates a buffer binding.
  36092. *
  36093. * @abstract
  36094. * @param {Buffer} binding - The buffer binding to update.
  36095. */
  36096. updateBinding( /*binding*/ ) { }
  36097. // pipeline
  36098. /**
  36099. * Creates a render pipeline for the given render object.
  36100. *
  36101. * @abstract
  36102. * @param {RenderObject} renderObject - The render object.
  36103. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  36104. */
  36105. createRenderPipeline( /*renderObject, promises*/ ) { }
  36106. /**
  36107. * Creates a compute pipeline for the given compute node.
  36108. *
  36109. * @abstract
  36110. * @param {ComputePipeline} computePipeline - The compute pipeline.
  36111. * @param {Array<BindGroup>} bindings - The bindings.
  36112. */
  36113. createComputePipeline( /*computePipeline, bindings*/ ) { }
  36114. // cache key
  36115. /**
  36116. * Returns `true` if the render pipeline requires an update.
  36117. *
  36118. * @abstract
  36119. * @param {RenderObject} renderObject - The render object.
  36120. * @return {Boolean} Whether the render pipeline requires an update or not.
  36121. */
  36122. needsRenderUpdate( /*renderObject*/ ) { }
  36123. /**
  36124. * Returns a cache key that is used to identify render pipelines.
  36125. *
  36126. * @abstract
  36127. * @param {RenderObject} renderObject - The render object.
  36128. * @return {String} The cache key.
  36129. */
  36130. getRenderCacheKey( /*renderObject*/ ) { }
  36131. // node builder
  36132. /**
  36133. * Returns a node builder for the given render object.
  36134. *
  36135. * @abstract
  36136. * @param {RenderObject} renderObject - The render object.
  36137. * @param {Renderer} renderer - The renderer.
  36138. * @return {NodeBuilder} The node builder.
  36139. */
  36140. createNodeBuilder( /*renderObject, renderer*/ ) { }
  36141. // textures
  36142. /**
  36143. * Creates a sampler for the given texture.
  36144. *
  36145. * @abstract
  36146. * @param {Texture} texture - The texture to create the sampler for.
  36147. */
  36148. createSampler( /*texture*/ ) { }
  36149. /**
  36150. * Destroys the sampler for the given texture.
  36151. *
  36152. * @abstract
  36153. * @param {Texture} texture - The texture to destroy the sampler for.
  36154. */
  36155. destroySampler( /*texture*/ ) {}
  36156. /**
  36157. * Creates a default texture for the given texture that can be used
  36158. * as a placeholder until the actual texture is ready for usage.
  36159. *
  36160. * @abstract
  36161. * @param {Texture} texture - The texture to create a default texture for.
  36162. */
  36163. createDefaultTexture( /*texture*/ ) { }
  36164. /**
  36165. * Defines a texture on the GPU for the given texture object.
  36166. *
  36167. * @abstract
  36168. * @param {Texture} texture - The texture.
  36169. * @param {Object} [options={}] - Optional configuration parameter.
  36170. */
  36171. createTexture( /*texture, options={}*/ ) { }
  36172. /**
  36173. * Uploads the updated texture data to the GPU.
  36174. *
  36175. * @abstract
  36176. * @param {Texture} texture - The texture.
  36177. * @param {Object} [options={}] - Optional configuration parameter.
  36178. */
  36179. updateTexture( /*texture, options = {}*/ ) { }
  36180. /**
  36181. * Generates mipmaps for the given texture
  36182. *
  36183. * @abstract
  36184. * @param {Texture} texture - The texture.
  36185. */
  36186. generateMipmaps( /*texture*/ ) { }
  36187. /**
  36188. * Destroys the GPU data for the given texture object.
  36189. *
  36190. * @abstract
  36191. * @param {Texture} texture - The texture.
  36192. */
  36193. destroyTexture( /*texture*/ ) { }
  36194. /**
  36195. * Returns texture data as a typed array.
  36196. *
  36197. * @abstract
  36198. * @param {Texture} texture - The texture to copy.
  36199. * @param {Number} x - The x coordinate of the copy origin.
  36200. * @param {Number} y - The y coordinate of the copy origin.
  36201. * @param {Number} width - The width of the copy.
  36202. * @param {Number} height - The height of the copy.
  36203. * @param {Number} faceIndex - The face index.
  36204. * @return {TypedArray} The texture data as a typed array.
  36205. */
  36206. copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  36207. /**
  36208. * Copies data of the given source texture to the given destination texture.
  36209. *
  36210. * @abstract
  36211. * @param {Texture} srcTexture - The source texture.
  36212. * @param {Texture} dstTexture - The destination texture.
  36213. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  36214. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  36215. * @param {Number} [level=0] - The mip level to copy.
  36216. */
  36217. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0*/ ) {}
  36218. /**
  36219. * Copies the current bound framebuffer to the given texture.
  36220. *
  36221. * @abstract
  36222. * @param {Texture} texture - The destination texture.
  36223. * @param {RenderContext} renderContext - The render context.
  36224. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  36225. */
  36226. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  36227. // attributes
  36228. /**
  36229. * Creates the buffer of a shader attribute.
  36230. *
  36231. * @abstract
  36232. * @param {BufferAttribute} attribute - The buffer attribute.
  36233. */
  36234. createAttribute( /*attribute*/ ) { }
  36235. /**
  36236. * Creates the buffer of an indexed shader attribute.
  36237. *
  36238. * @abstract
  36239. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  36240. */
  36241. createIndexAttribute( /*attribute*/ ) { }
  36242. /**
  36243. * Creates the buffer of a storage attribute.
  36244. *
  36245. * @abstract
  36246. * @param {BufferAttribute} attribute - The buffer attribute.
  36247. */
  36248. createStorageAttribute( /*attribute*/ ) { }
  36249. /**
  36250. * Updates the buffer of a shader attribute.
  36251. *
  36252. * @abstract
  36253. * @param {BufferAttribute} attribute - The buffer attribute to update.
  36254. */
  36255. updateAttribute( /*attribute*/ ) { }
  36256. /**
  36257. * Destroys the buffer of a shader attribute.
  36258. *
  36259. * @abstract
  36260. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  36261. */
  36262. destroyAttribute( /*attribute*/ ) { }
  36263. // canvas
  36264. /**
  36265. * Returns the backend's rendering context.
  36266. *
  36267. * @abstract
  36268. * @return {Object} The rendering context.
  36269. */
  36270. getContext() { }
  36271. /**
  36272. * Backends can use this method if they have to run
  36273. * logic when the renderer gets resized.
  36274. *
  36275. * @abstract
  36276. */
  36277. updateSize() { }
  36278. /**
  36279. * Updates the viewport with the values from the given render context.
  36280. *
  36281. * @abstract
  36282. * @param {RenderContext} renderContext - The render context.
  36283. */
  36284. updateViewport( /*renderContext*/ ) {}
  36285. // utils
  36286. /**
  36287. * Returns `true` if the given 3D object is fully occluded by other
  36288. * 3D objects in the scene. Backends must implement this method by using
  36289. * a Occlusion Query API.
  36290. *
  36291. * @abstract
  36292. * @param {RenderContext} renderContext - The render context.
  36293. * @param {Object3D} object - The 3D object to test.
  36294. * @return {Boolean} Whether the 3D object is fully occluded or not.
  36295. */
  36296. isOccluded( /*renderContext, object*/ ) {}
  36297. /**
  36298. * Resolves the time stamp for the given render context and type.
  36299. *
  36300. * @async
  36301. * @abstract
  36302. * @param {RenderContext} renderContext - The render context.
  36303. * @param {String} type - The render context.
  36304. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  36305. */
  36306. async resolveTimestampAsync( /*renderContext, type*/ ) { }
  36307. /**
  36308. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  36309. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  36310. *
  36311. * @async
  36312. * @abstract
  36313. * @return {Promise} A Promise that resolves when synchronization has been finished.
  36314. */
  36315. async waitForGPU() {}
  36316. /**
  36317. * Checks if the given feature is supported by the backend.
  36318. *
  36319. * @async
  36320. * @abstract
  36321. * @param {String} name - The feature's name.
  36322. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  36323. */
  36324. async hasFeatureAsync( /*name*/ ) { }
  36325. /**
  36326. * Checks if the given feature is supported by the backend.
  36327. *
  36328. * @abstract
  36329. * @param {String} name - The feature's name.
  36330. * @return {Boolean} Whether the feature is supported or not.
  36331. */
  36332. hasFeature( /*name*/ ) {}
  36333. /**
  36334. * Returns the maximum anisotropy texture filtering value.
  36335. *
  36336. * @abstract
  36337. * @return {Number} The maximum anisotropy texture filtering value.
  36338. */
  36339. getMaxAnisotropy() {}
  36340. /**
  36341. * Returns the drawing buffer size.
  36342. *
  36343. * @return {Vector2} The drawing buffer size.
  36344. */
  36345. getDrawingBufferSize() {
  36346. _vector2 = _vector2 || new Vector2();
  36347. return this.renderer.getDrawingBufferSize( _vector2 );
  36348. }
  36349. /**
  36350. * Defines the scissor test.
  36351. *
  36352. * @abstract
  36353. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  36354. */
  36355. setScissorTest( /*boolean*/ ) { }
  36356. /**
  36357. * Returns the clear color and alpha into a single
  36358. * color object.
  36359. *
  36360. * @return {Color4} The clear color.
  36361. */
  36362. getClearColor() {
  36363. const renderer = this.renderer;
  36364. _color4 = _color4 || new Color4();
  36365. renderer.getClearColor( _color4 );
  36366. _color4.getRGB( _color4, this.renderer.currentColorSpace );
  36367. return _color4;
  36368. }
  36369. /**
  36370. * Returns the DOM element. If no DOM element exists, the backend
  36371. * creates a new one.
  36372. *
  36373. * @return {HTMLCanvasElement} The DOM element.
  36374. */
  36375. getDomElement() {
  36376. let domElement = this.domElement;
  36377. if ( domElement === null ) {
  36378. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  36379. // OffscreenCanvas does not have setAttribute, see #22811
  36380. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  36381. this.domElement = domElement;
  36382. }
  36383. return domElement;
  36384. }
  36385. /**
  36386. * Sets a dictionary for the given object into the
  36387. * internal data structure.
  36388. *
  36389. * @param {Object} object - The object.
  36390. * @param {Object} value - The dictionary to set.
  36391. */
  36392. set( object, value ) {
  36393. this.data.set( object, value );
  36394. }
  36395. /**
  36396. * Returns the dictionary for the given object.
  36397. *
  36398. * @param {Object} object - The object.
  36399. * @return {Object} The object's dictionary.
  36400. */
  36401. get( object ) {
  36402. let map = this.data.get( object );
  36403. if ( map === undefined ) {
  36404. map = {};
  36405. this.data.set( object, map );
  36406. }
  36407. return map;
  36408. }
  36409. /**
  36410. * Checks if the given object has a dictionary
  36411. * with data defined.
  36412. *
  36413. * @param {Object} object - The object.
  36414. * @return {Boolean} Whether a dictionary for the given object as been defined or not.
  36415. */
  36416. has( object ) {
  36417. return this.data.has( object );
  36418. }
  36419. /**
  36420. * Deletes an object from the internal data structure.
  36421. *
  36422. * @param {Object} object - The object to delete.
  36423. */
  36424. delete( object ) {
  36425. this.data.delete( object );
  36426. }
  36427. /**
  36428. * Frees internal resources.
  36429. *
  36430. * @abstract
  36431. */
  36432. dispose() { }
  36433. }
  36434. let _id$1 = 0;
  36435. class DualAttributeData {
  36436. constructor( attributeData, dualBuffer ) {
  36437. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  36438. this.type = attributeData.type;
  36439. this.bufferType = attributeData.bufferType;
  36440. this.pbo = attributeData.pbo;
  36441. this.byteLength = attributeData.byteLength;
  36442. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  36443. this.version = attributeData.version;
  36444. this.isInteger = attributeData.isInteger;
  36445. this.activeBufferIndex = 0;
  36446. this.baseId = attributeData.id;
  36447. }
  36448. get id() {
  36449. return `${ this.baseId }|${ this.activeBufferIndex }`;
  36450. }
  36451. get bufferGPU() {
  36452. return this.buffers[ this.activeBufferIndex ];
  36453. }
  36454. get transformBuffer() {
  36455. return this.buffers[ this.activeBufferIndex ^ 1 ];
  36456. }
  36457. switchBuffers() {
  36458. this.activeBufferIndex ^= 1;
  36459. }
  36460. }
  36461. class WebGLAttributeUtils {
  36462. constructor( backend ) {
  36463. this.backend = backend;
  36464. }
  36465. createAttribute( attribute, bufferType ) {
  36466. const backend = this.backend;
  36467. const { gl } = backend;
  36468. const array = attribute.array;
  36469. const usage = attribute.usage || gl.STATIC_DRAW;
  36470. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  36471. const bufferData = backend.get( bufferAttribute );
  36472. let bufferGPU = bufferData.bufferGPU;
  36473. if ( bufferGPU === undefined ) {
  36474. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  36475. bufferData.bufferGPU = bufferGPU;
  36476. bufferData.bufferType = bufferType;
  36477. bufferData.version = bufferAttribute.version;
  36478. }
  36479. //attribute.onUploadCallback();
  36480. let type;
  36481. if ( array instanceof Float32Array ) {
  36482. type = gl.FLOAT;
  36483. } else if ( array instanceof Uint16Array ) {
  36484. if ( attribute.isFloat16BufferAttribute ) {
  36485. type = gl.HALF_FLOAT;
  36486. } else {
  36487. type = gl.UNSIGNED_SHORT;
  36488. }
  36489. } else if ( array instanceof Int16Array ) {
  36490. type = gl.SHORT;
  36491. } else if ( array instanceof Uint32Array ) {
  36492. type = gl.UNSIGNED_INT;
  36493. } else if ( array instanceof Int32Array ) {
  36494. type = gl.INT;
  36495. } else if ( array instanceof Int8Array ) {
  36496. type = gl.BYTE;
  36497. } else if ( array instanceof Uint8Array ) {
  36498. type = gl.UNSIGNED_BYTE;
  36499. } else if ( array instanceof Uint8ClampedArray ) {
  36500. type = gl.UNSIGNED_BYTE;
  36501. } else {
  36502. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  36503. }
  36504. let attributeData = {
  36505. bufferGPU,
  36506. bufferType,
  36507. type,
  36508. byteLength: array.byteLength,
  36509. bytesPerElement: array.BYTES_PER_ELEMENT,
  36510. version: attribute.version,
  36511. pbo: attribute.pbo,
  36512. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  36513. id: _id$1 ++
  36514. };
  36515. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  36516. // create buffer for transform feedback use
  36517. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  36518. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  36519. }
  36520. backend.set( attribute, attributeData );
  36521. }
  36522. updateAttribute( attribute ) {
  36523. const backend = this.backend;
  36524. const { gl } = backend;
  36525. const array = attribute.array;
  36526. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  36527. const bufferData = backend.get( bufferAttribute );
  36528. const bufferType = bufferData.bufferType;
  36529. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  36530. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  36531. if ( updateRanges.length === 0 ) {
  36532. // Not using update ranges
  36533. gl.bufferSubData( bufferType, 0, array );
  36534. } else {
  36535. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  36536. const range = updateRanges[ i ];
  36537. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  36538. array, range.start, range.count );
  36539. }
  36540. bufferAttribute.clearUpdateRanges();
  36541. }
  36542. gl.bindBuffer( bufferType, null );
  36543. bufferData.version = bufferAttribute.version;
  36544. }
  36545. destroyAttribute( attribute ) {
  36546. const backend = this.backend;
  36547. const { gl } = backend;
  36548. if ( attribute.isInterleavedBufferAttribute ) {
  36549. backend.delete( attribute.data );
  36550. }
  36551. const attributeData = backend.get( attribute );
  36552. gl.deleteBuffer( attributeData.bufferGPU );
  36553. backend.delete( attribute );
  36554. }
  36555. async getArrayBufferAsync( attribute ) {
  36556. const backend = this.backend;
  36557. const { gl } = backend;
  36558. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  36559. const { bufferGPU } = backend.get( bufferAttribute );
  36560. const array = attribute.array;
  36561. const byteLength = array.byteLength;
  36562. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  36563. const writeBuffer = gl.createBuffer();
  36564. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  36565. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  36566. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  36567. await backend.utils._clientWaitAsync();
  36568. const dstBuffer = new attribute.array.constructor( array.length );
  36569. // Ensure the buffer is bound before reading
  36570. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  36571. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  36572. gl.deleteBuffer( writeBuffer );
  36573. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  36574. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  36575. return dstBuffer.buffer;
  36576. }
  36577. _createBuffer( gl, bufferType, array, usage ) {
  36578. const bufferGPU = gl.createBuffer();
  36579. gl.bindBuffer( bufferType, bufferGPU );
  36580. gl.bufferData( bufferType, array, usage );
  36581. gl.bindBuffer( bufferType, null );
  36582. return bufferGPU;
  36583. }
  36584. }
  36585. let initialized$1 = false, equationToGL, factorToGL;
  36586. class WebGLState {
  36587. constructor( backend ) {
  36588. this.backend = backend;
  36589. this.gl = this.backend.gl;
  36590. this.enabled = {};
  36591. this.currentFlipSided = null;
  36592. this.currentCullFace = null;
  36593. this.currentProgram = null;
  36594. this.currentBlendingEnabled = false;
  36595. this.currentBlending = null;
  36596. this.currentBlendSrc = null;
  36597. this.currentBlendDst = null;
  36598. this.currentBlendSrcAlpha = null;
  36599. this.currentBlendDstAlpha = null;
  36600. this.currentPremultipledAlpha = null;
  36601. this.currentPolygonOffsetFactor = null;
  36602. this.currentPolygonOffsetUnits = null;
  36603. this.currentColorMask = null;
  36604. this.currentDepthFunc = null;
  36605. this.currentDepthMask = null;
  36606. this.currentStencilFunc = null;
  36607. this.currentStencilRef = null;
  36608. this.currentStencilFuncMask = null;
  36609. this.currentStencilFail = null;
  36610. this.currentStencilZFail = null;
  36611. this.currentStencilZPass = null;
  36612. this.currentStencilMask = null;
  36613. this.currentLineWidth = null;
  36614. this.currentClippingPlanes = 0;
  36615. this.currentBoundFramebuffers = {};
  36616. this.currentDrawbuffers = new WeakMap();
  36617. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  36618. this.currentTextureSlot = null;
  36619. this.currentBoundTextures = {};
  36620. this.currentBoundBufferBases = {};
  36621. if ( initialized$1 === false ) {
  36622. this._init( this.gl );
  36623. initialized$1 = true;
  36624. }
  36625. }
  36626. _init( gl ) {
  36627. // Store only WebGL constants here.
  36628. equationToGL = {
  36629. [ AddEquation ]: gl.FUNC_ADD,
  36630. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  36631. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  36632. };
  36633. factorToGL = {
  36634. [ ZeroFactor ]: gl.ZERO,
  36635. [ OneFactor ]: gl.ONE,
  36636. [ SrcColorFactor ]: gl.SRC_COLOR,
  36637. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  36638. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  36639. [ DstColorFactor ]: gl.DST_COLOR,
  36640. [ DstAlphaFactor ]: gl.DST_ALPHA,
  36641. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  36642. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  36643. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  36644. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  36645. };
  36646. }
  36647. enable( id ) {
  36648. const { enabled } = this;
  36649. if ( enabled[ id ] !== true ) {
  36650. this.gl.enable( id );
  36651. enabled[ id ] = true;
  36652. }
  36653. }
  36654. disable( id ) {
  36655. const { enabled } = this;
  36656. if ( enabled[ id ] !== false ) {
  36657. this.gl.disable( id );
  36658. enabled[ id ] = false;
  36659. }
  36660. }
  36661. setFlipSided( flipSided ) {
  36662. if ( this.currentFlipSided !== flipSided ) {
  36663. const { gl } = this;
  36664. if ( flipSided ) {
  36665. gl.frontFace( gl.CW );
  36666. } else {
  36667. gl.frontFace( gl.CCW );
  36668. }
  36669. this.currentFlipSided = flipSided;
  36670. }
  36671. }
  36672. setCullFace( cullFace ) {
  36673. const { gl } = this;
  36674. if ( cullFace !== CullFaceNone ) {
  36675. this.enable( gl.CULL_FACE );
  36676. if ( cullFace !== this.currentCullFace ) {
  36677. if ( cullFace === CullFaceBack ) {
  36678. gl.cullFace( gl.BACK );
  36679. } else if ( cullFace === CullFaceFront ) {
  36680. gl.cullFace( gl.FRONT );
  36681. } else {
  36682. gl.cullFace( gl.FRONT_AND_BACK );
  36683. }
  36684. }
  36685. } else {
  36686. this.disable( gl.CULL_FACE );
  36687. }
  36688. this.currentCullFace = cullFace;
  36689. }
  36690. setLineWidth( width ) {
  36691. const { currentLineWidth, gl } = this;
  36692. if ( width !== currentLineWidth ) {
  36693. gl.lineWidth( width );
  36694. this.currentLineWidth = width;
  36695. }
  36696. }
  36697. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  36698. const { gl } = this;
  36699. if ( blending === NoBlending ) {
  36700. if ( this.currentBlendingEnabled === true ) {
  36701. this.disable( gl.BLEND );
  36702. this.currentBlendingEnabled = false;
  36703. }
  36704. return;
  36705. }
  36706. if ( this.currentBlendingEnabled === false ) {
  36707. this.enable( gl.BLEND );
  36708. this.currentBlendingEnabled = true;
  36709. }
  36710. if ( blending !== CustomBlending ) {
  36711. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  36712. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  36713. gl.blendEquation( gl.FUNC_ADD );
  36714. this.currentBlendEquation = AddEquation;
  36715. this.currentBlendEquationAlpha = AddEquation;
  36716. }
  36717. if ( premultipliedAlpha ) {
  36718. switch ( blending ) {
  36719. case NormalBlending:
  36720. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  36721. break;
  36722. case AdditiveBlending:
  36723. gl.blendFunc( gl.ONE, gl.ONE );
  36724. break;
  36725. case SubtractiveBlending:
  36726. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  36727. break;
  36728. case MultiplyBlending:
  36729. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  36730. break;
  36731. default:
  36732. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  36733. break;
  36734. }
  36735. } else {
  36736. switch ( blending ) {
  36737. case NormalBlending:
  36738. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  36739. break;
  36740. case AdditiveBlending:
  36741. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  36742. break;
  36743. case SubtractiveBlending:
  36744. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  36745. break;
  36746. case MultiplyBlending:
  36747. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  36748. break;
  36749. default:
  36750. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  36751. break;
  36752. }
  36753. }
  36754. this.currentBlendSrc = null;
  36755. this.currentBlendDst = null;
  36756. this.currentBlendSrcAlpha = null;
  36757. this.currentBlendDstAlpha = null;
  36758. this.currentBlending = blending;
  36759. this.currentPremultipledAlpha = premultipliedAlpha;
  36760. }
  36761. return;
  36762. }
  36763. // custom blending
  36764. blendEquationAlpha = blendEquationAlpha || blendEquation;
  36765. blendSrcAlpha = blendSrcAlpha || blendSrc;
  36766. blendDstAlpha = blendDstAlpha || blendDst;
  36767. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  36768. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  36769. this.currentBlendEquation = blendEquation;
  36770. this.currentBlendEquationAlpha = blendEquationAlpha;
  36771. }
  36772. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  36773. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  36774. this.currentBlendSrc = blendSrc;
  36775. this.currentBlendDst = blendDst;
  36776. this.currentBlendSrcAlpha = blendSrcAlpha;
  36777. this.currentBlendDstAlpha = blendDstAlpha;
  36778. }
  36779. this.currentBlending = blending;
  36780. this.currentPremultipledAlpha = false;
  36781. }
  36782. setColorMask( colorMask ) {
  36783. if ( this.currentColorMask !== colorMask ) {
  36784. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  36785. this.currentColorMask = colorMask;
  36786. }
  36787. }
  36788. setDepthTest( depthTest ) {
  36789. const { gl } = this;
  36790. if ( depthTest ) {
  36791. this.enable( gl.DEPTH_TEST );
  36792. } else {
  36793. this.disable( gl.DEPTH_TEST );
  36794. }
  36795. }
  36796. setDepthMask( depthMask ) {
  36797. if ( this.currentDepthMask !== depthMask ) {
  36798. this.gl.depthMask( depthMask );
  36799. this.currentDepthMask = depthMask;
  36800. }
  36801. }
  36802. setDepthFunc( depthFunc ) {
  36803. if ( this.currentDepthFunc !== depthFunc ) {
  36804. const { gl } = this;
  36805. switch ( depthFunc ) {
  36806. case NeverDepth:
  36807. gl.depthFunc( gl.NEVER );
  36808. break;
  36809. case AlwaysDepth:
  36810. gl.depthFunc( gl.ALWAYS );
  36811. break;
  36812. case LessDepth:
  36813. gl.depthFunc( gl.LESS );
  36814. break;
  36815. case LessEqualDepth:
  36816. gl.depthFunc( gl.LEQUAL );
  36817. break;
  36818. case EqualDepth:
  36819. gl.depthFunc( gl.EQUAL );
  36820. break;
  36821. case GreaterEqualDepth:
  36822. gl.depthFunc( gl.GEQUAL );
  36823. break;
  36824. case GreaterDepth:
  36825. gl.depthFunc( gl.GREATER );
  36826. break;
  36827. case NotEqualDepth:
  36828. gl.depthFunc( gl.NOTEQUAL );
  36829. break;
  36830. default:
  36831. gl.depthFunc( gl.LEQUAL );
  36832. }
  36833. this.currentDepthFunc = depthFunc;
  36834. }
  36835. }
  36836. setStencilTest( stencilTest ) {
  36837. const { gl } = this;
  36838. if ( stencilTest ) {
  36839. this.enable( gl.STENCIL_TEST );
  36840. } else {
  36841. this.disable( gl.STENCIL_TEST );
  36842. }
  36843. }
  36844. setStencilMask( stencilMask ) {
  36845. if ( this.currentStencilMask !== stencilMask ) {
  36846. this.gl.stencilMask( stencilMask );
  36847. this.currentStencilMask = stencilMask;
  36848. }
  36849. }
  36850. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  36851. if ( this.currentStencilFunc !== stencilFunc ||
  36852. this.currentStencilRef !== stencilRef ||
  36853. this.currentStencilFuncMask !== stencilMask ) {
  36854. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  36855. this.currentStencilFunc = stencilFunc;
  36856. this.currentStencilRef = stencilRef;
  36857. this.currentStencilFuncMask = stencilMask;
  36858. }
  36859. }
  36860. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  36861. if ( this.currentStencilFail !== stencilFail ||
  36862. this.currentStencilZFail !== stencilZFail ||
  36863. this.currentStencilZPass !== stencilZPass ) {
  36864. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  36865. this.currentStencilFail = stencilFail;
  36866. this.currentStencilZFail = stencilZFail;
  36867. this.currentStencilZPass = stencilZPass;
  36868. }
  36869. }
  36870. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  36871. const { gl } = this;
  36872. material.side === DoubleSide
  36873. ? this.disable( gl.CULL_FACE )
  36874. : this.enable( gl.CULL_FACE );
  36875. let flipSided = ( material.side === BackSide );
  36876. if ( frontFaceCW ) flipSided = ! flipSided;
  36877. this.setFlipSided( flipSided );
  36878. ( material.blending === NormalBlending && material.transparent === false )
  36879. ? this.setBlending( NoBlending )
  36880. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  36881. this.setDepthFunc( material.depthFunc );
  36882. this.setDepthTest( material.depthTest );
  36883. this.setDepthMask( material.depthWrite );
  36884. this.setColorMask( material.colorWrite );
  36885. const stencilWrite = material.stencilWrite;
  36886. this.setStencilTest( stencilWrite );
  36887. if ( stencilWrite ) {
  36888. this.setStencilMask( material.stencilWriteMask );
  36889. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  36890. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  36891. }
  36892. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  36893. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  36894. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  36895. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  36896. if ( hardwareClippingPlanes > 0 ) {
  36897. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  36898. const CLIP_DISTANCE0_WEBGL = 0x3000;
  36899. for ( let i = 0; i < 8; i ++ ) {
  36900. if ( i < hardwareClippingPlanes ) {
  36901. this.enable( CLIP_DISTANCE0_WEBGL + i );
  36902. } else {
  36903. this.disable( CLIP_DISTANCE0_WEBGL + i );
  36904. }
  36905. }
  36906. }
  36907. }
  36908. }
  36909. setPolygonOffset( polygonOffset, factor, units ) {
  36910. const { gl } = this;
  36911. if ( polygonOffset ) {
  36912. this.enable( gl.POLYGON_OFFSET_FILL );
  36913. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  36914. gl.polygonOffset( factor, units );
  36915. this.currentPolygonOffsetFactor = factor;
  36916. this.currentPolygonOffsetUnits = units;
  36917. }
  36918. } else {
  36919. this.disable( gl.POLYGON_OFFSET_FILL );
  36920. }
  36921. }
  36922. useProgram( program ) {
  36923. if ( this.currentProgram !== program ) {
  36924. this.gl.useProgram( program );
  36925. this.currentProgram = program;
  36926. return true;
  36927. }
  36928. return false;
  36929. }
  36930. // framebuffer
  36931. bindFramebuffer( target, framebuffer ) {
  36932. const { gl, currentBoundFramebuffers } = this;
  36933. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  36934. gl.bindFramebuffer( target, framebuffer );
  36935. currentBoundFramebuffers[ target ] = framebuffer;
  36936. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  36937. if ( target === gl.DRAW_FRAMEBUFFER ) {
  36938. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  36939. }
  36940. if ( target === gl.FRAMEBUFFER ) {
  36941. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  36942. }
  36943. return true;
  36944. }
  36945. return false;
  36946. }
  36947. drawBuffers( renderContext, framebuffer ) {
  36948. const { gl } = this;
  36949. let drawBuffers = [];
  36950. let needsUpdate = false;
  36951. if ( renderContext.textures !== null ) {
  36952. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  36953. if ( drawBuffers === undefined ) {
  36954. drawBuffers = [];
  36955. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  36956. }
  36957. const textures = renderContext.textures;
  36958. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  36959. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  36960. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  36961. }
  36962. drawBuffers.length = textures.length;
  36963. needsUpdate = true;
  36964. }
  36965. } else {
  36966. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  36967. drawBuffers[ 0 ] = gl.BACK;
  36968. needsUpdate = true;
  36969. }
  36970. }
  36971. if ( needsUpdate ) {
  36972. gl.drawBuffers( drawBuffers );
  36973. }
  36974. }
  36975. // texture
  36976. activeTexture( webglSlot ) {
  36977. const { gl, currentTextureSlot, maxTextures } = this;
  36978. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  36979. if ( currentTextureSlot !== webglSlot ) {
  36980. gl.activeTexture( webglSlot );
  36981. this.currentTextureSlot = webglSlot;
  36982. }
  36983. }
  36984. bindTexture( webglType, webglTexture, webglSlot ) {
  36985. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  36986. if ( webglSlot === undefined ) {
  36987. if ( currentTextureSlot === null ) {
  36988. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  36989. } else {
  36990. webglSlot = currentTextureSlot;
  36991. }
  36992. }
  36993. let boundTexture = currentBoundTextures[ webglSlot ];
  36994. if ( boundTexture === undefined ) {
  36995. boundTexture = { type: undefined, texture: undefined };
  36996. currentBoundTextures[ webglSlot ] = boundTexture;
  36997. }
  36998. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  36999. if ( currentTextureSlot !== webglSlot ) {
  37000. gl.activeTexture( webglSlot );
  37001. this.currentTextureSlot = webglSlot;
  37002. }
  37003. gl.bindTexture( webglType, webglTexture );
  37004. boundTexture.type = webglType;
  37005. boundTexture.texture = webglTexture;
  37006. }
  37007. }
  37008. bindBufferBase( target, index, buffer ) {
  37009. const { gl } = this;
  37010. const key = `${target}-${index}`;
  37011. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  37012. gl.bindBufferBase( target, index, buffer );
  37013. this.currentBoundBufferBases[ key ] = buffer;
  37014. return true;
  37015. }
  37016. return false;
  37017. }
  37018. unbindTexture() {
  37019. const { gl, currentTextureSlot, currentBoundTextures } = this;
  37020. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  37021. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  37022. gl.bindTexture( boundTexture.type, null );
  37023. boundTexture.type = undefined;
  37024. boundTexture.texture = undefined;
  37025. }
  37026. }
  37027. }
  37028. class WebGLUtils {
  37029. constructor( backend ) {
  37030. this.backend = backend;
  37031. this.gl = this.backend.gl;
  37032. this.extensions = backend.extensions;
  37033. }
  37034. convert( p, colorSpace = NoColorSpace ) {
  37035. const { gl, extensions } = this;
  37036. let extension;
  37037. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  37038. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  37039. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  37040. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  37041. if ( p === ByteType ) return gl.BYTE;
  37042. if ( p === ShortType ) return gl.SHORT;
  37043. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  37044. if ( p === IntType ) return gl.INT;
  37045. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  37046. if ( p === FloatType ) return gl.FLOAT;
  37047. if ( p === HalfFloatType ) {
  37048. return gl.HALF_FLOAT;
  37049. }
  37050. if ( p === AlphaFormat ) return gl.ALPHA;
  37051. if ( p === RGBFormat ) return gl.RGB;
  37052. if ( p === RGBAFormat ) return gl.RGBA;
  37053. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  37054. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  37055. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  37056. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  37057. // WebGL2 formats.
  37058. if ( p === RedFormat ) return gl.RED;
  37059. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  37060. if ( p === RGFormat ) return gl.RG;
  37061. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  37062. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  37063. // S3TC
  37064. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  37065. if ( colorSpace === SRGBColorSpace ) {
  37066. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  37067. if ( extension !== null ) {
  37068. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  37069. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  37070. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  37071. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  37072. } else {
  37073. return null;
  37074. }
  37075. } else {
  37076. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  37077. if ( extension !== null ) {
  37078. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  37079. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  37080. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  37081. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  37082. } else {
  37083. return null;
  37084. }
  37085. }
  37086. }
  37087. // PVRTC
  37088. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  37089. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  37090. if ( extension !== null ) {
  37091. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  37092. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  37093. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  37094. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  37095. } else {
  37096. return null;
  37097. }
  37098. }
  37099. // ETC
  37100. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  37101. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  37102. if ( extension !== null ) {
  37103. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  37104. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  37105. } else {
  37106. return null;
  37107. }
  37108. }
  37109. // ASTC
  37110. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  37111. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  37112. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  37113. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  37114. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  37115. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  37116. if ( extension !== null ) {
  37117. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  37118. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  37119. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  37120. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  37121. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  37122. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  37123. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  37124. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  37125. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  37126. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  37127. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  37128. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  37129. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  37130. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  37131. } else {
  37132. return null;
  37133. }
  37134. }
  37135. // BPTC
  37136. if ( p === RGBA_BPTC_Format ) {
  37137. extension = extensions.get( 'EXT_texture_compression_bptc' );
  37138. if ( extension !== null ) {
  37139. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  37140. } else {
  37141. return null;
  37142. }
  37143. }
  37144. // RGTC
  37145. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  37146. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  37147. if ( extension !== null ) {
  37148. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  37149. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  37150. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  37151. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  37152. } else {
  37153. return null;
  37154. }
  37155. }
  37156. //
  37157. if ( p === UnsignedInt248Type ) {
  37158. return gl.UNSIGNED_INT_24_8;
  37159. }
  37160. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  37161. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  37162. }
  37163. _clientWaitAsync() {
  37164. const { gl } = this;
  37165. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  37166. gl.flush();
  37167. return new Promise( ( resolve, reject ) => {
  37168. function test() {
  37169. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  37170. if ( res === gl.WAIT_FAILED ) {
  37171. gl.deleteSync( sync );
  37172. reject();
  37173. return;
  37174. }
  37175. if ( res === gl.TIMEOUT_EXPIRED ) {
  37176. requestAnimationFrame( test );
  37177. return;
  37178. }
  37179. gl.deleteSync( sync );
  37180. resolve();
  37181. }
  37182. test();
  37183. } );
  37184. }
  37185. }
  37186. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  37187. class WebGLTextureUtils {
  37188. constructor( backend ) {
  37189. this.backend = backend;
  37190. this.gl = backend.gl;
  37191. this.extensions = backend.extensions;
  37192. this.defaultTextures = {};
  37193. if ( initialized === false ) {
  37194. this._init( this.gl );
  37195. initialized = true;
  37196. }
  37197. }
  37198. _init( gl ) {
  37199. // Store only WebGL constants here.
  37200. wrappingToGL = {
  37201. [ RepeatWrapping ]: gl.REPEAT,
  37202. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  37203. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  37204. };
  37205. filterToGL = {
  37206. [ NearestFilter ]: gl.NEAREST,
  37207. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  37208. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  37209. [ LinearFilter ]: gl.LINEAR,
  37210. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  37211. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  37212. };
  37213. compareToGL = {
  37214. [ NeverCompare ]: gl.NEVER,
  37215. [ AlwaysCompare ]: gl.ALWAYS,
  37216. [ LessCompare ]: gl.LESS,
  37217. [ LessEqualCompare ]: gl.LEQUAL,
  37218. [ EqualCompare ]: gl.EQUAL,
  37219. [ GreaterEqualCompare ]: gl.GEQUAL,
  37220. [ GreaterCompare ]: gl.GREATER,
  37221. [ NotEqualCompare ]: gl.NOTEQUAL
  37222. };
  37223. }
  37224. filterFallback( f ) {
  37225. const { gl } = this;
  37226. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  37227. return gl.NEAREST;
  37228. }
  37229. return gl.LINEAR;
  37230. }
  37231. getGLTextureType( texture ) {
  37232. const { gl } = this;
  37233. let glTextureType;
  37234. if ( texture.isCubeTexture === true ) {
  37235. glTextureType = gl.TEXTURE_CUBE_MAP;
  37236. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  37237. glTextureType = gl.TEXTURE_2D_ARRAY;
  37238. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  37239. glTextureType = gl.TEXTURE_3D;
  37240. } else {
  37241. glTextureType = gl.TEXTURE_2D;
  37242. }
  37243. return glTextureType;
  37244. }
  37245. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  37246. const { gl, extensions } = this;
  37247. if ( internalFormatName !== null ) {
  37248. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  37249. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  37250. }
  37251. let internalFormat = glFormat;
  37252. if ( glFormat === gl.RED ) {
  37253. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  37254. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  37255. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  37256. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  37257. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  37258. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  37259. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  37260. if ( glType === gl.INT ) internalFormat = gl.R32I;
  37261. }
  37262. if ( glFormat === gl.RED_INTEGER ) {
  37263. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  37264. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  37265. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  37266. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  37267. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  37268. if ( glType === gl.INT ) internalFormat = gl.R32I;
  37269. }
  37270. if ( glFormat === gl.RG ) {
  37271. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  37272. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  37273. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  37274. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  37275. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  37276. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  37277. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  37278. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  37279. }
  37280. if ( glFormat === gl.RG_INTEGER ) {
  37281. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  37282. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  37283. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  37284. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  37285. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  37286. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  37287. }
  37288. if ( glFormat === gl.RGB ) {
  37289. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  37290. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  37291. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  37292. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  37293. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  37294. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  37295. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  37296. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  37297. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  37298. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  37299. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  37300. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  37301. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  37302. }
  37303. if ( glFormat === gl.RGB_INTEGER ) {
  37304. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  37305. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  37306. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  37307. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  37308. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  37309. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  37310. }
  37311. if ( glFormat === gl.RGBA ) {
  37312. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  37313. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  37314. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  37315. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  37316. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  37317. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  37318. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  37319. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  37320. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  37321. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  37322. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  37323. }
  37324. if ( glFormat === gl.RGBA_INTEGER ) {
  37325. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  37326. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  37327. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  37328. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  37329. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  37330. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  37331. }
  37332. if ( glFormat === gl.DEPTH_COMPONENT ) {
  37333. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  37334. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  37335. }
  37336. if ( glFormat === gl.DEPTH_STENCIL ) {
  37337. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  37338. }
  37339. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  37340. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  37341. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  37342. extensions.get( 'EXT_color_buffer_float' );
  37343. }
  37344. return internalFormat;
  37345. }
  37346. setTextureParameters( textureType, texture ) {
  37347. const { gl, extensions, backend } = this;
  37348. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  37349. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  37350. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  37351. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  37352. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  37353. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  37354. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  37355. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  37356. }
  37357. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  37358. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  37359. // follow WebGPU backend mapping for texture filtering
  37360. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  37361. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  37362. if ( texture.compareFunction ) {
  37363. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  37364. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  37365. }
  37366. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  37367. if ( texture.magFilter === NearestFilter ) return;
  37368. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  37369. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  37370. if ( texture.anisotropy > 1 ) {
  37371. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  37372. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  37373. }
  37374. }
  37375. }
  37376. createDefaultTexture( texture ) {
  37377. const { gl, backend, defaultTextures } = this;
  37378. const glTextureType = this.getGLTextureType( texture );
  37379. let textureGPU = defaultTextures[ glTextureType ];
  37380. if ( textureGPU === undefined ) {
  37381. textureGPU = gl.createTexture();
  37382. backend.state.bindTexture( glTextureType, textureGPU );
  37383. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  37384. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  37385. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  37386. defaultTextures[ glTextureType ] = textureGPU;
  37387. }
  37388. backend.set( texture, {
  37389. textureGPU,
  37390. glTextureType,
  37391. isDefault: true
  37392. } );
  37393. }
  37394. createTexture( texture, options ) {
  37395. const { gl, backend } = this;
  37396. const { levels, width, height, depth } = options;
  37397. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  37398. const glType = backend.utils.convert( texture.type );
  37399. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  37400. const textureGPU = gl.createTexture();
  37401. const glTextureType = this.getGLTextureType( texture );
  37402. backend.state.bindTexture( glTextureType, textureGPU );
  37403. this.setTextureParameters( glTextureType, texture );
  37404. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  37405. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  37406. } else if ( texture.isData3DTexture ) {
  37407. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  37408. } else if ( ! texture.isVideoTexture ) {
  37409. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  37410. }
  37411. backend.set( texture, {
  37412. textureGPU,
  37413. glTextureType,
  37414. glFormat,
  37415. glType,
  37416. glInternalFormat
  37417. } );
  37418. }
  37419. copyBufferToTexture( buffer, texture ) {
  37420. const { gl, backend } = this;
  37421. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  37422. const { width, height } = texture.source.data;
  37423. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  37424. backend.state.bindTexture( glTextureType, textureGPU );
  37425. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  37426. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  37427. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  37428. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  37429. backend.state.unbindTexture();
  37430. // debug
  37431. // const framebuffer = gl.createFramebuffer();
  37432. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  37433. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  37434. // const readout = new Float32Array( width * height * 4 );
  37435. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  37436. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  37437. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  37438. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  37439. // console.log( readout );
  37440. }
  37441. updateTexture( texture, options ) {
  37442. const { gl } = this;
  37443. const { width, height } = options;
  37444. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  37445. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  37446. return;
  37447. const getImage = ( source ) => {
  37448. if ( source.isDataTexture ) {
  37449. return source.image.data;
  37450. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  37451. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  37452. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  37453. source instanceof OffscreenCanvas ) {
  37454. return source;
  37455. }
  37456. return source.data;
  37457. };
  37458. this.backend.state.bindTexture( glTextureType, textureGPU );
  37459. this.setTextureParameters( glTextureType, texture );
  37460. if ( texture.isCompressedTexture ) {
  37461. const mipmaps = texture.mipmaps;
  37462. const image = options.image;
  37463. for ( let i = 0; i < mipmaps.length; i ++ ) {
  37464. const mipmap = mipmaps[ i ];
  37465. if ( texture.isCompressedArrayTexture ) {
  37466. if ( texture.format !== gl.RGBA ) {
  37467. if ( glFormat !== null ) {
  37468. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  37469. } else {
  37470. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  37471. }
  37472. } else {
  37473. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  37474. }
  37475. } else {
  37476. if ( glFormat !== null ) {
  37477. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  37478. } else {
  37479. console.warn( 'Unsupported compressed texture format' );
  37480. }
  37481. }
  37482. }
  37483. } else if ( texture.isCubeTexture ) {
  37484. const images = options.images;
  37485. for ( let i = 0; i < 6; i ++ ) {
  37486. const image = getImage( images[ i ] );
  37487. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  37488. }
  37489. } else if ( texture.isDataArrayTexture ) {
  37490. const image = options.image;
  37491. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  37492. } else if ( texture.isData3DTexture ) {
  37493. const image = options.image;
  37494. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  37495. } else if ( texture.isVideoTexture ) {
  37496. texture.update();
  37497. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  37498. } else {
  37499. const image = getImage( options.image );
  37500. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  37501. }
  37502. }
  37503. generateMipmaps( texture ) {
  37504. const { gl, backend } = this;
  37505. const { textureGPU, glTextureType } = backend.get( texture );
  37506. backend.state.bindTexture( glTextureType, textureGPU );
  37507. gl.generateMipmap( glTextureType );
  37508. }
  37509. deallocateRenderBuffers( renderTarget ) {
  37510. const { gl, backend } = this;
  37511. // remove framebuffer reference
  37512. if ( renderTarget ) {
  37513. const renderContextData = backend.get( renderTarget );
  37514. renderContextData.renderBufferStorageSetup = undefined;
  37515. if ( renderContextData.framebuffers ) {
  37516. for ( const cacheKey in renderContextData.framebuffers ) {
  37517. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  37518. }
  37519. delete renderContextData.framebuffers;
  37520. }
  37521. if ( renderContextData.depthRenderbuffer ) {
  37522. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  37523. delete renderContextData.depthRenderbuffer;
  37524. }
  37525. if ( renderContextData.stencilRenderbuffer ) {
  37526. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  37527. delete renderContextData.stencilRenderbuffer;
  37528. }
  37529. if ( renderContextData.msaaFrameBuffer ) {
  37530. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  37531. delete renderContextData.msaaFrameBuffer;
  37532. }
  37533. if ( renderContextData.msaaRenderbuffers ) {
  37534. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  37535. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  37536. }
  37537. delete renderContextData.msaaRenderbuffers;
  37538. }
  37539. }
  37540. }
  37541. destroyTexture( texture ) {
  37542. const { gl, backend } = this;
  37543. const { textureGPU, renderTarget } = backend.get( texture );
  37544. this.deallocateRenderBuffers( renderTarget );
  37545. gl.deleteTexture( textureGPU );
  37546. backend.delete( texture );
  37547. }
  37548. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  37549. const { gl, backend } = this;
  37550. const { state } = this.backend;
  37551. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  37552. let width, height, minX, minY;
  37553. let dstX, dstY;
  37554. if ( srcRegion !== null ) {
  37555. width = srcRegion.max.x - srcRegion.min.x;
  37556. height = srcRegion.max.y - srcRegion.min.y;
  37557. minX = srcRegion.min.x;
  37558. minY = srcRegion.min.y;
  37559. } else {
  37560. width = srcTexture.image.width;
  37561. height = srcTexture.image.height;
  37562. minX = 0;
  37563. minY = 0;
  37564. }
  37565. if ( dstPosition !== null ) {
  37566. dstX = dstPosition.x;
  37567. dstY = dstPosition.y;
  37568. } else {
  37569. dstX = 0;
  37570. dstY = 0;
  37571. }
  37572. state.bindTexture( glTextureType, dstTextureGPU );
  37573. // As another texture upload may have changed pixelStorei
  37574. // parameters, make sure they are correct for the dstTexture
  37575. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  37576. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  37577. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  37578. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  37579. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  37580. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  37581. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  37582. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  37583. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  37584. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  37585. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  37586. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  37587. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  37588. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  37589. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  37590. const srcTextureData = backend.get( srcTexture );
  37591. const dstTextureData = backend.get( dstTexture );
  37592. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  37593. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  37594. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  37595. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  37596. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  37597. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  37598. let mask = gl.COLOR_BUFFER_BIT;
  37599. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  37600. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  37601. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  37602. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  37603. } else {
  37604. if ( srcTexture.isDataTexture ) {
  37605. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  37606. } else {
  37607. if ( srcTexture.isCompressedTexture ) {
  37608. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  37609. } else {
  37610. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  37611. }
  37612. }
  37613. }
  37614. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  37615. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  37616. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  37617. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  37618. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  37619. // Generate mipmaps only when copying level 0
  37620. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  37621. state.unbindTexture();
  37622. }
  37623. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  37624. const { gl } = this;
  37625. const { state } = this.backend;
  37626. const { textureGPU } = this.backend.get( texture );
  37627. const { x, y, z: width, w: height } = rectangle;
  37628. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  37629. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  37630. if ( requireDrawFrameBuffer ) {
  37631. const partial = ( x !== 0 || y !== 0 );
  37632. let mask;
  37633. let attachment;
  37634. if ( texture.isDepthTexture === true ) {
  37635. mask = gl.DEPTH_BUFFER_BIT;
  37636. attachment = gl.DEPTH_ATTACHMENT;
  37637. if ( renderContext.stencil ) {
  37638. mask |= gl.STENCIL_BUFFER_BIT;
  37639. }
  37640. } else {
  37641. mask = gl.COLOR_BUFFER_BIT;
  37642. attachment = gl.COLOR_ATTACHMENT0;
  37643. }
  37644. if ( partial ) {
  37645. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  37646. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  37647. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  37648. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  37649. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  37650. const flippedY = srcHeight - y - height;
  37651. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  37652. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  37653. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  37654. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  37655. state.unbindTexture();
  37656. } else {
  37657. const fb = gl.createFramebuffer();
  37658. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  37659. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  37660. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  37661. gl.deleteFramebuffer( fb );
  37662. }
  37663. } else {
  37664. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  37665. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  37666. state.unbindTexture();
  37667. }
  37668. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  37669. this.backend._setFramebuffer( renderContext );
  37670. }
  37671. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  37672. setupRenderBufferStorage( renderbuffer, renderContext ) {
  37673. const { gl } = this;
  37674. const renderTarget = renderContext.renderTarget;
  37675. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  37676. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  37677. if ( depthBuffer && ! stencilBuffer ) {
  37678. let glInternalFormat = gl.DEPTH_COMPONENT24;
  37679. if ( samples > 0 ) {
  37680. if ( depthTexture && depthTexture.isDepthTexture ) {
  37681. if ( depthTexture.type === gl.FLOAT ) {
  37682. glInternalFormat = gl.DEPTH_COMPONENT32F;
  37683. }
  37684. }
  37685. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  37686. } else {
  37687. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  37688. }
  37689. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  37690. } else if ( depthBuffer && stencilBuffer ) {
  37691. if ( samples > 0 ) {
  37692. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  37693. } else {
  37694. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  37695. }
  37696. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  37697. }
  37698. }
  37699. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  37700. const { backend, gl } = this;
  37701. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  37702. const fb = gl.createFramebuffer();
  37703. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  37704. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  37705. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  37706. const typedArrayType = this._getTypedArrayType( glType );
  37707. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  37708. const elementCount = width * height;
  37709. const byteLength = elementCount * bytesPerTexel;
  37710. const buffer = gl.createBuffer();
  37711. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  37712. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  37713. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  37714. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  37715. await backend.utils._clientWaitAsync();
  37716. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  37717. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  37718. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  37719. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  37720. gl.deleteFramebuffer( fb );
  37721. return dstBuffer;
  37722. }
  37723. _getTypedArrayType( glType ) {
  37724. const { gl } = this;
  37725. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  37726. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  37727. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  37728. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  37729. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  37730. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  37731. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  37732. if ( glType === gl.FLOAT ) return Float32Array;
  37733. throw new Error( `Unsupported WebGL type: ${glType}` );
  37734. }
  37735. _getBytesPerTexel( glType, glFormat ) {
  37736. const { gl } = this;
  37737. let bytesPerComponent = 0;
  37738. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  37739. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  37740. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  37741. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  37742. glType === gl.UNSIGNED_SHORT ||
  37743. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  37744. if ( glType === gl.UNSIGNED_INT ||
  37745. glType === gl.FLOAT ) bytesPerComponent = 4;
  37746. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  37747. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  37748. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  37749. }
  37750. }
  37751. class WebGLExtensions {
  37752. constructor( backend ) {
  37753. this.backend = backend;
  37754. this.gl = this.backend.gl;
  37755. this.availableExtensions = this.gl.getSupportedExtensions();
  37756. this.extensions = {};
  37757. }
  37758. get( name ) {
  37759. let extension = this.extensions[ name ];
  37760. if ( extension === undefined ) {
  37761. extension = this.gl.getExtension( name );
  37762. this.extensions[ name ] = extension;
  37763. }
  37764. return extension;
  37765. }
  37766. has( name ) {
  37767. return this.availableExtensions.includes( name );
  37768. }
  37769. }
  37770. class WebGLCapabilities {
  37771. constructor( backend ) {
  37772. this.backend = backend;
  37773. this.maxAnisotropy = null;
  37774. }
  37775. getMaxAnisotropy() {
  37776. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  37777. const gl = this.backend.gl;
  37778. const extensions = this.backend.extensions;
  37779. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  37780. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  37781. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  37782. } else {
  37783. this.maxAnisotropy = 0;
  37784. }
  37785. return this.maxAnisotropy;
  37786. }
  37787. }
  37788. const GLFeatureName = {
  37789. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  37790. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  37791. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  37792. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  37793. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  37794. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  37795. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  37796. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  37797. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  37798. };
  37799. class WebGLBufferRenderer {
  37800. constructor( backend ) {
  37801. this.gl = backend.gl;
  37802. this.extensions = backend.extensions;
  37803. this.info = backend.renderer.info;
  37804. this.mode = null;
  37805. this.index = 0;
  37806. this.type = null;
  37807. this.object = null;
  37808. }
  37809. render( start, count ) {
  37810. const { gl, mode, object, type, info, index } = this;
  37811. if ( index !== 0 ) {
  37812. gl.drawElements( mode, count, type, start );
  37813. } else {
  37814. gl.drawArrays( mode, start, count );
  37815. }
  37816. info.update( object, count, mode, 1 );
  37817. }
  37818. renderInstances( start, count, primcount ) {
  37819. const { gl, mode, type, index, object, info } = this;
  37820. if ( primcount === 0 ) return;
  37821. if ( index !== 0 ) {
  37822. gl.drawElementsInstanced( mode, count, type, start, primcount );
  37823. } else {
  37824. gl.drawArraysInstanced( mode, start, count, primcount );
  37825. }
  37826. info.update( object, count, mode, primcount );
  37827. }
  37828. renderMultiDraw( starts, counts, drawCount ) {
  37829. const { extensions, mode, object, info } = this;
  37830. if ( drawCount === 0 ) return;
  37831. const extension = extensions.get( 'WEBGL_multi_draw' );
  37832. if ( extension === null ) {
  37833. for ( let i = 0; i < drawCount; i ++ ) {
  37834. this.render( starts[ i ], counts[ i ] );
  37835. }
  37836. } else {
  37837. if ( this.index !== 0 ) {
  37838. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  37839. } else {
  37840. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  37841. }
  37842. let elementCount = 0;
  37843. for ( let i = 0; i < drawCount; i ++ ) {
  37844. elementCount += counts[ i ];
  37845. }
  37846. info.update( object, elementCount, mode, 1 );
  37847. }
  37848. }
  37849. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  37850. const { extensions, mode, object, info } = this;
  37851. if ( drawCount === 0 ) return;
  37852. const extension = extensions.get( 'WEBGL_multi_draw' );
  37853. if ( extension === null ) {
  37854. for ( let i = 0; i < drawCount; i ++ ) {
  37855. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  37856. }
  37857. } else {
  37858. if ( this.index !== 0 ) {
  37859. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  37860. } else {
  37861. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  37862. }
  37863. let elementCount = 0;
  37864. for ( let i = 0; i < drawCount; i ++ ) {
  37865. elementCount += counts[ i ] * primcount[ i ];
  37866. }
  37867. info.update( object, elementCount, mode, 1 );
  37868. }
  37869. }
  37870. //
  37871. }
  37872. /**
  37873. * A backend implementation targeting WebGL 2.
  37874. *
  37875. * @private
  37876. * @augments Backend
  37877. */
  37878. class WebGLBackend extends Backend {
  37879. /**
  37880. * Constructs a new WebGPU backend.
  37881. *
  37882. * @param {Object} parameters - The configuration parameter.
  37883. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  37884. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  37885. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  37886. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  37887. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  37888. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  37889. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses it WebGL 2 backend no matter if WebGPU is supported or not.
  37890. * @param {WebGL2RenderingContext} [parameters.context=undefined] - A WebGL 2 rendering context.
  37891. */
  37892. constructor( parameters = {} ) {
  37893. super( parameters );
  37894. /**
  37895. * This flag can be used for type testing.
  37896. *
  37897. * @type {Boolean}
  37898. * @readonly
  37899. * @default true
  37900. */
  37901. this.isWebGLBackend = true;
  37902. /**
  37903. * A reference to a backend module holding shader attribute-related
  37904. * utility functions.
  37905. *
  37906. * @type {WebGLAttributeUtils?}
  37907. * @default null
  37908. */
  37909. this.attributeUtils = null;
  37910. /**
  37911. * A reference to a backend module holding extension-related
  37912. * utility functions.
  37913. *
  37914. * @type {WebGLExtensions?}
  37915. * @default null
  37916. */
  37917. this.extensions = null;
  37918. /**
  37919. * A reference to a backend module holding capability-related
  37920. * utility functions.
  37921. *
  37922. * @type {WebGLCapabilities?}
  37923. * @default null
  37924. */
  37925. this.capabilities = null;
  37926. /**
  37927. * A reference to a backend module holding texture-related
  37928. * utility functions.
  37929. *
  37930. * @type {WebGLTextureUtils?}
  37931. * @default null
  37932. */
  37933. this.textureUtils = null;
  37934. /**
  37935. * A reference to a backend module holding renderer-related
  37936. * utility functions.
  37937. *
  37938. * @type {WebGLBufferRenderer?}
  37939. * @default null
  37940. */
  37941. this.bufferRenderer = null;
  37942. /**
  37943. * A reference to the rendering context.
  37944. *
  37945. * @type {WebGL2RenderingContext?}
  37946. * @default null
  37947. */
  37948. this.gl = null;
  37949. /**
  37950. * A reference to a backend module holding state-related
  37951. * utility functions.
  37952. *
  37953. * @type {WebGLState?}
  37954. * @default null
  37955. */
  37956. this.state = null;
  37957. /**
  37958. * A reference to a backend module holding common
  37959. * utility functions.
  37960. *
  37961. * @type {WebGLUtils?}
  37962. * @default null
  37963. */
  37964. this.utils = null;
  37965. /**
  37966. * Dictionary for caching VAOs.
  37967. *
  37968. * @type {Object<String,WebGLVertexArrayObject>}
  37969. */
  37970. this.vaoCache = {};
  37971. /**
  37972. * Dictionary for caching transform feedback objects.
  37973. *
  37974. * @type {Object<String,WebGLTransformFeedback>}
  37975. */
  37976. this.transformFeedbackCache = {};
  37977. /**
  37978. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  37979. * Only relevant when using compute shaders.
  37980. *
  37981. * @type {Boolean}
  37982. * @default false
  37983. */
  37984. this.discard = false;
  37985. /**
  37986. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  37987. * device does not support the extension.
  37988. *
  37989. * @type {EXTDisjointTimerQueryWebGL2?}
  37990. * @default null
  37991. */
  37992. this.disjoint = null;
  37993. /**
  37994. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  37995. * device does not support the extension.
  37996. *
  37997. * @type {KHRParallelShaderCompile?}
  37998. * @default null
  37999. */
  38000. this.parallel = null;
  38001. /**
  38002. * Whether to track timestamps with a Timestamp Query API or not.
  38003. *
  38004. * @type {Boolean}
  38005. * @default false
  38006. */
  38007. this.trackTimestamp = ( parameters.trackTimestamp === true );
  38008. /**
  38009. * A reference to the current render context.
  38010. *
  38011. * @private
  38012. * @type {RenderContext}
  38013. * @default null
  38014. */
  38015. this._currentContext = null;
  38016. /**
  38017. * A unique collection of bindings.
  38018. *
  38019. * @private
  38020. * @type {WeakSet}
  38021. */
  38022. this._knownBindings = new WeakSet();
  38023. }
  38024. /**
  38025. * Initializes the backend so it is ready for usage.
  38026. *
  38027. * @param {Renderer} renderer - The renderer.
  38028. */
  38029. init( renderer ) {
  38030. super.init( renderer );
  38031. //
  38032. const parameters = this.parameters;
  38033. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  38034. function onContextLost( event ) {
  38035. event.preventDefault();
  38036. const contextLossInfo = {
  38037. api: 'WebGL',
  38038. message: event.statusMessage || 'Unknown reason',
  38039. reason: null,
  38040. originalEvent: event
  38041. };
  38042. renderer.onDeviceLost( contextLossInfo );
  38043. }
  38044. this._onContextLost = onContextLost;
  38045. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  38046. this.gl = glContext;
  38047. this.extensions = new WebGLExtensions( this );
  38048. this.capabilities = new WebGLCapabilities( this );
  38049. this.attributeUtils = new WebGLAttributeUtils( this );
  38050. this.textureUtils = new WebGLTextureUtils( this );
  38051. this.bufferRenderer = new WebGLBufferRenderer( this );
  38052. this.state = new WebGLState( this );
  38053. this.utils = new WebGLUtils( this );
  38054. this.extensions.get( 'EXT_color_buffer_float' );
  38055. this.extensions.get( 'WEBGL_clip_cull_distance' );
  38056. this.extensions.get( 'OES_texture_float_linear' );
  38057. this.extensions.get( 'EXT_color_buffer_half_float' );
  38058. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  38059. this.extensions.get( 'WEBGL_render_shared_exponent' );
  38060. this.extensions.get( 'WEBGL_multi_draw' );
  38061. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  38062. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  38063. }
  38064. /**
  38065. * The coordinate system of the backend.
  38066. *
  38067. * @type {Number}
  38068. * @readonly
  38069. */
  38070. get coordinateSystem() {
  38071. return WebGLCoordinateSystem;
  38072. }
  38073. /**
  38074. * Transfers buffer data from a storage buffer attribute
  38075. * from the GPU to the CPU in context of compute shaders.
  38076. *
  38077. * @async
  38078. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38079. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38080. */
  38081. async getArrayBufferAsync( attribute ) {
  38082. return await this.attributeUtils.getArrayBufferAsync( attribute );
  38083. }
  38084. /**
  38085. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  38086. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  38087. *
  38088. * @async
  38089. * @return {Promise} A Promise that resolves when synchronization has been finished.
  38090. */
  38091. async waitForGPU() {
  38092. await this.utils._clientWaitAsync();
  38093. }
  38094. /**
  38095. * Inits a time stamp query for the given render context.
  38096. *
  38097. * @param {RenderContext} renderContext - The render context.
  38098. */
  38099. initTimestampQuery( renderContext ) {
  38100. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38101. const renderContextData = this.get( renderContext );
  38102. if ( this.queryRunning ) {
  38103. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  38104. renderContextData.queryQueue.push( renderContext );
  38105. return;
  38106. }
  38107. if ( renderContextData.activeQuery ) {
  38108. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  38109. renderContextData.activeQuery = null;
  38110. }
  38111. renderContextData.activeQuery = this.gl.createQuery();
  38112. if ( renderContextData.activeQuery !== null ) {
  38113. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  38114. this.queryRunning = true;
  38115. }
  38116. }
  38117. // timestamp utils
  38118. /**
  38119. * Prepares the timestamp buffer.
  38120. *
  38121. * @param {RenderContext} renderContext - The render context.
  38122. */
  38123. prepareTimestampBuffer( renderContext ) {
  38124. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38125. const renderContextData = this.get( renderContext );
  38126. if ( renderContextData.activeQuery ) {
  38127. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  38128. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  38129. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  38130. renderContextData.activeQuery = null;
  38131. this.queryRunning = false;
  38132. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  38133. const nextRenderContext = renderContextData.queryQueue.shift();
  38134. this.initTimestampQuery( nextRenderContext );
  38135. }
  38136. }
  38137. }
  38138. /**
  38139. * Resolves the time stamp for the given render context and type.
  38140. *
  38141. * @async
  38142. * @param {RenderContext} renderContext - The render context.
  38143. * @param {String} type - The render context.
  38144. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  38145. */
  38146. async resolveTimestampAsync( renderContext, type = 'render' ) {
  38147. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  38148. const renderContextData = this.get( renderContext );
  38149. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  38150. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  38151. const queryInfo = renderContextData.gpuQueries[ i ];
  38152. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  38153. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  38154. if ( available && ! disjoint ) {
  38155. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  38156. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  38157. this.gl.deleteQuery( queryInfo.query );
  38158. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  38159. i --;
  38160. this.renderer.info.updateTimestamp( type, duration );
  38161. }
  38162. }
  38163. }
  38164. /**
  38165. * Returns the backend's rendering context.
  38166. *
  38167. * @return {WebGL2RenderingContext} The rendering context.
  38168. */
  38169. getContext() {
  38170. return this.gl;
  38171. }
  38172. /**
  38173. * This method is executed at the beginning of a render call and prepares
  38174. * the WebGL state for upcoming render calls
  38175. *
  38176. * @param {RenderContext} renderContext - The render context.
  38177. */
  38178. beginRender( renderContext ) {
  38179. const { gl } = this;
  38180. const renderContextData = this.get( renderContext );
  38181. //
  38182. //
  38183. this.initTimestampQuery( renderContext );
  38184. renderContextData.previousContext = this._currentContext;
  38185. this._currentContext = renderContext;
  38186. this._setFramebuffer( renderContext );
  38187. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  38188. //
  38189. if ( renderContext.viewport ) {
  38190. this.updateViewport( renderContext );
  38191. } else {
  38192. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  38193. }
  38194. if ( renderContext.scissor ) {
  38195. const { x, y, width, height } = renderContext.scissorValue;
  38196. gl.scissor( x, renderContext.height - height - y, width, height );
  38197. }
  38198. const occlusionQueryCount = renderContext.occlusionQueryCount;
  38199. if ( occlusionQueryCount > 0 ) {
  38200. // Get a reference to the array of objects with queries. The renderContextData property
  38201. // can be changed by another render pass before the async reading of all previous queries complete
  38202. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  38203. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  38204. renderContextData.lastOcclusionObject = null;
  38205. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  38206. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  38207. renderContextData.occlusionQueryIndex = 0;
  38208. }
  38209. }
  38210. /**
  38211. * This method is executed at the end of a render call and finalizes work
  38212. * after draw calls.
  38213. *
  38214. * @param {RenderContext} renderContext - The render context.
  38215. */
  38216. finishRender( renderContext ) {
  38217. const { gl, state } = this;
  38218. const renderContextData = this.get( renderContext );
  38219. const previousContext = renderContextData.previousContext;
  38220. const occlusionQueryCount = renderContext.occlusionQueryCount;
  38221. if ( occlusionQueryCount > 0 ) {
  38222. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  38223. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  38224. }
  38225. this.resolveOccludedAsync( renderContext );
  38226. }
  38227. const textures = renderContext.textures;
  38228. if ( textures !== null ) {
  38229. for ( let i = 0; i < textures.length; i ++ ) {
  38230. const texture = textures[ i ];
  38231. if ( texture.generateMipmaps ) {
  38232. this.generateMipmaps( texture );
  38233. }
  38234. }
  38235. }
  38236. this._currentContext = previousContext;
  38237. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  38238. const renderTargetContextData = this.get( renderContext.renderTarget );
  38239. const { samples } = renderContext.renderTarget;
  38240. if ( samples > 0 ) {
  38241. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  38242. const mask = gl.COLOR_BUFFER_BIT;
  38243. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  38244. const textures = renderContext.textures;
  38245. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  38246. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  38247. for ( let i = 0; i < textures.length; i ++ ) {
  38248. // TODO Add support for MRT
  38249. if ( renderContext.scissor ) {
  38250. const { x, y, width, height } = renderContext.scissorValue;
  38251. const viewY = renderContext.height - height - y;
  38252. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  38253. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  38254. } else {
  38255. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  38256. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  38257. }
  38258. }
  38259. }
  38260. }
  38261. if ( previousContext !== null ) {
  38262. this._setFramebuffer( previousContext );
  38263. if ( previousContext.viewport ) {
  38264. this.updateViewport( previousContext );
  38265. } else {
  38266. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  38267. }
  38268. }
  38269. this.prepareTimestampBuffer( renderContext );
  38270. }
  38271. /**
  38272. * This method processes the result of occlusion queries and writes it
  38273. * into render context data.
  38274. *
  38275. * @async
  38276. * @param {RenderContext} renderContext - The render context.
  38277. */
  38278. resolveOccludedAsync( renderContext ) {
  38279. const renderContextData = this.get( renderContext );
  38280. // handle occlusion query results
  38281. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  38282. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  38283. const occluded = new WeakSet();
  38284. const { gl } = this;
  38285. renderContextData.currentOcclusionQueryObjects = null;
  38286. renderContextData.currentOcclusionQueries = null;
  38287. const check = () => {
  38288. let completed = 0;
  38289. // check all queries and requeue as appropriate
  38290. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  38291. const query = currentOcclusionQueries[ i ];
  38292. if ( query === null ) continue;
  38293. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  38294. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  38295. currentOcclusionQueries[ i ] = null;
  38296. gl.deleteQuery( query );
  38297. completed ++;
  38298. }
  38299. }
  38300. if ( completed < currentOcclusionQueries.length ) {
  38301. requestAnimationFrame( check );
  38302. } else {
  38303. renderContextData.occluded = occluded;
  38304. }
  38305. };
  38306. check();
  38307. }
  38308. }
  38309. /**
  38310. * Returns `true` if the given 3D object is fully occluded by other
  38311. * 3D objects in the scene.
  38312. *
  38313. * @param {RenderContext} renderContext - The render context.
  38314. * @param {Object3D} object - The 3D object to test.
  38315. * @return {Boolean} Whether the 3D object is fully occluded or not.
  38316. */
  38317. isOccluded( renderContext, object ) {
  38318. const renderContextData = this.get( renderContext );
  38319. return renderContextData.occluded && renderContextData.occluded.has( object );
  38320. }
  38321. /**
  38322. * Updates the viewport with the values from the given render context.
  38323. *
  38324. * @param {RenderContext} renderContext - The render context.
  38325. */
  38326. updateViewport( renderContext ) {
  38327. const gl = this.gl;
  38328. const { x, y, width, height } = renderContext.viewportValue;
  38329. gl.viewport( x, renderContext.height - height - y, width, height );
  38330. }
  38331. /**
  38332. * Defines the scissor test.
  38333. *
  38334. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  38335. */
  38336. setScissorTest( boolean ) {
  38337. const gl = this.gl;
  38338. if ( boolean ) {
  38339. gl.enable( gl.SCISSOR_TEST );
  38340. } else {
  38341. gl.disable( gl.SCISSOR_TEST );
  38342. }
  38343. }
  38344. /**
  38345. * Performs a clear operation.
  38346. *
  38347. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  38348. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  38349. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  38350. * @param {Object?} [descriptor=null] - The render context of the current set render target.
  38351. * @param {Boolean} [setFrameBuffer=true] - TODO.
  38352. */
  38353. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  38354. const { gl } = this;
  38355. if ( descriptor === null ) {
  38356. const clearColor = this.getClearColor();
  38357. // premultiply alpha
  38358. clearColor.r *= clearColor.a;
  38359. clearColor.g *= clearColor.a;
  38360. clearColor.b *= clearColor.a;
  38361. descriptor = {
  38362. textures: null,
  38363. clearColorValue: clearColor
  38364. };
  38365. }
  38366. //
  38367. let clear = 0;
  38368. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  38369. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  38370. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  38371. if ( clear !== 0 ) {
  38372. let clearColor;
  38373. if ( descriptor.clearColorValue ) {
  38374. clearColor = descriptor.clearColorValue;
  38375. } else {
  38376. clearColor = this.getClearColor();
  38377. // premultiply alpha
  38378. clearColor.r *= clearColor.a;
  38379. clearColor.g *= clearColor.a;
  38380. clearColor.b *= clearColor.a;
  38381. }
  38382. if ( depth ) this.state.setDepthMask( true );
  38383. if ( descriptor.textures === null ) {
  38384. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  38385. gl.clear( clear );
  38386. } else {
  38387. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  38388. if ( color ) {
  38389. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  38390. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  38391. }
  38392. }
  38393. if ( depth && stencil ) {
  38394. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  38395. } else if ( depth ) {
  38396. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  38397. } else if ( stencil ) {
  38398. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  38399. }
  38400. }
  38401. }
  38402. }
  38403. /**
  38404. * This method is executed at the beginning of a compute call and
  38405. * prepares the state for upcoming compute tasks.
  38406. *
  38407. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  38408. */
  38409. beginCompute( computeGroup ) {
  38410. const { state, gl } = this;
  38411. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  38412. this.initTimestampQuery( computeGroup );
  38413. }
  38414. /**
  38415. * Executes a compute command for the given compute node.
  38416. *
  38417. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  38418. * @param {Node} computeNode - The compute node.
  38419. * @param {Array<BindGroup>} bindings - The bindings.
  38420. * @param {ComputePipeline} pipeline - The compute pipeline.
  38421. */
  38422. compute( computeGroup, computeNode, bindings, pipeline ) {
  38423. const { state, gl } = this;
  38424. if ( this.discard === false ) {
  38425. // required here to handle async behaviour of render.compute()
  38426. gl.enable( gl.RASTERIZER_DISCARD );
  38427. this.discard = true;
  38428. }
  38429. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  38430. const vaoKey = this._getVaoKey( null, attributes );
  38431. const vaoGPU = this.vaoCache[ vaoKey ];
  38432. if ( vaoGPU === undefined ) {
  38433. this._createVao( null, attributes );
  38434. } else {
  38435. gl.bindVertexArray( vaoGPU );
  38436. }
  38437. state.useProgram( programGPU );
  38438. this._bindUniforms( bindings );
  38439. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  38440. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  38441. gl.beginTransformFeedback( gl.POINTS );
  38442. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  38443. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  38444. } else {
  38445. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  38446. }
  38447. gl.endTransformFeedback();
  38448. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  38449. // switch active buffers
  38450. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  38451. const dualAttributeData = transformBuffers[ i ];
  38452. if ( dualAttributeData.pbo ) {
  38453. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  38454. }
  38455. dualAttributeData.switchBuffers();
  38456. }
  38457. }
  38458. /**
  38459. * This method is executed at the end of a compute call and
  38460. * finalizes work after compute tasks.
  38461. *
  38462. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  38463. */
  38464. finishCompute( computeGroup ) {
  38465. const gl = this.gl;
  38466. this.discard = false;
  38467. gl.disable( gl.RASTERIZER_DISCARD );
  38468. this.prepareTimestampBuffer( computeGroup );
  38469. if ( this._currentContext ) {
  38470. this._setFramebuffer( this._currentContext );
  38471. }
  38472. }
  38473. /**
  38474. * Executes a draw command for the given render object.
  38475. *
  38476. * @param {RenderObject} renderObject - The render object to draw.
  38477. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  38478. */
  38479. draw( renderObject/*, info*/ ) {
  38480. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  38481. const { programGPU } = this.get( pipeline );
  38482. const { gl, state } = this;
  38483. const contextData = this.get( context );
  38484. const drawParams = renderObject.getDrawParameters();
  38485. if ( drawParams === null ) return;
  38486. //
  38487. this._bindUniforms( renderObject.getBindings() );
  38488. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  38489. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  38490. state.useProgram( programGPU );
  38491. //
  38492. const renderObjectData = this.get( renderObject );
  38493. let vaoGPU = renderObjectData.staticVao;
  38494. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  38495. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  38496. vaoGPU = this.vaoCache[ vaoKey ];
  38497. if ( vaoGPU === undefined ) {
  38498. let staticVao;
  38499. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  38500. if ( staticVao ) {
  38501. renderObjectData.staticVao = vaoGPU;
  38502. renderObjectData.geometryId = renderObject.geometry.id;
  38503. }
  38504. }
  38505. }
  38506. gl.bindVertexArray( vaoGPU );
  38507. //
  38508. const index = renderObject.getIndex();
  38509. //
  38510. const lastObject = contextData.lastOcclusionObject;
  38511. if ( lastObject !== object && lastObject !== undefined ) {
  38512. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  38513. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  38514. contextData.occlusionQueryIndex ++;
  38515. }
  38516. if ( object.occlusionTest === true ) {
  38517. const query = gl.createQuery();
  38518. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  38519. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  38520. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  38521. }
  38522. contextData.lastOcclusionObject = object;
  38523. }
  38524. //
  38525. const renderer = this.bufferRenderer;
  38526. if ( object.isPoints ) renderer.mode = gl.POINTS;
  38527. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  38528. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  38529. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  38530. else {
  38531. if ( material.wireframe === true ) {
  38532. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  38533. renderer.mode = gl.LINES;
  38534. } else {
  38535. renderer.mode = gl.TRIANGLES;
  38536. }
  38537. }
  38538. //
  38539. const { vertexCount, instanceCount } = drawParams;
  38540. let { firstVertex } = drawParams;
  38541. renderer.object = object;
  38542. if ( index !== null ) {
  38543. firstVertex *= index.array.BYTES_PER_ELEMENT;
  38544. const indexData = this.get( index );
  38545. renderer.index = index.count;
  38546. renderer.type = indexData.type;
  38547. } else {
  38548. renderer.index = 0;
  38549. }
  38550. if ( object.isBatchedMesh ) {
  38551. if ( object._multiDrawInstances !== null ) {
  38552. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  38553. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  38554. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  38555. } else {
  38556. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  38557. }
  38558. } else if ( instanceCount > 1 ) {
  38559. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  38560. } else {
  38561. renderer.render( firstVertex, vertexCount );
  38562. }
  38563. //
  38564. gl.bindVertexArray( null );
  38565. }
  38566. /**
  38567. * Explain why always null is returned.
  38568. *
  38569. * @param {RenderObject} renderObject - The render object.
  38570. * @return {Boolean} Whether the render pipeline requires an update or not.
  38571. */
  38572. needsRenderUpdate( /*renderObject*/ ) {
  38573. return false;
  38574. }
  38575. /**
  38576. * Explain why no cache key is computed.
  38577. *
  38578. * @param {RenderObject} renderObject - The render object.
  38579. * @return {String} The cache key.
  38580. */
  38581. getRenderCacheKey( /*renderObject*/ ) {
  38582. return '';
  38583. }
  38584. // textures
  38585. /**
  38586. * Creates a default texture for the given texture that can be used
  38587. * as a placeholder until the actual texture is ready for usage.
  38588. *
  38589. * @param {Texture} texture - The texture to create a default texture for.
  38590. */
  38591. createDefaultTexture( texture ) {
  38592. this.textureUtils.createDefaultTexture( texture );
  38593. }
  38594. /**
  38595. * Defines a texture on the GPU for the given texture object.
  38596. *
  38597. * @param {Texture} texture - The texture.
  38598. * @param {Object} [options={}] - Optional configuration parameter.
  38599. */
  38600. createTexture( texture, options ) {
  38601. this.textureUtils.createTexture( texture, options );
  38602. }
  38603. /**
  38604. * Uploads the updated texture data to the GPU.
  38605. *
  38606. * @param {Texture} texture - The texture.
  38607. * @param {Object} [options={}] - Optional configuration parameter.
  38608. */
  38609. updateTexture( texture, options ) {
  38610. this.textureUtils.updateTexture( texture, options );
  38611. }
  38612. /**
  38613. * Generates mipmaps for the given texture
  38614. *
  38615. * @param {Texture} texture - The texture.
  38616. */
  38617. generateMipmaps( texture ) {
  38618. this.textureUtils.generateMipmaps( texture );
  38619. }
  38620. /**
  38621. * Destroys the GPU data for the given texture object.
  38622. *
  38623. * @param {Texture} texture - The texture.
  38624. */
  38625. destroyTexture( texture ) {
  38626. this.textureUtils.destroyTexture( texture );
  38627. }
  38628. /**
  38629. * Returns texture data as a typed array.
  38630. *
  38631. * @param {Texture} texture - The texture to copy.
  38632. * @param {Number} x - The x coordinate of the copy origin.
  38633. * @param {Number} y - The y coordinate of the copy origin.
  38634. * @param {Number} width - The width of the copy.
  38635. * @param {Number} height - The height of the copy.
  38636. * @param {Number} faceIndex - The face index.
  38637. * @return {TypedArray} The texture data as a typed array.
  38638. */
  38639. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  38640. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  38641. }
  38642. /**
  38643. * This method does nothing since WebGL 2 has no concept of samplers.
  38644. *
  38645. * @param {Texture} texture - The texture to create the sampler for.
  38646. */
  38647. createSampler( /*texture*/ ) {
  38648. //console.warn( 'Abstract class.' );
  38649. }
  38650. /**
  38651. * This method does nothing since WebGL 2 has no concept of samplers.
  38652. *
  38653. * @param {Texture} texture - The texture to destroy the sampler for.
  38654. */
  38655. destroySampler( /*texture*/ ) {}
  38656. // node builder
  38657. /**
  38658. * Returns a node builder for the given render object.
  38659. *
  38660. * @param {RenderObject} object - The render object.
  38661. * @param {Renderer} renderer - The renderer.
  38662. * @return {GLSLNodeBuilder} The node builder.
  38663. */
  38664. createNodeBuilder( object, renderer ) {
  38665. return new GLSLNodeBuilder( object, renderer );
  38666. }
  38667. // program
  38668. /**
  38669. * Creates a shader program from the given programmable stage.
  38670. *
  38671. * @param {ProgrammableStage} program - The programmable stage.
  38672. */
  38673. createProgram( program ) {
  38674. const gl = this.gl;
  38675. const { stage, code } = program;
  38676. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  38677. gl.shaderSource( shader, code );
  38678. gl.compileShader( shader );
  38679. this.set( program, {
  38680. shaderGPU: shader
  38681. } );
  38682. }
  38683. /**
  38684. * Destroys the shader program of the given programmable stage.
  38685. *
  38686. * @param {ProgrammableStage} program - The programmable stage.
  38687. */
  38688. destroyProgram( program ) {
  38689. this.delete( program );
  38690. }
  38691. /**
  38692. * Creates a render pipeline for the given render object.
  38693. *
  38694. * @param {RenderObject} renderObject - The render object.
  38695. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  38696. */
  38697. createRenderPipeline( renderObject, promises ) {
  38698. const gl = this.gl;
  38699. const pipeline = renderObject.pipeline;
  38700. // Program
  38701. const { fragmentProgram, vertexProgram } = pipeline;
  38702. const programGPU = gl.createProgram();
  38703. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  38704. const vertexShader = this.get( vertexProgram ).shaderGPU;
  38705. gl.attachShader( programGPU, fragmentShader );
  38706. gl.attachShader( programGPU, vertexShader );
  38707. gl.linkProgram( programGPU );
  38708. this.set( pipeline, {
  38709. programGPU,
  38710. fragmentShader,
  38711. vertexShader
  38712. } );
  38713. if ( promises !== null && this.parallel ) {
  38714. const p = new Promise( ( resolve /*, reject*/ ) => {
  38715. const parallel = this.parallel;
  38716. const checkStatus = () => {
  38717. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  38718. this._completeCompile( renderObject, pipeline );
  38719. resolve();
  38720. } else {
  38721. requestAnimationFrame( checkStatus );
  38722. }
  38723. };
  38724. checkStatus();
  38725. } );
  38726. promises.push( p );
  38727. return;
  38728. }
  38729. this._completeCompile( renderObject, pipeline );
  38730. }
  38731. /**
  38732. * Formats the source code of error messages.
  38733. *
  38734. * @private
  38735. * @param {String} string - The code.
  38736. * @param {Number} errorLine - The error line.
  38737. * @return {String} The formatted code.
  38738. */
  38739. _handleSource( string, errorLine ) {
  38740. const lines = string.split( '\n' );
  38741. const lines2 = [];
  38742. const from = Math.max( errorLine - 6, 0 );
  38743. const to = Math.min( errorLine + 6, lines.length );
  38744. for ( let i = from; i < to; i ++ ) {
  38745. const line = i + 1;
  38746. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  38747. }
  38748. return lines2.join( '\n' );
  38749. }
  38750. /**
  38751. * Gets the shader compilation errors from the info log.
  38752. *
  38753. * @private
  38754. * @param {WebGL2RenderingContext} gl - The rendering context.
  38755. * @param {WebGLShader} shader - The WebGL shader object.
  38756. * @param {String} type - The shader type.
  38757. * @return {String} The shader errors.
  38758. */
  38759. _getShaderErrors( gl, shader, type ) {
  38760. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  38761. const errors = gl.getShaderInfoLog( shader ).trim();
  38762. if ( status && errors === '' ) return '';
  38763. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  38764. if ( errorMatches ) {
  38765. const errorLine = parseInt( errorMatches[ 1 ] );
  38766. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  38767. } else {
  38768. return errors;
  38769. }
  38770. }
  38771. /**
  38772. * Logs shader compilation errors.
  38773. *
  38774. * @private
  38775. * @param {WebGLProgram} programGPU - The WebGL program.
  38776. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  38777. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  38778. */
  38779. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  38780. if ( this.renderer.debug.checkShaderErrors ) {
  38781. const gl = this.gl;
  38782. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  38783. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  38784. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  38785. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  38786. } else {
  38787. // default error reporting
  38788. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  38789. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  38790. console.error(
  38791. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  38792. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  38793. 'Program Info Log: ' + programLog + '\n' +
  38794. vertexErrors + '\n' +
  38795. fragmentErrors
  38796. );
  38797. }
  38798. } else if ( programLog !== '' ) {
  38799. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  38800. }
  38801. }
  38802. }
  38803. /**
  38804. * Completes the shader program setup for the given render object.
  38805. *
  38806. * @private
  38807. * @param {RenderObject} renderObject - The render object.
  38808. * @param {RenderPipeline} pipeline - The render pipeline.
  38809. */
  38810. _completeCompile( renderObject, pipeline ) {
  38811. const { state, gl } = this;
  38812. const pipelineData = this.get( pipeline );
  38813. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  38814. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  38815. this._logProgramError( programGPU, fragmentShader, vertexShader );
  38816. }
  38817. state.useProgram( programGPU );
  38818. // Bindings
  38819. const bindings = renderObject.getBindings();
  38820. this._setupBindings( bindings, programGPU );
  38821. //
  38822. this.set( pipeline, {
  38823. programGPU
  38824. } );
  38825. }
  38826. /**
  38827. * Creates a compute pipeline for the given compute node.
  38828. *
  38829. * @param {ComputePipeline} computePipeline - The compute pipeline.
  38830. * @param {Array<BindGroup>} bindings - The bindings.
  38831. */
  38832. createComputePipeline( computePipeline, bindings ) {
  38833. const { state, gl } = this;
  38834. // Program
  38835. const fragmentProgram = {
  38836. stage: 'fragment',
  38837. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  38838. };
  38839. this.createProgram( fragmentProgram );
  38840. const { computeProgram } = computePipeline;
  38841. const programGPU = gl.createProgram();
  38842. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  38843. const vertexShader = this.get( computeProgram ).shaderGPU;
  38844. const transforms = computeProgram.transforms;
  38845. const transformVaryingNames = [];
  38846. const transformAttributeNodes = [];
  38847. for ( let i = 0; i < transforms.length; i ++ ) {
  38848. const transform = transforms[ i ];
  38849. transformVaryingNames.push( transform.varyingName );
  38850. transformAttributeNodes.push( transform.attributeNode );
  38851. }
  38852. gl.attachShader( programGPU, fragmentShader );
  38853. gl.attachShader( programGPU, vertexShader );
  38854. gl.transformFeedbackVaryings(
  38855. programGPU,
  38856. transformVaryingNames,
  38857. gl.SEPARATE_ATTRIBS
  38858. );
  38859. gl.linkProgram( programGPU );
  38860. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  38861. this._logProgramError( programGPU, fragmentShader, vertexShader );
  38862. }
  38863. state.useProgram( programGPU );
  38864. // Bindings
  38865. this._setupBindings( bindings, programGPU );
  38866. const attributeNodes = computeProgram.attributes;
  38867. const attributes = [];
  38868. const transformBuffers = [];
  38869. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  38870. const attribute = attributeNodes[ i ].node.attribute;
  38871. attributes.push( attribute );
  38872. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  38873. }
  38874. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  38875. const attribute = transformAttributeNodes[ i ].attribute;
  38876. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  38877. const attributeData = this.get( attribute );
  38878. transformBuffers.push( attributeData );
  38879. }
  38880. //
  38881. this.set( computePipeline, {
  38882. programGPU,
  38883. transformBuffers,
  38884. attributes
  38885. } );
  38886. }
  38887. /**
  38888. * Creates bindings from the given bind group definition.
  38889. *
  38890. * @param {BindGroup} bindGroup - The bind group.
  38891. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38892. * @param {Number} cacheIndex - The cache index.
  38893. * @param {Number} version - The version.
  38894. */
  38895. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  38896. if ( this._knownBindings.has( bindings ) === false ) {
  38897. this._knownBindings.add( bindings );
  38898. let uniformBuffers = 0;
  38899. let textures = 0;
  38900. for ( const bindGroup of bindings ) {
  38901. this.set( bindGroup, {
  38902. textures: textures,
  38903. uniformBuffers: uniformBuffers
  38904. } );
  38905. for ( const binding of bindGroup.bindings ) {
  38906. if ( binding.isUniformBuffer ) uniformBuffers ++;
  38907. if ( binding.isSampledTexture ) textures ++;
  38908. }
  38909. }
  38910. }
  38911. this.updateBindings( bindGroup, bindings );
  38912. }
  38913. /**
  38914. * Updates the given bind group definition.
  38915. *
  38916. * @param {BindGroup} bindGroup - The bind group.
  38917. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38918. * @param {Number} cacheIndex - The cache index.
  38919. * @param {Number} version - The version.
  38920. */
  38921. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  38922. const { gl } = this;
  38923. const bindGroupData = this.get( bindGroup );
  38924. let i = bindGroupData.uniformBuffers;
  38925. let t = bindGroupData.textures;
  38926. for ( const binding of bindGroup.bindings ) {
  38927. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  38928. const data = binding.buffer;
  38929. const bufferGPU = gl.createBuffer();
  38930. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  38931. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  38932. this.set( binding, {
  38933. index: i ++,
  38934. bufferGPU
  38935. } );
  38936. } else if ( binding.isSampledTexture ) {
  38937. const { textureGPU, glTextureType } = this.get( binding.texture );
  38938. this.set( binding, {
  38939. index: t ++,
  38940. textureGPU,
  38941. glTextureType
  38942. } );
  38943. }
  38944. }
  38945. }
  38946. /**
  38947. * Updates a buffer binding.
  38948. *
  38949. * @param {Buffer} binding - The buffer binding to update.
  38950. */
  38951. updateBinding( binding ) {
  38952. const gl = this.gl;
  38953. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  38954. const bindingData = this.get( binding );
  38955. const bufferGPU = bindingData.bufferGPU;
  38956. const data = binding.buffer;
  38957. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  38958. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  38959. }
  38960. }
  38961. // attributes
  38962. /**
  38963. * Creates the buffer of an indexed shader attribute.
  38964. *
  38965. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  38966. */
  38967. createIndexAttribute( attribute ) {
  38968. const gl = this.gl;
  38969. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  38970. }
  38971. /**
  38972. * Creates the buffer of a shader attribute.
  38973. *
  38974. * @param {BufferAttribute} attribute - The buffer attribute.
  38975. */
  38976. createAttribute( attribute ) {
  38977. if ( this.has( attribute ) ) return;
  38978. const gl = this.gl;
  38979. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  38980. }
  38981. /**
  38982. * Creates the buffer of a storage attribute.
  38983. *
  38984. * @param {BufferAttribute} attribute - The buffer attribute.
  38985. */
  38986. createStorageAttribute( attribute ) {
  38987. if ( this.has( attribute ) ) return;
  38988. const gl = this.gl;
  38989. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  38990. }
  38991. /**
  38992. * Updates the buffer of a shader attribute.
  38993. *
  38994. * @param {BufferAttribute} attribute - The buffer attribute to update.
  38995. */
  38996. updateAttribute( attribute ) {
  38997. this.attributeUtils.updateAttribute( attribute );
  38998. }
  38999. /**
  39000. * Destroys the buffer of a shader attribute.
  39001. *
  39002. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  39003. */
  39004. destroyAttribute( attribute ) {
  39005. this.attributeUtils.destroyAttribute( attribute );
  39006. }
  39007. /**
  39008. * Checks if the given feature is supported by the backend.
  39009. *
  39010. * @param {String} name - The feature's name.
  39011. * @return {Boolean} Whether the feature is supported or not.
  39012. */
  39013. hasFeature( name ) {
  39014. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  39015. const extensions = this.extensions;
  39016. for ( let i = 0; i < keysMatching.length; i ++ ) {
  39017. if ( extensions.has( keysMatching[ i ] ) ) return true;
  39018. }
  39019. return false;
  39020. }
  39021. /**
  39022. * Returns the maximum anisotropy texture filtering value.
  39023. *
  39024. * @return {Number} The maximum anisotropy texture filtering value.
  39025. */
  39026. getMaxAnisotropy() {
  39027. return this.capabilities.getMaxAnisotropy();
  39028. }
  39029. /**
  39030. * Copies data of the given source texture to the given destination texture.
  39031. *
  39032. * @param {Texture} srcTexture - The source texture.
  39033. * @param {Texture} dstTexture - The destination texture.
  39034. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  39035. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  39036. * @param {Number} [level=0] - The mip level to copy.
  39037. */
  39038. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  39039. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  39040. }
  39041. /**
  39042. * Copies the current bound framebuffer to the given texture.
  39043. *
  39044. * @param {Texture} texture - The destination texture.
  39045. * @param {RenderContext} renderContext - The render context.
  39046. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  39047. */
  39048. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  39049. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  39050. }
  39051. /**
  39052. * Configures the active framebuffer from the given render context.
  39053. *
  39054. * @private
  39055. * @param {RenderContext} descriptor - The render context.
  39056. */
  39057. _setFramebuffer( descriptor ) {
  39058. const { gl, state } = this;
  39059. let currentFrameBuffer = null;
  39060. if ( descriptor.textures !== null ) {
  39061. const renderTarget = descriptor.renderTarget;
  39062. const renderTargetContextData = this.get( renderTarget );
  39063. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  39064. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  39065. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  39066. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  39067. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  39068. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  39069. const cacheKey = getCacheKey( descriptor );
  39070. let fb;
  39071. if ( isCube ) {
  39072. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  39073. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  39074. } else {
  39075. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  39076. fb = renderTargetContextData.framebuffers[ cacheKey ];
  39077. }
  39078. if ( fb === undefined ) {
  39079. fb = gl.createFramebuffer();
  39080. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  39081. const textures = descriptor.textures;
  39082. if ( isCube ) {
  39083. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  39084. const { textureGPU } = this.get( textures[ 0 ] );
  39085. const cubeFace = this.renderer._activeCubeFace;
  39086. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  39087. } else {
  39088. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  39089. for ( let i = 0; i < textures.length; i ++ ) {
  39090. const texture = textures[ i ];
  39091. const textureData = this.get( texture );
  39092. textureData.renderTarget = descriptor.renderTarget;
  39093. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  39094. const attachment = gl.COLOR_ATTACHMENT0 + i;
  39095. if ( isRenderTarget3D || isRenderTargetArray ) {
  39096. const layer = this.renderer._activeCubeFace;
  39097. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  39098. } else {
  39099. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39100. }
  39101. }
  39102. state.drawBuffers( descriptor, fb );
  39103. }
  39104. if ( descriptor.depthTexture !== null ) {
  39105. const textureData = this.get( descriptor.depthTexture );
  39106. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39107. textureData.renderTarget = descriptor.renderTarget;
  39108. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  39109. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  39110. }
  39111. }
  39112. if ( samples > 0 ) {
  39113. if ( msaaFb === undefined ) {
  39114. const invalidationArray = [];
  39115. msaaFb = gl.createFramebuffer();
  39116. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  39117. const msaaRenderbuffers = [];
  39118. const textures = descriptor.textures;
  39119. for ( let i = 0; i < textures.length; i ++ ) {
  39120. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  39121. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39122. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  39123. if ( depthBuffer ) {
  39124. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39125. invalidationArray.push( depthStyle );
  39126. }
  39127. const texture = descriptor.textures[ i ];
  39128. const textureData = this.get( texture );
  39129. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  39130. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  39131. }
  39132. renderTargetContextData.msaaFrameBuffer = msaaFb;
  39133. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  39134. if ( depthRenderbuffer === undefined ) {
  39135. depthRenderbuffer = gl.createRenderbuffer();
  39136. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  39137. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  39138. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  39139. invalidationArray.push( depthStyle );
  39140. }
  39141. renderTargetContextData.invalidationArray = invalidationArray;
  39142. }
  39143. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39144. } else {
  39145. currentFrameBuffer = fb;
  39146. }
  39147. }
  39148. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  39149. }
  39150. /**
  39151. * Computes the VAO key for the given index and attributes.
  39152. *
  39153. * @private
  39154. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  39155. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  39156. * @return {String} The VAO key.
  39157. */
  39158. _getVaoKey( index, attributes ) {
  39159. let key = '';
  39160. if ( index !== null ) {
  39161. const indexData = this.get( index );
  39162. key += ':' + indexData.id;
  39163. }
  39164. for ( let i = 0; i < attributes.length; i ++ ) {
  39165. const attributeData = this.get( attributes[ i ] );
  39166. key += ':' + attributeData.id;
  39167. }
  39168. return key;
  39169. }
  39170. /**
  39171. * Creates a VAO from the index and attributes.
  39172. *
  39173. * @private
  39174. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  39175. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  39176. * @return {Object} The VAO data.
  39177. */
  39178. _createVao( index, attributes ) {
  39179. const { gl } = this;
  39180. const vaoGPU = gl.createVertexArray();
  39181. let key = '';
  39182. let staticVao = true;
  39183. gl.bindVertexArray( vaoGPU );
  39184. if ( index !== null ) {
  39185. const indexData = this.get( index );
  39186. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  39187. key += ':' + indexData.id;
  39188. }
  39189. for ( let i = 0; i < attributes.length; i ++ ) {
  39190. const attribute = attributes[ i ];
  39191. const attributeData = this.get( attribute );
  39192. key += ':' + attributeData.id;
  39193. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  39194. gl.enableVertexAttribArray( i );
  39195. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  39196. let stride, offset;
  39197. if ( attribute.isInterleavedBufferAttribute === true ) {
  39198. stride = attribute.data.stride * attributeData.bytesPerElement;
  39199. offset = attribute.offset * attributeData.bytesPerElement;
  39200. } else {
  39201. stride = 0;
  39202. offset = 0;
  39203. }
  39204. if ( attributeData.isInteger ) {
  39205. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  39206. } else {
  39207. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  39208. }
  39209. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  39210. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  39211. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  39212. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  39213. }
  39214. }
  39215. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  39216. this.vaoCache[ key ] = vaoGPU;
  39217. return { vaoGPU, staticVao };
  39218. }
  39219. /**
  39220. * Creates a tranform feedback from the given transform buffers.
  39221. *
  39222. * @private
  39223. * @param {Array<DualAttributeData>} transformBuffers - The tranform buffers.
  39224. * @return {WebGLTransformFeedback} The tranform feedback.
  39225. */
  39226. _getTransformFeedback( transformBuffers ) {
  39227. let key = '';
  39228. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39229. key += ':' + transformBuffers[ i ].id;
  39230. }
  39231. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  39232. if ( transformFeedbackGPU !== undefined ) {
  39233. return transformFeedbackGPU;
  39234. }
  39235. const { gl } = this;
  39236. transformFeedbackGPU = gl.createTransformFeedback();
  39237. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  39238. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  39239. const attributeData = transformBuffers[ i ];
  39240. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  39241. }
  39242. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  39243. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  39244. return transformFeedbackGPU;
  39245. }
  39246. /**
  39247. * Setups the given bindings.
  39248. *
  39249. * @private
  39250. * @param {Array<BindGroup>} bindings - The bindings.
  39251. * @param {WebGLProgram} programGPU - The WebGL program.
  39252. */
  39253. _setupBindings( bindings, programGPU ) {
  39254. const gl = this.gl;
  39255. for ( const bindGroup of bindings ) {
  39256. for ( const binding of bindGroup.bindings ) {
  39257. const bindingData = this.get( binding );
  39258. const index = bindingData.index;
  39259. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39260. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  39261. gl.uniformBlockBinding( programGPU, location, index );
  39262. } else if ( binding.isSampledTexture ) {
  39263. const location = gl.getUniformLocation( programGPU, binding.name );
  39264. gl.uniform1i( location, index );
  39265. }
  39266. }
  39267. }
  39268. }
  39269. /**
  39270. * Binds the given uniforms.
  39271. *
  39272. * @private
  39273. * @param {Array<BindGroup>} bindings - The bindings.
  39274. */
  39275. _bindUniforms( bindings ) {
  39276. const { gl, state } = this;
  39277. for ( const bindGroup of bindings ) {
  39278. for ( const binding of bindGroup.bindings ) {
  39279. const bindingData = this.get( binding );
  39280. const index = bindingData.index;
  39281. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  39282. // TODO USE bindBufferRange to group multiple uniform buffers
  39283. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  39284. } else if ( binding.isSampledTexture ) {
  39285. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  39286. }
  39287. }
  39288. }
  39289. }
  39290. /**
  39291. * Frees internal resources.
  39292. */
  39293. dispose() {
  39294. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  39295. }
  39296. }
  39297. const GPUPrimitiveTopology = {
  39298. PointList: 'point-list',
  39299. LineList: 'line-list',
  39300. LineStrip: 'line-strip',
  39301. TriangleList: 'triangle-list',
  39302. TriangleStrip: 'triangle-strip',
  39303. };
  39304. const GPUCompareFunction = {
  39305. Never: 'never',
  39306. Less: 'less',
  39307. Equal: 'equal',
  39308. LessEqual: 'less-equal',
  39309. Greater: 'greater',
  39310. NotEqual: 'not-equal',
  39311. GreaterEqual: 'greater-equal',
  39312. Always: 'always'
  39313. };
  39314. const GPUStoreOp = {
  39315. Store: 'store',
  39316. Discard: 'discard'
  39317. };
  39318. const GPULoadOp = {
  39319. Load: 'load',
  39320. Clear: 'clear'
  39321. };
  39322. const GPUFrontFace = {
  39323. CCW: 'ccw',
  39324. CW: 'cw'
  39325. };
  39326. const GPUCullMode = {
  39327. None: 'none',
  39328. Front: 'front',
  39329. Back: 'back'
  39330. };
  39331. const GPUIndexFormat = {
  39332. Uint16: 'uint16',
  39333. Uint32: 'uint32'
  39334. };
  39335. const GPUTextureFormat = {
  39336. // 8-bit formats
  39337. R8Unorm: 'r8unorm',
  39338. R8Snorm: 'r8snorm',
  39339. R8Uint: 'r8uint',
  39340. R8Sint: 'r8sint',
  39341. // 16-bit formats
  39342. R16Uint: 'r16uint',
  39343. R16Sint: 'r16sint',
  39344. R16Float: 'r16float',
  39345. RG8Unorm: 'rg8unorm',
  39346. RG8Snorm: 'rg8snorm',
  39347. RG8Uint: 'rg8uint',
  39348. RG8Sint: 'rg8sint',
  39349. // 32-bit formats
  39350. R32Uint: 'r32uint',
  39351. R32Sint: 'r32sint',
  39352. R32Float: 'r32float',
  39353. RG16Uint: 'rg16uint',
  39354. RG16Sint: 'rg16sint',
  39355. RG16Float: 'rg16float',
  39356. RGBA8Unorm: 'rgba8unorm',
  39357. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  39358. RGBA8Snorm: 'rgba8snorm',
  39359. RGBA8Uint: 'rgba8uint',
  39360. RGBA8Sint: 'rgba8sint',
  39361. BGRA8Unorm: 'bgra8unorm',
  39362. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  39363. // Packed 32-bit formats
  39364. RGB9E5UFloat: 'rgb9e5ufloat',
  39365. RGB10A2Unorm: 'rgb10a2unorm',
  39366. RG11B10uFloat: 'rgb10a2unorm',
  39367. // 64-bit formats
  39368. RG32Uint: 'rg32uint',
  39369. RG32Sint: 'rg32sint',
  39370. RG32Float: 'rg32float',
  39371. RGBA16Uint: 'rgba16uint',
  39372. RGBA16Sint: 'rgba16sint',
  39373. RGBA16Float: 'rgba16float',
  39374. // 128-bit formats
  39375. RGBA32Uint: 'rgba32uint',
  39376. RGBA32Sint: 'rgba32sint',
  39377. RGBA32Float: 'rgba32float',
  39378. // Depth and stencil formats
  39379. Stencil8: 'stencil8',
  39380. Depth16Unorm: 'depth16unorm',
  39381. Depth24Plus: 'depth24plus',
  39382. Depth24PlusStencil8: 'depth24plus-stencil8',
  39383. Depth32Float: 'depth32float',
  39384. // 'depth32float-stencil8' extension
  39385. Depth32FloatStencil8: 'depth32float-stencil8',
  39386. // BC compressed formats usable if 'texture-compression-bc' is both
  39387. // supported by the device/user agent and enabled in requestDevice.
  39388. BC1RGBAUnorm: 'bc1-rgba-unorm',
  39389. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  39390. BC2RGBAUnorm: 'bc2-rgba-unorm',
  39391. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  39392. BC3RGBAUnorm: 'bc3-rgba-unorm',
  39393. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  39394. BC4RUnorm: 'bc4-r-unorm',
  39395. BC4RSnorm: 'bc4-r-snorm',
  39396. BC5RGUnorm: 'bc5-rg-unorm',
  39397. BC5RGSnorm: 'bc5-rg-snorm',
  39398. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  39399. BC6HRGBFloat: 'bc6h-rgb-float',
  39400. BC7RGBAUnorm: 'bc7-rgba-unorm',
  39401. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  39402. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  39403. // supported by the device/user agent and enabled in requestDevice.
  39404. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  39405. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  39406. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  39407. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  39408. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  39409. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  39410. EACR11Unorm: 'eac-r11unorm',
  39411. EACR11Snorm: 'eac-r11snorm',
  39412. EACRG11Unorm: 'eac-rg11unorm',
  39413. EACRG11Snorm: 'eac-rg11snorm',
  39414. // ASTC compressed formats usable if 'texture-compression-astc' is both
  39415. // supported by the device/user agent and enabled in requestDevice.
  39416. ASTC4x4Unorm: 'astc-4x4-unorm',
  39417. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  39418. ASTC5x4Unorm: 'astc-5x4-unorm',
  39419. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  39420. ASTC5x5Unorm: 'astc-5x5-unorm',
  39421. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  39422. ASTC6x5Unorm: 'astc-6x5-unorm',
  39423. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  39424. ASTC6x6Unorm: 'astc-6x6-unorm',
  39425. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  39426. ASTC8x5Unorm: 'astc-8x5-unorm',
  39427. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  39428. ASTC8x6Unorm: 'astc-8x6-unorm',
  39429. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  39430. ASTC8x8Unorm: 'astc-8x8-unorm',
  39431. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  39432. ASTC10x5Unorm: 'astc-10x5-unorm',
  39433. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  39434. ASTC10x6Unorm: 'astc-10x6-unorm',
  39435. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  39436. ASTC10x8Unorm: 'astc-10x8-unorm',
  39437. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  39438. ASTC10x10Unorm: 'astc-10x10-unorm',
  39439. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  39440. ASTC12x10Unorm: 'astc-12x10-unorm',
  39441. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  39442. ASTC12x12Unorm: 'astc-12x12-unorm',
  39443. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  39444. };
  39445. const GPUAddressMode = {
  39446. ClampToEdge: 'clamp-to-edge',
  39447. Repeat: 'repeat',
  39448. MirrorRepeat: 'mirror-repeat'
  39449. };
  39450. const GPUFilterMode = {
  39451. Linear: 'linear',
  39452. Nearest: 'nearest'
  39453. };
  39454. const GPUBlendFactor = {
  39455. Zero: 'zero',
  39456. One: 'one',
  39457. Src: 'src',
  39458. OneMinusSrc: 'one-minus-src',
  39459. SrcAlpha: 'src-alpha',
  39460. OneMinusSrcAlpha: 'one-minus-src-alpha',
  39461. Dst: 'dst',
  39462. OneMinusDstColor: 'one-minus-dst',
  39463. DstAlpha: 'dst-alpha',
  39464. OneMinusDstAlpha: 'one-minus-dst-alpha',
  39465. SrcAlphaSaturated: 'src-alpha-saturated',
  39466. Constant: 'constant',
  39467. OneMinusConstant: 'one-minus-constant'
  39468. };
  39469. const GPUBlendOperation = {
  39470. Add: 'add',
  39471. Subtract: 'subtract',
  39472. ReverseSubtract: 'reverse-subtract',
  39473. Min: 'min',
  39474. Max: 'max'
  39475. };
  39476. const GPUColorWriteFlags = {
  39477. None: 0,
  39478. Red: 0x1,
  39479. Green: 0x2,
  39480. Blue: 0x4,
  39481. Alpha: 0x8,
  39482. All: 0xF
  39483. };
  39484. const GPUStencilOperation = {
  39485. Keep: 'keep',
  39486. Zero: 'zero',
  39487. Replace: 'replace',
  39488. Invert: 'invert',
  39489. IncrementClamp: 'increment-clamp',
  39490. DecrementClamp: 'decrement-clamp',
  39491. IncrementWrap: 'increment-wrap',
  39492. DecrementWrap: 'decrement-wrap'
  39493. };
  39494. const GPUBufferBindingType = {
  39495. Uniform: 'uniform',
  39496. Storage: 'storage',
  39497. ReadOnlyStorage: 'read-only-storage'
  39498. };
  39499. const GPUStorageTextureAccess = {
  39500. WriteOnly: 'write-only',
  39501. ReadOnly: 'read-only',
  39502. ReadWrite: 'read-write',
  39503. };
  39504. const GPUTextureSampleType = {
  39505. Float: 'float',
  39506. UnfilterableFloat: 'unfilterable-float',
  39507. Depth: 'depth',
  39508. SInt: 'sint',
  39509. UInt: 'uint'
  39510. };
  39511. const GPUTextureDimension = {
  39512. OneD: '1d',
  39513. TwoD: '2d',
  39514. ThreeD: '3d'
  39515. };
  39516. const GPUTextureViewDimension = {
  39517. OneD: '1d',
  39518. TwoD: '2d',
  39519. TwoDArray: '2d-array',
  39520. Cube: 'cube',
  39521. CubeArray: 'cube-array',
  39522. ThreeD: '3d'
  39523. };
  39524. const GPUTextureAspect = {
  39525. All: 'all',
  39526. StencilOnly: 'stencil-only',
  39527. DepthOnly: 'depth-only'
  39528. };
  39529. const GPUInputStepMode = {
  39530. Vertex: 'vertex',
  39531. Instance: 'instance'
  39532. };
  39533. const GPUFeatureName = {
  39534. DepthClipControl: 'depth-clip-control',
  39535. Depth32FloatStencil8: 'depth32float-stencil8',
  39536. TextureCompressionBC: 'texture-compression-bc',
  39537. TextureCompressionETC2: 'texture-compression-etc2',
  39538. TextureCompressionASTC: 'texture-compression-astc',
  39539. TimestampQuery: 'timestamp-query',
  39540. IndirectFirstInstance: 'indirect-first-instance',
  39541. ShaderF16: 'shader-f16',
  39542. RG11B10UFloat: 'rg11b10ufloat-renderable',
  39543. BGRA8UNormStorage: 'bgra8unorm-storage',
  39544. Float32Filterable: 'float32-filterable',
  39545. ClipDistances: 'clip-distances',
  39546. DualSourceBlending: 'dual-source-blending',
  39547. Subgroups: 'subgroups'
  39548. };
  39549. /**
  39550. * Represents a sampler binding type.
  39551. *
  39552. * @private
  39553. * @augments Binding
  39554. */
  39555. class Sampler extends Binding {
  39556. /**
  39557. * Constructs a new sampler.
  39558. *
  39559. * @param {String} name - The samplers's name.
  39560. * @param {Texture?} texture - The texture this binding is referring to.
  39561. */
  39562. constructor( name, texture ) {
  39563. super( name );
  39564. /**
  39565. * The texture the sampler is referring to.
  39566. *
  39567. * @type {Texture?}
  39568. */
  39569. this.texture = texture;
  39570. /**
  39571. * The binding's version.
  39572. *
  39573. * @type {Number}
  39574. */
  39575. this.version = texture ? texture.version : 0;
  39576. /**
  39577. * This flag can be used for type testing.
  39578. *
  39579. * @type {Boolean}
  39580. * @readonly
  39581. * @default true
  39582. */
  39583. this.isSampler = true;
  39584. }
  39585. }
  39586. /**
  39587. * A special form of sampler binding type.
  39588. * It's texture value is managed by a node object.
  39589. *
  39590. * @private
  39591. * @augments Sampler
  39592. */
  39593. class NodeSampler extends Sampler {
  39594. /**
  39595. * Constructs a new node-based sampler.
  39596. *
  39597. * @param {String} name - The samplers's name.
  39598. * @param {TextureNode} textureNode - The texture node.
  39599. * @param {UniformGroupNode} groupNode - The uniform group node.
  39600. */
  39601. constructor( name, textureNode, groupNode ) {
  39602. super( name, textureNode ? textureNode.value : null );
  39603. /**
  39604. * The texture node.
  39605. *
  39606. * @type {TextureNode}
  39607. */
  39608. this.textureNode = textureNode;
  39609. /**
  39610. * The uniform group node.
  39611. *
  39612. * @type {UniformGroupNode}
  39613. */
  39614. this.groupNode = groupNode;
  39615. }
  39616. /**
  39617. * Updates the texture value of this sampler.
  39618. */
  39619. update() {
  39620. this.texture = this.textureNode.value;
  39621. }
  39622. }
  39623. /**
  39624. * Represents a storage buffer binding type.
  39625. *
  39626. * @private
  39627. * @augments Buffer
  39628. */
  39629. class StorageBuffer extends Buffer {
  39630. /**
  39631. * Constructs a new uniform buffer.
  39632. *
  39633. * @param {String} name - The buffer's name.
  39634. * @param {BufferAttribute} attribute - The buffer attribute.
  39635. */
  39636. constructor( name, attribute ) {
  39637. super( name, attribute ? attribute.array : null );
  39638. /**
  39639. * This flag can be used for type testing.
  39640. *
  39641. * @type {BufferAttribute}
  39642. */
  39643. this.attribute = attribute;
  39644. /**
  39645. * This flag can be used for type testing.
  39646. *
  39647. * @type {Boolean}
  39648. * @readonly
  39649. * @default true
  39650. */
  39651. this.isStorageBuffer = true;
  39652. }
  39653. }
  39654. let _id = 0;
  39655. /**
  39656. * A special form of storage buffer binding type.
  39657. * It's buffer value is managed by a node object.
  39658. *
  39659. * @private
  39660. * @augments StorageBuffer
  39661. */
  39662. class NodeStorageBuffer extends StorageBuffer {
  39663. /**
  39664. * Constructs a new node-based storage buffer.
  39665. *
  39666. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  39667. * @param {UniformGroupNode} groupNode - The uniform group node.
  39668. */
  39669. constructor( nodeUniform, groupNode ) {
  39670. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  39671. /**
  39672. * The node uniform.
  39673. *
  39674. * @type {StorageBufferNode}
  39675. */
  39676. this.nodeUniform = nodeUniform;
  39677. /**
  39678. * The access type.
  39679. *
  39680. * @type {String}
  39681. */
  39682. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  39683. /**
  39684. * The uniform group node.
  39685. *
  39686. * @type {UniformGroupNode}
  39687. */
  39688. this.groupNode = groupNode;
  39689. }
  39690. /**
  39691. * The storage buffer.
  39692. *
  39693. * @type {BufferAttribute}
  39694. */
  39695. get buffer() {
  39696. return this.nodeUniform.value;
  39697. }
  39698. }
  39699. class WebGPUTexturePassUtils extends DataMap {
  39700. constructor( device ) {
  39701. super();
  39702. this.device = device;
  39703. const mipmapVertexSource = `
  39704. struct VarysStruct {
  39705. @builtin( position ) Position: vec4<f32>,
  39706. @location( 0 ) vTex : vec2<f32>
  39707. };
  39708. @vertex
  39709. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  39710. var Varys : VarysStruct;
  39711. var pos = array< vec2<f32>, 4 >(
  39712. vec2<f32>( -1.0, 1.0 ),
  39713. vec2<f32>( 1.0, 1.0 ),
  39714. vec2<f32>( -1.0, -1.0 ),
  39715. vec2<f32>( 1.0, -1.0 )
  39716. );
  39717. var tex = array< vec2<f32>, 4 >(
  39718. vec2<f32>( 0.0, 0.0 ),
  39719. vec2<f32>( 1.0, 0.0 ),
  39720. vec2<f32>( 0.0, 1.0 ),
  39721. vec2<f32>( 1.0, 1.0 )
  39722. );
  39723. Varys.vTex = tex[ vertexIndex ];
  39724. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  39725. return Varys;
  39726. }
  39727. `;
  39728. const mipmapFragmentSource = `
  39729. @group( 0 ) @binding( 0 )
  39730. var imgSampler : sampler;
  39731. @group( 0 ) @binding( 1 )
  39732. var img : texture_2d<f32>;
  39733. @fragment
  39734. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  39735. return textureSample( img, imgSampler, vTex );
  39736. }
  39737. `;
  39738. const flipYFragmentSource = `
  39739. @group( 0 ) @binding( 0 )
  39740. var imgSampler : sampler;
  39741. @group( 0 ) @binding( 1 )
  39742. var img : texture_2d<f32>;
  39743. @fragment
  39744. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  39745. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  39746. }
  39747. `;
  39748. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  39749. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  39750. // We'll need a new pipeline for every texture format used.
  39751. this.transferPipelines = {};
  39752. this.flipYPipelines = {};
  39753. this.mipmapVertexShaderModule = device.createShaderModule( {
  39754. label: 'mipmapVertex',
  39755. code: mipmapVertexSource
  39756. } );
  39757. this.mipmapFragmentShaderModule = device.createShaderModule( {
  39758. label: 'mipmapFragment',
  39759. code: mipmapFragmentSource
  39760. } );
  39761. this.flipYFragmentShaderModule = device.createShaderModule( {
  39762. label: 'flipYFragment',
  39763. code: flipYFragmentSource
  39764. } );
  39765. }
  39766. getTransferPipeline( format ) {
  39767. let pipeline = this.transferPipelines[ format ];
  39768. if ( pipeline === undefined ) {
  39769. pipeline = this.device.createRenderPipeline( {
  39770. label: `mipmap-${ format }`,
  39771. vertex: {
  39772. module: this.mipmapVertexShaderModule,
  39773. entryPoint: 'main'
  39774. },
  39775. fragment: {
  39776. module: this.mipmapFragmentShaderModule,
  39777. entryPoint: 'main',
  39778. targets: [ { format } ]
  39779. },
  39780. primitive: {
  39781. topology: GPUPrimitiveTopology.TriangleStrip,
  39782. stripIndexFormat: GPUIndexFormat.Uint32
  39783. },
  39784. layout: 'auto'
  39785. } );
  39786. this.transferPipelines[ format ] = pipeline;
  39787. }
  39788. return pipeline;
  39789. }
  39790. getFlipYPipeline( format ) {
  39791. let pipeline = this.flipYPipelines[ format ];
  39792. if ( pipeline === undefined ) {
  39793. pipeline = this.device.createRenderPipeline( {
  39794. label: `flipY-${ format }`,
  39795. vertex: {
  39796. module: this.mipmapVertexShaderModule,
  39797. entryPoint: 'main'
  39798. },
  39799. fragment: {
  39800. module: this.flipYFragmentShaderModule,
  39801. entryPoint: 'main',
  39802. targets: [ { format } ]
  39803. },
  39804. primitive: {
  39805. topology: GPUPrimitiveTopology.TriangleStrip,
  39806. stripIndexFormat: GPUIndexFormat.Uint32
  39807. },
  39808. layout: 'auto'
  39809. } );
  39810. this.flipYPipelines[ format ] = pipeline;
  39811. }
  39812. return pipeline;
  39813. }
  39814. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  39815. const format = textureGPUDescriptor.format;
  39816. const { width, height } = textureGPUDescriptor.size;
  39817. const transferPipeline = this.getTransferPipeline( format );
  39818. const flipYPipeline = this.getFlipYPipeline( format );
  39819. const tempTexture = this.device.createTexture( {
  39820. size: { width, height, depthOrArrayLayers: 1 },
  39821. format,
  39822. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  39823. } );
  39824. const srcView = textureGPU.createView( {
  39825. baseMipLevel: 0,
  39826. mipLevelCount: 1,
  39827. dimension: GPUTextureViewDimension.TwoD,
  39828. baseArrayLayer
  39829. } );
  39830. const dstView = tempTexture.createView( {
  39831. baseMipLevel: 0,
  39832. mipLevelCount: 1,
  39833. dimension: GPUTextureViewDimension.TwoD,
  39834. baseArrayLayer: 0
  39835. } );
  39836. const commandEncoder = this.device.createCommandEncoder( {} );
  39837. const pass = ( pipeline, sourceView, destinationView ) => {
  39838. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  39839. const bindGroup = this.device.createBindGroup( {
  39840. layout: bindGroupLayout,
  39841. entries: [ {
  39842. binding: 0,
  39843. resource: this.flipYSampler
  39844. }, {
  39845. binding: 1,
  39846. resource: sourceView
  39847. } ]
  39848. } );
  39849. const passEncoder = commandEncoder.beginRenderPass( {
  39850. colorAttachments: [ {
  39851. view: destinationView,
  39852. loadOp: GPULoadOp.Clear,
  39853. storeOp: GPUStoreOp.Store,
  39854. clearValue: [ 0, 0, 0, 0 ]
  39855. } ]
  39856. } );
  39857. passEncoder.setPipeline( pipeline );
  39858. passEncoder.setBindGroup( 0, bindGroup );
  39859. passEncoder.draw( 4, 1, 0, 0 );
  39860. passEncoder.end();
  39861. };
  39862. pass( transferPipeline, srcView, dstView );
  39863. pass( flipYPipeline, dstView, srcView );
  39864. this.device.queue.submit( [ commandEncoder.finish() ] );
  39865. tempTexture.destroy();
  39866. }
  39867. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  39868. const textureData = this.get( textureGPU );
  39869. if ( textureData.useCount === undefined ) {
  39870. textureData.useCount = 0;
  39871. textureData.layers = [];
  39872. }
  39873. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  39874. const commandEncoder = this.device.createCommandEncoder( {} );
  39875. this._mipmapRunBundles( commandEncoder, passes );
  39876. this.device.queue.submit( [ commandEncoder.finish() ] );
  39877. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  39878. textureData.useCount ++;
  39879. }
  39880. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  39881. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  39882. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  39883. let srcView = textureGPU.createView( {
  39884. baseMipLevel: 0,
  39885. mipLevelCount: 1,
  39886. dimension: GPUTextureViewDimension.TwoD,
  39887. baseArrayLayer
  39888. } );
  39889. const passes = [];
  39890. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  39891. const bindGroup = this.device.createBindGroup( {
  39892. layout: bindGroupLayout,
  39893. entries: [ {
  39894. binding: 0,
  39895. resource: this.mipmapSampler
  39896. }, {
  39897. binding: 1,
  39898. resource: srcView
  39899. } ]
  39900. } );
  39901. const dstView = textureGPU.createView( {
  39902. baseMipLevel: i,
  39903. mipLevelCount: 1,
  39904. dimension: GPUTextureViewDimension.TwoD,
  39905. baseArrayLayer
  39906. } );
  39907. const passDescriptor = {
  39908. colorAttachments: [ {
  39909. view: dstView,
  39910. loadOp: GPULoadOp.Clear,
  39911. storeOp: GPUStoreOp.Store,
  39912. clearValue: [ 0, 0, 0, 0 ]
  39913. } ]
  39914. };
  39915. const passEncoder = this.device.createRenderBundleEncoder( {
  39916. colorFormats: [ textureGPUDescriptor.format ]
  39917. } );
  39918. passEncoder.setPipeline( pipeline );
  39919. passEncoder.setBindGroup( 0, bindGroup );
  39920. passEncoder.draw( 4, 1, 0, 0 );
  39921. passes.push( {
  39922. renderBundles: [ passEncoder.finish() ],
  39923. passDescriptor
  39924. } );
  39925. srcView = dstView;
  39926. }
  39927. return passes;
  39928. }
  39929. _mipmapRunBundles( commandEncoder, passes ) {
  39930. const levels = passes.length;
  39931. for ( let i = 0; i < levels; i ++ ) {
  39932. const pass = passes[ i ];
  39933. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  39934. passEncoder.executeBundles( pass.renderBundles );
  39935. passEncoder.end();
  39936. }
  39937. }
  39938. }
  39939. const _compareToWebGPU = {
  39940. [ NeverCompare ]: 'never',
  39941. [ LessCompare ]: 'less',
  39942. [ EqualCompare ]: 'equal',
  39943. [ LessEqualCompare ]: 'less-equal',
  39944. [ GreaterCompare ]: 'greater',
  39945. [ GreaterEqualCompare ]: 'greater-equal',
  39946. [ AlwaysCompare ]: 'always',
  39947. [ NotEqualCompare ]: 'not-equal'
  39948. };
  39949. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  39950. class WebGPUTextureUtils {
  39951. constructor( backend ) {
  39952. this.backend = backend;
  39953. this._passUtils = null;
  39954. this.defaultTexture = {};
  39955. this.defaultCubeTexture = {};
  39956. this.defaultVideoFrame = null;
  39957. this.colorBuffer = null;
  39958. this.depthTexture = new DepthTexture();
  39959. this.depthTexture.name = 'depthBuffer';
  39960. }
  39961. createSampler( texture ) {
  39962. const backend = this.backend;
  39963. const device = backend.device;
  39964. const textureGPU = backend.get( texture );
  39965. const samplerDescriptorGPU = {
  39966. addressModeU: this._convertAddressMode( texture.wrapS ),
  39967. addressModeV: this._convertAddressMode( texture.wrapT ),
  39968. addressModeW: this._convertAddressMode( texture.wrapR ),
  39969. magFilter: this._convertFilterMode( texture.magFilter ),
  39970. minFilter: this._convertFilterMode( texture.minFilter ),
  39971. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  39972. maxAnisotropy: 1
  39973. };
  39974. // anisotropy can only be used when all filter modes are set to linear.
  39975. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  39976. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  39977. }
  39978. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  39979. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  39980. }
  39981. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  39982. }
  39983. createDefaultTexture( texture ) {
  39984. let textureGPU;
  39985. const format = getFormat( texture );
  39986. if ( texture.isCubeTexture ) {
  39987. textureGPU = this._getDefaultCubeTextureGPU( format );
  39988. } else if ( texture.isVideoTexture ) {
  39989. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  39990. } else {
  39991. textureGPU = this._getDefaultTextureGPU( format );
  39992. }
  39993. this.backend.get( texture ).texture = textureGPU;
  39994. }
  39995. createTexture( texture, options = {} ) {
  39996. const backend = this.backend;
  39997. const textureData = backend.get( texture );
  39998. if ( textureData.initialized ) {
  39999. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  40000. }
  40001. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  40002. if ( options.levels === undefined ) options.levels = 1;
  40003. if ( options.depth === undefined ) options.depth = 1;
  40004. const { width, height, depth, levels } = options;
  40005. if ( texture.isFramebufferTexture ) {
  40006. if ( options.renderTarget ) {
  40007. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  40008. } else {
  40009. options.format = this.backend.utils.getPreferredCanvasFormat();
  40010. }
  40011. }
  40012. const dimension = this._getDimension( texture );
  40013. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  40014. textureData.format = format;
  40015. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  40016. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  40017. if ( texture.isStorageTexture === true ) {
  40018. usage |= GPUTextureUsage.STORAGE_BINDING;
  40019. }
  40020. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  40021. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  40022. }
  40023. const textureDescriptorGPU = {
  40024. label: texture.name,
  40025. size: {
  40026. width: width,
  40027. height: height,
  40028. depthOrArrayLayers: depth,
  40029. },
  40030. mipLevelCount: levels,
  40031. sampleCount: primarySamples,
  40032. dimension: dimension,
  40033. format: format,
  40034. usage: usage
  40035. };
  40036. // texture creation
  40037. if ( texture.isVideoTexture ) {
  40038. const video = texture.source.data;
  40039. const videoFrame = new VideoFrame( video );
  40040. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  40041. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  40042. videoFrame.close();
  40043. textureData.externalTexture = video;
  40044. } else {
  40045. if ( format === undefined ) {
  40046. console.warn( 'WebGPURenderer: Texture format not supported.' );
  40047. return this.createDefaultTexture( texture );
  40048. }
  40049. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  40050. }
  40051. if ( isMSAA ) {
  40052. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  40053. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  40054. msaaTextureDescriptorGPU.sampleCount = samples;
  40055. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  40056. }
  40057. textureData.initialized = true;
  40058. textureData.textureDescriptorGPU = textureDescriptorGPU;
  40059. }
  40060. destroyTexture( texture ) {
  40061. const backend = this.backend;
  40062. const textureData = backend.get( texture );
  40063. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  40064. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  40065. backend.delete( texture );
  40066. }
  40067. destroySampler( texture ) {
  40068. const backend = this.backend;
  40069. const textureData = backend.get( texture );
  40070. delete textureData.sampler;
  40071. }
  40072. generateMipmaps( texture ) {
  40073. const textureData = this.backend.get( texture );
  40074. if ( texture.isCubeTexture ) {
  40075. for ( let i = 0; i < 6; i ++ ) {
  40076. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  40077. }
  40078. } else {
  40079. const depth = texture.image.depth || 1;
  40080. for ( let i = 0; i < depth; i ++ ) {
  40081. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  40082. }
  40083. }
  40084. }
  40085. getColorBuffer() {
  40086. if ( this.colorBuffer ) this.colorBuffer.destroy();
  40087. const backend = this.backend;
  40088. const { width, height } = backend.getDrawingBufferSize();
  40089. this.colorBuffer = backend.device.createTexture( {
  40090. label: 'colorBuffer',
  40091. size: {
  40092. width: width,
  40093. height: height,
  40094. depthOrArrayLayers: 1
  40095. },
  40096. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  40097. format: backend.utils.getPreferredCanvasFormat(),
  40098. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  40099. } );
  40100. return this.colorBuffer;
  40101. }
  40102. getDepthBuffer( depth = true, stencil = false ) {
  40103. const backend = this.backend;
  40104. const { width, height } = backend.getDrawingBufferSize();
  40105. const depthTexture = this.depthTexture;
  40106. const depthTextureGPU = backend.get( depthTexture ).texture;
  40107. let format, type;
  40108. if ( stencil ) {
  40109. format = DepthStencilFormat;
  40110. type = UnsignedInt248Type;
  40111. } else if ( depth ) {
  40112. format = DepthFormat;
  40113. type = UnsignedIntType;
  40114. }
  40115. if ( depthTextureGPU !== undefined ) {
  40116. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  40117. return depthTextureGPU;
  40118. }
  40119. this.destroyTexture( depthTexture );
  40120. }
  40121. depthTexture.name = 'depthBuffer';
  40122. depthTexture.format = format;
  40123. depthTexture.type = type;
  40124. depthTexture.image.width = width;
  40125. depthTexture.image.height = height;
  40126. this.createTexture( depthTexture, { width, height } );
  40127. return backend.get( depthTexture ).texture;
  40128. }
  40129. updateTexture( texture, options ) {
  40130. const textureData = this.backend.get( texture );
  40131. const { textureDescriptorGPU } = textureData;
  40132. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  40133. return;
  40134. // transfer texture data
  40135. if ( texture.isDataTexture ) {
  40136. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40137. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  40138. for ( let i = 0; i < options.image.depth; i ++ ) {
  40139. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  40140. }
  40141. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  40142. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  40143. } else if ( texture.isCubeTexture ) {
  40144. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  40145. } else if ( texture.isVideoTexture ) {
  40146. const video = texture.source.data;
  40147. textureData.externalTexture = video;
  40148. } else {
  40149. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  40150. }
  40151. //
  40152. textureData.version = texture.version;
  40153. if ( texture.onUpdate ) texture.onUpdate( texture );
  40154. }
  40155. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40156. const device = this.backend.device;
  40157. const textureData = this.backend.get( texture );
  40158. const textureGPU = textureData.texture;
  40159. const format = textureData.textureDescriptorGPU.format;
  40160. const bytesPerTexel = this._getBytesPerTexel( format );
  40161. let bytesPerRow = width * bytesPerTexel;
  40162. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  40163. const readBuffer = device.createBuffer(
  40164. {
  40165. size: width * height * bytesPerTexel,
  40166. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  40167. }
  40168. );
  40169. const encoder = device.createCommandEncoder();
  40170. encoder.copyTextureToBuffer(
  40171. {
  40172. texture: textureGPU,
  40173. origin: { x, y, z: faceIndex },
  40174. },
  40175. {
  40176. buffer: readBuffer,
  40177. bytesPerRow: bytesPerRow
  40178. },
  40179. {
  40180. width: width,
  40181. height: height
  40182. }
  40183. );
  40184. const typedArrayType = this._getTypedArrayType( format );
  40185. device.queue.submit( [ encoder.finish() ] );
  40186. await readBuffer.mapAsync( GPUMapMode.READ );
  40187. const buffer = readBuffer.getMappedRange();
  40188. return new typedArrayType( buffer );
  40189. }
  40190. _isEnvironmentTexture( texture ) {
  40191. const mapping = texture.mapping;
  40192. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  40193. }
  40194. _getDefaultTextureGPU( format ) {
  40195. let defaultTexture = this.defaultTexture[ format ];
  40196. if ( defaultTexture === undefined ) {
  40197. const texture = new Texture();
  40198. texture.minFilter = NearestFilter;
  40199. texture.magFilter = NearestFilter;
  40200. this.createTexture( texture, { width: 1, height: 1, format } );
  40201. this.defaultTexture[ format ] = defaultTexture = texture;
  40202. }
  40203. return this.backend.get( defaultTexture ).texture;
  40204. }
  40205. _getDefaultCubeTextureGPU( format ) {
  40206. let defaultCubeTexture = this.defaultTexture[ format ];
  40207. if ( defaultCubeTexture === undefined ) {
  40208. const texture = new CubeTexture();
  40209. texture.minFilter = NearestFilter;
  40210. texture.magFilter = NearestFilter;
  40211. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  40212. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  40213. }
  40214. return this.backend.get( defaultCubeTexture ).texture;
  40215. }
  40216. _getDefaultVideoFrame() {
  40217. let defaultVideoFrame = this.defaultVideoFrame;
  40218. if ( defaultVideoFrame === null ) {
  40219. const init = {
  40220. timestamp: 0,
  40221. codedWidth: 1,
  40222. codedHeight: 1,
  40223. format: 'RGBA',
  40224. };
  40225. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  40226. }
  40227. return defaultVideoFrame;
  40228. }
  40229. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  40230. for ( let i = 0; i < 6; i ++ ) {
  40231. const image = images[ i ];
  40232. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  40233. if ( image.isDataTexture ) {
  40234. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40235. } else {
  40236. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  40237. }
  40238. }
  40239. }
  40240. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  40241. const device = this.backend.device;
  40242. device.queue.copyExternalImageToTexture(
  40243. {
  40244. source: image
  40245. }, {
  40246. texture: textureGPU,
  40247. mipLevel: 0,
  40248. origin: { x: 0, y: 0, z: originDepth }
  40249. }, {
  40250. width: image.width,
  40251. height: image.height,
  40252. depthOrArrayLayers: 1
  40253. }
  40254. );
  40255. if ( flipY === true ) {
  40256. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40257. }
  40258. }
  40259. _getPassUtils() {
  40260. let passUtils = this._passUtils;
  40261. if ( passUtils === null ) {
  40262. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  40263. }
  40264. return passUtils;
  40265. }
  40266. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  40267. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  40268. }
  40269. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  40270. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  40271. }
  40272. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  40273. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40274. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  40275. const device = this.backend.device;
  40276. const data = image.data;
  40277. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  40278. const bytesPerRow = image.width * bytesPerTexel;
  40279. device.queue.writeTexture(
  40280. {
  40281. texture: textureGPU,
  40282. mipLevel: 0,
  40283. origin: { x: 0, y: 0, z: originDepth }
  40284. },
  40285. data,
  40286. {
  40287. offset: image.width * image.height * bytesPerTexel * depth,
  40288. bytesPerRow
  40289. },
  40290. {
  40291. width: image.width,
  40292. height: image.height,
  40293. depthOrArrayLayers: 1
  40294. } );
  40295. if ( flipY === true ) {
  40296. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  40297. }
  40298. }
  40299. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  40300. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  40301. const device = this.backend.device;
  40302. const blockData = this._getBlockData( textureDescriptorGPU.format );
  40303. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  40304. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40305. const mipmap = mipmaps[ i ];
  40306. const width = mipmap.width;
  40307. const height = mipmap.height;
  40308. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  40309. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  40310. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  40311. for ( let j = 0; j < depth; j ++ ) {
  40312. device.queue.writeTexture(
  40313. {
  40314. texture: textureGPU,
  40315. mipLevel: i,
  40316. origin: { x: 0, y: 0, z: j }
  40317. },
  40318. mipmap.data,
  40319. {
  40320. offset: j * bytesPerImage,
  40321. bytesPerRow,
  40322. rowsPerImage: Math.ceil( height / blockData.height )
  40323. },
  40324. {
  40325. width: Math.ceil( width / blockData.width ) * blockData.width,
  40326. height: Math.ceil( height / blockData.height ) * blockData.height,
  40327. depthOrArrayLayers: 1
  40328. }
  40329. );
  40330. }
  40331. }
  40332. }
  40333. _getBlockData( format ) {
  40334. // this method is only relevant for compressed texture formats
  40335. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  40336. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  40337. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  40338. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  40339. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  40340. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  40341. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  40342. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40343. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  40344. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40345. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  40346. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  40347. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  40348. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  40349. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  40350. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  40351. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  40352. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  40353. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  40354. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  40355. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  40356. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  40357. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  40358. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  40359. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  40360. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  40361. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  40362. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  40363. }
  40364. _convertAddressMode( value ) {
  40365. let addressMode = GPUAddressMode.ClampToEdge;
  40366. if ( value === RepeatWrapping ) {
  40367. addressMode = GPUAddressMode.Repeat;
  40368. } else if ( value === MirroredRepeatWrapping ) {
  40369. addressMode = GPUAddressMode.MirrorRepeat;
  40370. }
  40371. return addressMode;
  40372. }
  40373. _convertFilterMode( value ) {
  40374. let filterMode = GPUFilterMode.Linear;
  40375. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  40376. filterMode = GPUFilterMode.Nearest;
  40377. }
  40378. return filterMode;
  40379. }
  40380. _getBytesPerTexel( format ) {
  40381. // 8-bit formats
  40382. if ( format === GPUTextureFormat.R8Unorm ||
  40383. format === GPUTextureFormat.R8Snorm ||
  40384. format === GPUTextureFormat.R8Uint ||
  40385. format === GPUTextureFormat.R8Sint ) return 1;
  40386. // 16-bit formats
  40387. if ( format === GPUTextureFormat.R16Uint ||
  40388. format === GPUTextureFormat.R16Sint ||
  40389. format === GPUTextureFormat.R16Float ||
  40390. format === GPUTextureFormat.RG8Unorm ||
  40391. format === GPUTextureFormat.RG8Snorm ||
  40392. format === GPUTextureFormat.RG8Uint ||
  40393. format === GPUTextureFormat.RG8Sint ) return 2;
  40394. // 32-bit formats
  40395. if ( format === GPUTextureFormat.R32Uint ||
  40396. format === GPUTextureFormat.R32Sint ||
  40397. format === GPUTextureFormat.R32Float ||
  40398. format === GPUTextureFormat.RG16Uint ||
  40399. format === GPUTextureFormat.RG16Sint ||
  40400. format === GPUTextureFormat.RG16Float ||
  40401. format === GPUTextureFormat.RGBA8Unorm ||
  40402. format === GPUTextureFormat.RGBA8UnormSRGB ||
  40403. format === GPUTextureFormat.RGBA8Snorm ||
  40404. format === GPUTextureFormat.RGBA8Uint ||
  40405. format === GPUTextureFormat.RGBA8Sint ||
  40406. format === GPUTextureFormat.BGRA8Unorm ||
  40407. format === GPUTextureFormat.BGRA8UnormSRGB ||
  40408. // Packed 32-bit formats
  40409. format === GPUTextureFormat.RGB9E5UFloat ||
  40410. format === GPUTextureFormat.RGB10A2Unorm ||
  40411. format === GPUTextureFormat.RG11B10UFloat ||
  40412. format === GPUTextureFormat.Depth32Float ||
  40413. format === GPUTextureFormat.Depth24Plus ||
  40414. format === GPUTextureFormat.Depth24PlusStencil8 ||
  40415. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  40416. // 64-bit formats
  40417. if ( format === GPUTextureFormat.RG32Uint ||
  40418. format === GPUTextureFormat.RG32Sint ||
  40419. format === GPUTextureFormat.RG32Float ||
  40420. format === GPUTextureFormat.RGBA16Uint ||
  40421. format === GPUTextureFormat.RGBA16Sint ||
  40422. format === GPUTextureFormat.RGBA16Float ) return 8;
  40423. // 128-bit formats
  40424. if ( format === GPUTextureFormat.RGBA32Uint ||
  40425. format === GPUTextureFormat.RGBA32Sint ||
  40426. format === GPUTextureFormat.RGBA32Float ) return 16;
  40427. }
  40428. _getTypedArrayType( format ) {
  40429. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  40430. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  40431. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  40432. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  40433. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  40434. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  40435. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  40436. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  40437. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  40438. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  40439. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  40440. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  40441. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  40442. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  40443. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  40444. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  40445. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  40446. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  40447. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  40448. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  40449. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  40450. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  40451. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  40452. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  40453. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  40454. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  40455. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  40456. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  40457. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  40458. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  40459. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  40460. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  40461. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  40462. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  40463. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  40464. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  40465. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  40466. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  40467. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  40468. }
  40469. _getDimension( texture ) {
  40470. let dimension;
  40471. if ( texture.isData3DTexture ) {
  40472. dimension = GPUTextureDimension.ThreeD;
  40473. } else {
  40474. dimension = GPUTextureDimension.TwoD;
  40475. }
  40476. return dimension;
  40477. }
  40478. }
  40479. function getFormat( texture, device = null ) {
  40480. const format = texture.format;
  40481. const type = texture.type;
  40482. const colorSpace = texture.colorSpace;
  40483. let formatGPU;
  40484. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  40485. switch ( format ) {
  40486. case RGBA_S3TC_DXT1_Format:
  40487. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  40488. break;
  40489. case RGBA_S3TC_DXT3_Format:
  40490. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  40491. break;
  40492. case RGBA_S3TC_DXT5_Format:
  40493. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  40494. break;
  40495. case RGB_ETC2_Format:
  40496. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  40497. break;
  40498. case RGBA_ETC2_EAC_Format:
  40499. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  40500. break;
  40501. case RGBA_ASTC_4x4_Format:
  40502. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  40503. break;
  40504. case RGBA_ASTC_5x4_Format:
  40505. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  40506. break;
  40507. case RGBA_ASTC_5x5_Format:
  40508. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  40509. break;
  40510. case RGBA_ASTC_6x5_Format:
  40511. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  40512. break;
  40513. case RGBA_ASTC_6x6_Format:
  40514. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  40515. break;
  40516. case RGBA_ASTC_8x5_Format:
  40517. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  40518. break;
  40519. case RGBA_ASTC_8x6_Format:
  40520. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  40521. break;
  40522. case RGBA_ASTC_8x8_Format:
  40523. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  40524. break;
  40525. case RGBA_ASTC_10x5_Format:
  40526. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  40527. break;
  40528. case RGBA_ASTC_10x6_Format:
  40529. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  40530. break;
  40531. case RGBA_ASTC_10x8_Format:
  40532. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  40533. break;
  40534. case RGBA_ASTC_10x10_Format:
  40535. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  40536. break;
  40537. case RGBA_ASTC_12x10_Format:
  40538. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  40539. break;
  40540. case RGBA_ASTC_12x12_Format:
  40541. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  40542. break;
  40543. case RGBAFormat:
  40544. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  40545. break;
  40546. default:
  40547. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40548. }
  40549. } else {
  40550. switch ( format ) {
  40551. case RGBAFormat:
  40552. switch ( type ) {
  40553. case ByteType:
  40554. formatGPU = GPUTextureFormat.RGBA8Snorm;
  40555. break;
  40556. case ShortType:
  40557. formatGPU = GPUTextureFormat.RGBA16Sint;
  40558. break;
  40559. case UnsignedShortType:
  40560. formatGPU = GPUTextureFormat.RGBA16Uint;
  40561. break;
  40562. case UnsignedIntType:
  40563. formatGPU = GPUTextureFormat.RGBA32Uint;
  40564. break;
  40565. case IntType:
  40566. formatGPU = GPUTextureFormat.RGBA32Sint;
  40567. break;
  40568. case UnsignedByteType:
  40569. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  40570. break;
  40571. case HalfFloatType:
  40572. formatGPU = GPUTextureFormat.RGBA16Float;
  40573. break;
  40574. case FloatType:
  40575. formatGPU = GPUTextureFormat.RGBA32Float;
  40576. break;
  40577. default:
  40578. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  40579. }
  40580. break;
  40581. case RGBFormat:
  40582. switch ( type ) {
  40583. case UnsignedInt5999Type:
  40584. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  40585. break;
  40586. default:
  40587. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  40588. }
  40589. break;
  40590. case RedFormat:
  40591. switch ( type ) {
  40592. case ByteType:
  40593. formatGPU = GPUTextureFormat.R8Snorm;
  40594. break;
  40595. case ShortType:
  40596. formatGPU = GPUTextureFormat.R16Sint;
  40597. break;
  40598. case UnsignedShortType:
  40599. formatGPU = GPUTextureFormat.R16Uint;
  40600. break;
  40601. case UnsignedIntType:
  40602. formatGPU = GPUTextureFormat.R32Uint;
  40603. break;
  40604. case IntType:
  40605. formatGPU = GPUTextureFormat.R32Sint;
  40606. break;
  40607. case UnsignedByteType:
  40608. formatGPU = GPUTextureFormat.R8Unorm;
  40609. break;
  40610. case HalfFloatType:
  40611. formatGPU = GPUTextureFormat.R16Float;
  40612. break;
  40613. case FloatType:
  40614. formatGPU = GPUTextureFormat.R32Float;
  40615. break;
  40616. default:
  40617. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  40618. }
  40619. break;
  40620. case RGFormat:
  40621. switch ( type ) {
  40622. case ByteType:
  40623. formatGPU = GPUTextureFormat.RG8Snorm;
  40624. break;
  40625. case ShortType:
  40626. formatGPU = GPUTextureFormat.RG16Sint;
  40627. break;
  40628. case UnsignedShortType:
  40629. formatGPU = GPUTextureFormat.RG16Uint;
  40630. break;
  40631. case UnsignedIntType:
  40632. formatGPU = GPUTextureFormat.RG32Uint;
  40633. break;
  40634. case IntType:
  40635. formatGPU = GPUTextureFormat.RG32Sint;
  40636. break;
  40637. case UnsignedByteType:
  40638. formatGPU = GPUTextureFormat.RG8Unorm;
  40639. break;
  40640. case HalfFloatType:
  40641. formatGPU = GPUTextureFormat.RG16Float;
  40642. break;
  40643. case FloatType:
  40644. formatGPU = GPUTextureFormat.RG32Float;
  40645. break;
  40646. default:
  40647. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  40648. }
  40649. break;
  40650. case DepthFormat:
  40651. switch ( type ) {
  40652. case UnsignedShortType:
  40653. formatGPU = GPUTextureFormat.Depth16Unorm;
  40654. break;
  40655. case UnsignedIntType:
  40656. formatGPU = GPUTextureFormat.Depth24Plus;
  40657. break;
  40658. case FloatType:
  40659. formatGPU = GPUTextureFormat.Depth32Float;
  40660. break;
  40661. default:
  40662. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  40663. }
  40664. break;
  40665. case DepthStencilFormat:
  40666. switch ( type ) {
  40667. case UnsignedInt248Type:
  40668. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  40669. break;
  40670. case FloatType:
  40671. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  40672. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  40673. }
  40674. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  40675. break;
  40676. default:
  40677. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  40678. }
  40679. break;
  40680. case RedIntegerFormat:
  40681. switch ( type ) {
  40682. case IntType:
  40683. formatGPU = GPUTextureFormat.R32Sint;
  40684. break;
  40685. case UnsignedIntType:
  40686. formatGPU = GPUTextureFormat.R32Uint;
  40687. break;
  40688. default:
  40689. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  40690. }
  40691. break;
  40692. case RGIntegerFormat:
  40693. switch ( type ) {
  40694. case IntType:
  40695. formatGPU = GPUTextureFormat.RG32Sint;
  40696. break;
  40697. case UnsignedIntType:
  40698. formatGPU = GPUTextureFormat.RG32Uint;
  40699. break;
  40700. default:
  40701. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  40702. }
  40703. break;
  40704. case RGBAIntegerFormat:
  40705. switch ( type ) {
  40706. case IntType:
  40707. formatGPU = GPUTextureFormat.RGBA32Sint;
  40708. break;
  40709. case UnsignedIntType:
  40710. formatGPU = GPUTextureFormat.RGBA32Uint;
  40711. break;
  40712. default:
  40713. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  40714. }
  40715. break;
  40716. default:
  40717. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  40718. }
  40719. }
  40720. return formatGPU;
  40721. }
  40722. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  40723. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  40724. const wgslTypeLib$1 = {
  40725. 'f32': 'float',
  40726. 'i32': 'int',
  40727. 'u32': 'uint',
  40728. 'bool': 'bool',
  40729. 'vec2<f32>': 'vec2',
  40730. 'vec2<i32>': 'ivec2',
  40731. 'vec2<u32>': 'uvec2',
  40732. 'vec2<bool>': 'bvec2',
  40733. 'vec2f': 'vec2',
  40734. 'vec2i': 'ivec2',
  40735. 'vec2u': 'uvec2',
  40736. 'vec2b': 'bvec2',
  40737. 'vec3<f32>': 'vec3',
  40738. 'vec3<i32>': 'ivec3',
  40739. 'vec3<u32>': 'uvec3',
  40740. 'vec3<bool>': 'bvec3',
  40741. 'vec3f': 'vec3',
  40742. 'vec3i': 'ivec3',
  40743. 'vec3u': 'uvec3',
  40744. 'vec3b': 'bvec3',
  40745. 'vec4<f32>': 'vec4',
  40746. 'vec4<i32>': 'ivec4',
  40747. 'vec4<u32>': 'uvec4',
  40748. 'vec4<bool>': 'bvec4',
  40749. 'vec4f': 'vec4',
  40750. 'vec4i': 'ivec4',
  40751. 'vec4u': 'uvec4',
  40752. 'vec4b': 'bvec4',
  40753. 'mat2x2<f32>': 'mat2',
  40754. 'mat2x2f': 'mat2',
  40755. 'mat3x3<f32>': 'mat3',
  40756. 'mat3x3f': 'mat3',
  40757. 'mat4x4<f32>': 'mat4',
  40758. 'mat4x4f': 'mat4',
  40759. 'sampler': 'sampler',
  40760. 'texture_1d': 'texture',
  40761. 'texture_2d': 'texture',
  40762. 'texture_2d_array': 'texture',
  40763. 'texture_multisampled_2d': 'cubeTexture',
  40764. 'texture_depth_2d': 'depthTexture',
  40765. 'texture_depth_multisampled_2d': 'depthTexture',
  40766. 'texture_3d': 'texture3D',
  40767. 'texture_cube': 'cubeTexture',
  40768. 'texture_cube_array': 'cubeTexture',
  40769. 'texture_storage_1d': 'storageTexture',
  40770. 'texture_storage_2d': 'storageTexture',
  40771. 'texture_storage_2d_array': 'storageTexture',
  40772. 'texture_storage_3d': 'storageTexture'
  40773. };
  40774. const parse = ( source ) => {
  40775. source = source.trim();
  40776. const declaration = source.match( declarationRegexp );
  40777. if ( declaration !== null && declaration.length === 4 ) {
  40778. const inputsCode = declaration[ 2 ];
  40779. const propsMatches = [];
  40780. let match = null;
  40781. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  40782. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  40783. }
  40784. // Process matches to correctly pair names and types
  40785. const inputs = [];
  40786. for ( let i = 0; i < propsMatches.length; i ++ ) {
  40787. const { name, type } = propsMatches[ i ];
  40788. let resolvedType = type;
  40789. if ( resolvedType.startsWith( 'ptr' ) ) {
  40790. resolvedType = 'pointer';
  40791. } else {
  40792. if ( resolvedType.startsWith( 'texture' ) ) {
  40793. resolvedType = type.split( '<' )[ 0 ];
  40794. }
  40795. resolvedType = wgslTypeLib$1[ resolvedType ];
  40796. }
  40797. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  40798. }
  40799. const blockCode = source.substring( declaration[ 0 ].length );
  40800. const outputType = declaration[ 3 ] || 'void';
  40801. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  40802. const type = wgslTypeLib$1[ outputType ] || outputType;
  40803. return {
  40804. type,
  40805. inputs,
  40806. name,
  40807. inputsCode,
  40808. blockCode,
  40809. outputType
  40810. };
  40811. } else {
  40812. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  40813. }
  40814. };
  40815. /**
  40816. * This class represents a WSL node function.
  40817. *
  40818. * @augments NodeFunction
  40819. */
  40820. class WGSLNodeFunction extends NodeFunction {
  40821. /**
  40822. * Constructs a new WGSL node function.
  40823. *
  40824. * @param {String} source - The WGSL source.
  40825. */
  40826. constructor( source ) {
  40827. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  40828. super( type, inputs, name );
  40829. this.inputsCode = inputsCode;
  40830. this.blockCode = blockCode;
  40831. this.outputType = outputType;
  40832. }
  40833. /**
  40834. * This method returns the WGSL code of the node function.
  40835. *
  40836. * @param {String} [name=this.name] - The function's name.
  40837. * @return {String} The shader code.
  40838. */
  40839. getCode( name = this.name ) {
  40840. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  40841. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  40842. }
  40843. }
  40844. /**
  40845. * A WGSL node parser.
  40846. *
  40847. * @augments NodeParser
  40848. */
  40849. class WGSLNodeParser extends NodeParser {
  40850. /**
  40851. * The method parses the given WGSL code an returns a node function.
  40852. *
  40853. * @param {String} source - The WGSL code.
  40854. * @return {WGSLNodeFunction} A node function.
  40855. */
  40856. parseFunction( source ) {
  40857. return new WGSLNodeFunction( source );
  40858. }
  40859. }
  40860. // GPUShaderStage is not defined in browsers not supporting WebGPU
  40861. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  40862. const accessNames = {
  40863. [ NodeAccess.READ_ONLY ]: 'read',
  40864. [ NodeAccess.WRITE_ONLY ]: 'write',
  40865. [ NodeAccess.READ_WRITE ]: 'read_write'
  40866. };
  40867. const wrapNames = {
  40868. [ RepeatWrapping ]: 'repeat',
  40869. [ ClampToEdgeWrapping ]: 'clamp',
  40870. [ MirroredRepeatWrapping ]: 'mirror'
  40871. };
  40872. const gpuShaderStageLib = {
  40873. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  40874. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  40875. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  40876. };
  40877. const supports = {
  40878. instance: true,
  40879. swizzleAssign: false,
  40880. storageBuffer: true
  40881. };
  40882. const wgslFnOpLib = {
  40883. '^^': 'tsl_xor'
  40884. };
  40885. const wgslTypeLib = {
  40886. float: 'f32',
  40887. int: 'i32',
  40888. uint: 'u32',
  40889. bool: 'bool',
  40890. color: 'vec3<f32>',
  40891. vec2: 'vec2<f32>',
  40892. ivec2: 'vec2<i32>',
  40893. uvec2: 'vec2<u32>',
  40894. bvec2: 'vec2<bool>',
  40895. vec3: 'vec3<f32>',
  40896. ivec3: 'vec3<i32>',
  40897. uvec3: 'vec3<u32>',
  40898. bvec3: 'vec3<bool>',
  40899. vec4: 'vec4<f32>',
  40900. ivec4: 'vec4<i32>',
  40901. uvec4: 'vec4<u32>',
  40902. bvec4: 'vec4<bool>',
  40903. mat2: 'mat2x2<f32>',
  40904. mat3: 'mat3x3<f32>',
  40905. mat4: 'mat4x4<f32>'
  40906. };
  40907. const wgslCodeCache = {};
  40908. const wgslPolyfill = {
  40909. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  40910. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  40911. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  40912. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  40913. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  40914. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  40915. equals_bvec2: new CodeNode( 'fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }' ),
  40916. equals_bvec3: new CodeNode( 'fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }' ),
  40917. equals_bvec4: new CodeNode( 'fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }' ),
  40918. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  40919. mirrorWrapping_float: new CodeNode( 'fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }' ),
  40920. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  40921. biquadraticTexture: new CodeNode( /* wgsl */`
  40922. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  40923. let res = vec2f( iRes );
  40924. let uvScaled = coord * res;
  40925. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  40926. // https://www.shadertoy.com/view/WtyXRy
  40927. let uv = uvWrapping - 0.5;
  40928. let iuv = floor( uv );
  40929. let f = fract( uv );
  40930. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  40931. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  40932. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  40933. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  40934. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  40935. }
  40936. ` )
  40937. };
  40938. const wgslMethods = {
  40939. dFdx: 'dpdx',
  40940. dFdy: '- dpdy',
  40941. mod_float: 'tsl_mod_float',
  40942. mod_vec2: 'tsl_mod_vec2',
  40943. mod_vec3: 'tsl_mod_vec3',
  40944. mod_vec4: 'tsl_mod_vec4',
  40945. equals_bool: 'tsl_equals_bool',
  40946. equals_bvec2: 'tsl_equals_bvec2',
  40947. equals_bvec3: 'tsl_equals_bvec3',
  40948. equals_bvec4: 'tsl_equals_bvec4',
  40949. inversesqrt: 'inverseSqrt',
  40950. bitcast: 'bitcast<f32>'
  40951. };
  40952. // WebGPU issue: does not support pow() with negative base on Windows
  40953. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  40954. wgslPolyfill.pow_float = new CodeNode( 'fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }' );
  40955. wgslPolyfill.pow_vec2 = new CodeNode( 'fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }', [ wgslPolyfill.pow_float ] );
  40956. wgslPolyfill.pow_vec3 = new CodeNode( 'fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }', [ wgslPolyfill.pow_float ] );
  40957. wgslPolyfill.pow_vec4 = new CodeNode( 'fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }', [ wgslPolyfill.pow_float ] );
  40958. wgslMethods.pow_float = 'tsl_pow_float';
  40959. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  40960. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  40961. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  40962. }
  40963. //
  40964. let diagnostics = '';
  40965. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  40966. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  40967. }
  40968. //
  40969. class WGSLNodeBuilder extends NodeBuilder {
  40970. constructor( object, renderer ) {
  40971. super( object, renderer, new WGSLNodeParser() );
  40972. this.uniformGroups = {};
  40973. this.builtins = {};
  40974. this.directives = {};
  40975. this.scopedArrays = new Map();
  40976. }
  40977. needsToWorkingColorSpace( texture ) {
  40978. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  40979. }
  40980. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40981. if ( shaderStage === 'fragment' ) {
  40982. if ( depthSnippet ) {
  40983. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  40984. } else {
  40985. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  40986. }
  40987. } else if ( this.isFilteredTexture( texture ) ) {
  40988. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  40989. } else {
  40990. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  40991. }
  40992. }
  40993. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  40994. if ( shaderStage === 'fragment' ) {
  40995. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  40996. } else {
  40997. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  40998. }
  40999. }
  41000. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41001. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  41002. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  41003. } else if ( this.isFilteredTexture( texture ) ) {
  41004. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  41005. } else {
  41006. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  41007. }
  41008. }
  41009. generateWrapFunction( texture ) {
  41010. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  41011. let nodeCode = wgslCodeCache[ functionName ];
  41012. if ( nodeCode === undefined ) {
  41013. const includes = [];
  41014. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  41015. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  41016. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  41017. const addWrapSnippet = ( wrap, axis ) => {
  41018. if ( wrap === RepeatWrapping ) {
  41019. includes.push( wgslPolyfill.repeatWrapping_float );
  41020. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  41021. } else if ( wrap === ClampToEdgeWrapping ) {
  41022. includes.push( wgslPolyfill.clampWrapping_float );
  41023. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  41024. } else if ( wrap === MirroredRepeatWrapping ) {
  41025. includes.push( wgslPolyfill.mirrorWrapping_float );
  41026. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  41027. } else {
  41028. code += `\t\tcoord.${ axis }`;
  41029. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  41030. }
  41031. };
  41032. addWrapSnippet( texture.wrapS, 'x' );
  41033. code += ',\n';
  41034. addWrapSnippet( texture.wrapT, 'y' );
  41035. if ( texture.isData3DTexture ) {
  41036. code += ',\n';
  41037. addWrapSnippet( texture.wrapR, 'z' );
  41038. }
  41039. code += '\n\t);\n\n}\n';
  41040. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  41041. }
  41042. nodeCode.build( this );
  41043. return functionName;
  41044. }
  41045. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  41046. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  41047. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  41048. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  41049. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  41050. let textureDimensionsParams;
  41051. let dimensionType;
  41052. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  41053. const isMultisampled = primarySamples > 1;
  41054. if ( texture.isData3DTexture ) {
  41055. dimensionType = 'vec3<u32>';
  41056. } else {
  41057. // Regular 2D textures, depth textures, etc.
  41058. dimensionType = 'vec2<u32>';
  41059. }
  41060. // Build parameters string based on texture type and multisampling
  41061. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  41062. textureDimensionsParams = textureProperty;
  41063. } else {
  41064. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  41065. }
  41066. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  41067. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  41068. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  41069. textureData.arrayLayerCount = new VarNode(
  41070. new ExpressionNode(
  41071. `textureNumLayers(${textureProperty})`,
  41072. 'u32'
  41073. )
  41074. );
  41075. }
  41076. // For cube textures, we know it's always 6 faces
  41077. if ( texture.isTextureCube ) {
  41078. textureData.cubeFaceCount = new VarNode(
  41079. new ExpressionNode( '6u', 'u32' )
  41080. );
  41081. }
  41082. }
  41083. return textureDimensionNode.build( this );
  41084. }
  41085. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  41086. this._include( 'biquadraticTexture' );
  41087. const wrapFunction = this.generateWrapFunction( texture );
  41088. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  41089. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  41090. }
  41091. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  41092. const wrapFunction = this.generateWrapFunction( texture );
  41093. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  41094. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  41095. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  41096. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  41097. }
  41098. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  41099. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  41100. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  41101. } else if ( depthSnippet ) {
  41102. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  41103. } else {
  41104. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  41105. }
  41106. }
  41107. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  41108. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  41109. }
  41110. isSampleCompare( texture ) {
  41111. return texture.isDepthTexture === true && texture.compareFunction !== null;
  41112. }
  41113. isUnfilterable( texture ) {
  41114. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  41115. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  41116. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  41117. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  41118. }
  41119. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41120. let snippet = null;
  41121. if ( texture.isVideoTexture === true ) {
  41122. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  41123. } else if ( this.isUnfilterable( texture ) ) {
  41124. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  41125. } else {
  41126. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  41127. }
  41128. return snippet;
  41129. }
  41130. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41131. if ( shaderStage === 'fragment' ) {
  41132. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  41133. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  41134. } else {
  41135. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  41136. }
  41137. }
  41138. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41139. if ( shaderStage === 'fragment' ) {
  41140. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  41141. } else {
  41142. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  41143. }
  41144. }
  41145. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41146. let snippet = null;
  41147. if ( texture.isVideoTexture === true ) {
  41148. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  41149. } else {
  41150. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  41151. }
  41152. return snippet;
  41153. }
  41154. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  41155. if ( shaderStage === 'fragment' ) {
  41156. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  41157. } else {
  41158. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  41159. }
  41160. }
  41161. getPropertyName( node, shaderStage = this.shaderStage ) {
  41162. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  41163. if ( shaderStage === 'vertex' ) {
  41164. return `varyings.${ node.name }`;
  41165. }
  41166. } else if ( node.isNodeUniform === true ) {
  41167. const name = node.name;
  41168. const type = node.type;
  41169. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  41170. return name;
  41171. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  41172. return `NodeBuffer_${ node.id }.${name}`;
  41173. } else {
  41174. return node.groupNode.name + '.' + name;
  41175. }
  41176. }
  41177. return super.getPropertyName( node );
  41178. }
  41179. getOutputStructName() {
  41180. return 'output';
  41181. }
  41182. _getUniformGroupCount( shaderStage ) {
  41183. return Object.keys( this.uniforms[ shaderStage ] ).length;
  41184. }
  41185. getFunctionOperator( op ) {
  41186. const fnOp = wgslFnOpLib[ op ];
  41187. if ( fnOp !== undefined ) {
  41188. this._include( fnOp );
  41189. return fnOp;
  41190. }
  41191. return null;
  41192. }
  41193. getNodeAccess( node, shaderStage ) {
  41194. if ( shaderStage !== 'compute' )
  41195. return NodeAccess.READ_ONLY;
  41196. return node.access;
  41197. }
  41198. getStorageAccess( node, shaderStage ) {
  41199. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  41200. }
  41201. getUniformFromNode( node, type, shaderStage, name = null ) {
  41202. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  41203. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  41204. if ( nodeData.uniformGPU === undefined ) {
  41205. let uniformGPU;
  41206. const group = node.groupNode;
  41207. const groupName = group.name;
  41208. const bindings = this.getBindGroupArray( groupName, shaderStage );
  41209. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  41210. let texture = null;
  41211. const access = this.getNodeAccess( node, shaderStage );
  41212. if ( type === 'texture' || type === 'storageTexture' ) {
  41213. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  41214. } else if ( type === 'cubeTexture' ) {
  41215. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  41216. } else if ( type === 'texture3D' ) {
  41217. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  41218. }
  41219. texture.store = node.isStorageTextureNode === true;
  41220. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41221. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  41222. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  41223. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41224. bindings.push( sampler, texture );
  41225. uniformGPU = [ sampler, texture ];
  41226. } else {
  41227. bindings.push( texture );
  41228. uniformGPU = [ texture ];
  41229. }
  41230. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  41231. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  41232. const buffer = new bufferClass( node, group );
  41233. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41234. bindings.push( buffer );
  41235. uniformGPU = buffer;
  41236. } else {
  41237. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  41238. let uniformsGroup = uniformsStage[ groupName ];
  41239. if ( uniformsGroup === undefined ) {
  41240. uniformsGroup = new NodeUniformsGroup( groupName, group );
  41241. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41242. uniformsStage[ groupName ] = uniformsGroup;
  41243. bindings.push( uniformsGroup );
  41244. }
  41245. uniformGPU = this.getNodeUniform( uniformNode, type );
  41246. uniformsGroup.addUniform( uniformGPU );
  41247. }
  41248. nodeData.uniformGPU = uniformGPU;
  41249. }
  41250. return uniformNode;
  41251. }
  41252. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  41253. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  41254. if ( map.has( name ) === false ) {
  41255. map.set( name, {
  41256. name,
  41257. property,
  41258. type
  41259. } );
  41260. }
  41261. return property;
  41262. }
  41263. hasBuiltin( name, shaderStage = this.shaderStage ) {
  41264. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  41265. }
  41266. getVertexIndex() {
  41267. if ( this.shaderStage === 'vertex' ) {
  41268. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  41269. }
  41270. return 'vertexIndex';
  41271. }
  41272. buildFunctionCode( shaderNode ) {
  41273. const layout = shaderNode.layout;
  41274. const flowData = this.flowShaderNode( shaderNode );
  41275. const parameters = [];
  41276. for ( const input of layout.inputs ) {
  41277. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  41278. }
  41279. //
  41280. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  41281. ${ flowData.vars }
  41282. ${ flowData.code }
  41283. `;
  41284. if ( flowData.result ) {
  41285. code += `\treturn ${ flowData.result };\n`;
  41286. }
  41287. code += '\n}\n';
  41288. //
  41289. return code;
  41290. }
  41291. getInstanceIndex() {
  41292. if ( this.shaderStage === 'vertex' ) {
  41293. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  41294. }
  41295. return 'instanceIndex';
  41296. }
  41297. getInvocationLocalIndex() {
  41298. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  41299. }
  41300. getSubgroupSize() {
  41301. this.enableSubGroups();
  41302. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  41303. }
  41304. getInvocationSubgroupIndex() {
  41305. this.enableSubGroups();
  41306. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  41307. }
  41308. getSubgroupIndex() {
  41309. this.enableSubGroups();
  41310. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  41311. }
  41312. getDrawIndex() {
  41313. return null;
  41314. }
  41315. getFrontFacing() {
  41316. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  41317. }
  41318. getFragCoord() {
  41319. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  41320. }
  41321. getFragDepth() {
  41322. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  41323. }
  41324. getClipDistance() {
  41325. return 'varyings.hw_clip_distances';
  41326. }
  41327. isFlipY() {
  41328. return false;
  41329. }
  41330. enableDirective( name, shaderStage = this.shaderStage ) {
  41331. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  41332. stage.add( name );
  41333. }
  41334. getDirectives( shaderStage ) {
  41335. const snippets = [];
  41336. const directives = this.directives[ shaderStage ];
  41337. if ( directives !== undefined ) {
  41338. for ( const directive of directives ) {
  41339. snippets.push( `enable ${directive};` );
  41340. }
  41341. }
  41342. return snippets.join( '\n' );
  41343. }
  41344. enableSubGroups() {
  41345. this.enableDirective( 'subgroups' );
  41346. }
  41347. enableSubgroupsF16() {
  41348. this.enableDirective( 'subgroups-f16' );
  41349. }
  41350. enableClipDistances() {
  41351. this.enableDirective( 'clip_distances' );
  41352. }
  41353. enableShaderF16() {
  41354. this.enableDirective( 'f16' );
  41355. }
  41356. enableDualSourceBlending() {
  41357. this.enableDirective( 'dual_source_blending' );
  41358. }
  41359. enableHardwareClipping( planeCount ) {
  41360. this.enableClipDistances();
  41361. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  41362. }
  41363. getBuiltins( shaderStage ) {
  41364. const snippets = [];
  41365. const builtins = this.builtins[ shaderStage ];
  41366. if ( builtins !== undefined ) {
  41367. for ( const { name, property, type } of builtins.values() ) {
  41368. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  41369. }
  41370. }
  41371. return snippets.join( ',\n\t' );
  41372. }
  41373. getScopedArray( name, scope, bufferType, bufferCount ) {
  41374. if ( this.scopedArrays.has( name ) === false ) {
  41375. this.scopedArrays.set( name, {
  41376. name,
  41377. scope,
  41378. bufferType,
  41379. bufferCount
  41380. } );
  41381. }
  41382. return name;
  41383. }
  41384. getScopedArrays( shaderStage ) {
  41385. if ( shaderStage !== 'compute' ) {
  41386. return;
  41387. }
  41388. const snippets = [];
  41389. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  41390. const type = this.getType( bufferType );
  41391. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  41392. }
  41393. return snippets.join( '\n' );
  41394. }
  41395. getAttributes( shaderStage ) {
  41396. const snippets = [];
  41397. if ( shaderStage === 'compute' ) {
  41398. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  41399. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  41400. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  41401. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  41402. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  41403. this.enableDirective( 'subgroups', shaderStage );
  41404. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  41405. }
  41406. }
  41407. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41408. const builtins = this.getBuiltins( 'attribute' );
  41409. if ( builtins ) snippets.push( builtins );
  41410. const attributes = this.getAttributesArray();
  41411. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  41412. const attribute = attributes[ index ];
  41413. const name = attribute.name;
  41414. const type = this.getType( attribute.type );
  41415. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  41416. }
  41417. }
  41418. return snippets.join( ',\n\t' );
  41419. }
  41420. getStructMembers( struct ) {
  41421. const snippets = [];
  41422. const members = struct.getMemberTypes();
  41423. for ( let i = 0; i < members.length; i ++ ) {
  41424. const member = members[ i ];
  41425. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  41426. }
  41427. const builtins = this.getBuiltins( 'output' );
  41428. if ( builtins ) snippets.push( '\t' + builtins );
  41429. return snippets.join( ',\n' );
  41430. }
  41431. getStructs( shaderStage ) {
  41432. const snippets = [];
  41433. const structs = this.structs[ shaderStage ];
  41434. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  41435. const struct = structs[ index ];
  41436. const name = struct.name;
  41437. let snippet = `\struct ${ name } {\n`;
  41438. snippet += this.getStructMembers( struct );
  41439. snippet += '\n}';
  41440. snippets.push( snippet );
  41441. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  41442. }
  41443. return snippets.join( '\n\n' );
  41444. }
  41445. getVar( type, name ) {
  41446. return `var ${ name } : ${ this.getType( type ) }`;
  41447. }
  41448. getVars( shaderStage ) {
  41449. const snippets = [];
  41450. const vars = this.vars[ shaderStage ];
  41451. if ( vars !== undefined ) {
  41452. for ( const variable of vars ) {
  41453. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  41454. }
  41455. }
  41456. return `\n${ snippets.join( '\n' ) }\n`;
  41457. }
  41458. getVaryings( shaderStage ) {
  41459. const snippets = [];
  41460. if ( shaderStage === 'vertex' ) {
  41461. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  41462. }
  41463. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  41464. const varyings = this.varyings;
  41465. const vars = this.vars[ shaderStage ];
  41466. for ( let index = 0; index < varyings.length; index ++ ) {
  41467. const varying = varyings[ index ];
  41468. if ( varying.needsInterpolation ) {
  41469. let attributesSnippet = `@location( ${index} )`;
  41470. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  41471. attributesSnippet += ' @interpolate( flat )';
  41472. }
  41473. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  41474. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  41475. vars.push( varying );
  41476. }
  41477. }
  41478. }
  41479. const builtins = this.getBuiltins( shaderStage );
  41480. if ( builtins ) snippets.push( builtins );
  41481. const code = snippets.join( ',\n\t' );
  41482. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  41483. }
  41484. getUniforms( shaderStage ) {
  41485. const uniforms = this.uniforms[ shaderStage ];
  41486. const bindingSnippets = [];
  41487. const bufferSnippets = [];
  41488. const structSnippets = [];
  41489. const uniformGroups = {};
  41490. for ( const uniform of uniforms ) {
  41491. const groupName = uniform.groupNode.name;
  41492. const uniformIndexes = this.bindingsIndexes[ groupName ];
  41493. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  41494. const texture = uniform.node.value;
  41495. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  41496. if ( this.isSampleCompare( texture ) ) {
  41497. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  41498. } else {
  41499. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  41500. }
  41501. }
  41502. let textureType;
  41503. let multisampled = '';
  41504. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  41505. if ( primarySamples > 1 ) {
  41506. multisampled = '_multisampled';
  41507. }
  41508. if ( texture.isCubeTexture === true ) {
  41509. textureType = 'texture_cube<f32>';
  41510. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  41511. textureType = 'texture_2d_array<f32>';
  41512. } else if ( texture.isDepthTexture === true ) {
  41513. textureType = `texture_depth${multisampled}_2d`;
  41514. } else if ( texture.isVideoTexture === true ) {
  41515. textureType = 'texture_external';
  41516. } else if ( texture.isData3DTexture === true ) {
  41517. textureType = 'texture_3d<f32>';
  41518. } else if ( uniform.node.isStorageTextureNode === true ) {
  41519. const format = getFormat( texture );
  41520. const access = this.getStorageAccess( uniform.node, shaderStage );
  41521. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  41522. } else {
  41523. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  41524. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  41525. }
  41526. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  41527. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  41528. const bufferNode = uniform.node;
  41529. const bufferType = this.getType( bufferNode.bufferType );
  41530. const bufferCount = bufferNode.bufferCount;
  41531. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  41532. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  41533. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  41534. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  41535. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  41536. } else {
  41537. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  41538. const groupName = uniform.groupNode.name;
  41539. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  41540. index: uniformIndexes.binding ++,
  41541. id: uniformIndexes.group,
  41542. snippets: []
  41543. } );
  41544. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  41545. }
  41546. }
  41547. for ( const name in uniformGroups ) {
  41548. const group = uniformGroups[ name ];
  41549. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  41550. }
  41551. let code = bindingSnippets.join( '\n' );
  41552. code += bufferSnippets.join( '\n' );
  41553. code += structSnippets.join( '\n' );
  41554. return code;
  41555. }
  41556. buildCode() {
  41557. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  41558. this.sortBindingGroups();
  41559. for ( const shaderStage in shadersData ) {
  41560. const stageData = shadersData[ shaderStage ];
  41561. stageData.uniforms = this.getUniforms( shaderStage );
  41562. stageData.attributes = this.getAttributes( shaderStage );
  41563. stageData.varyings = this.getVaryings( shaderStage );
  41564. stageData.structs = this.getStructs( shaderStage );
  41565. stageData.vars = this.getVars( shaderStage );
  41566. stageData.codes = this.getCodes( shaderStage );
  41567. stageData.directives = this.getDirectives( shaderStage );
  41568. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  41569. //
  41570. let flow = '// code\n\n';
  41571. flow += this.flowCode[ shaderStage ];
  41572. const flowNodes = this.flowNodes[ shaderStage ];
  41573. const mainNode = flowNodes[ flowNodes.length - 1 ];
  41574. const outputNode = mainNode.outputNode;
  41575. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  41576. for ( const node of flowNodes ) {
  41577. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  41578. const slotName = node.name;
  41579. if ( slotName ) {
  41580. if ( flow.length > 0 ) flow += '\n';
  41581. flow += `\t// flow -> ${ slotName }\n\t`;
  41582. }
  41583. flow += `${ flowSlotData.code }\n\t`;
  41584. if ( node === mainNode && shaderStage !== 'compute' ) {
  41585. flow += '// result\n\n\t';
  41586. if ( shaderStage === 'vertex' ) {
  41587. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  41588. } else if ( shaderStage === 'fragment' ) {
  41589. if ( isOutputStruct ) {
  41590. stageData.returnType = outputNode.nodeType;
  41591. flow += `return ${ flowSlotData.result };`;
  41592. } else {
  41593. let structSnippet = '\t@location(0) color: vec4<f32>';
  41594. const builtins = this.getBuiltins( 'output' );
  41595. if ( builtins ) structSnippet += ',\n\t' + builtins;
  41596. stageData.returnType = 'OutputStruct';
  41597. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  41598. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  41599. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  41600. }
  41601. }
  41602. }
  41603. }
  41604. stageData.flow = flow;
  41605. }
  41606. if ( this.material !== null ) {
  41607. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  41608. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  41609. } else {
  41610. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  41611. }
  41612. }
  41613. getMethod( method, output = null ) {
  41614. let wgslMethod;
  41615. if ( output !== null ) {
  41616. wgslMethod = this._getWGSLMethod( method + '_' + output );
  41617. }
  41618. if ( wgslMethod === undefined ) {
  41619. wgslMethod = this._getWGSLMethod( method );
  41620. }
  41621. return wgslMethod || method;
  41622. }
  41623. getType( type ) {
  41624. return wgslTypeLib[ type ] || type;
  41625. }
  41626. isAvailable( name ) {
  41627. let result = supports[ name ];
  41628. if ( result === undefined ) {
  41629. if ( name === 'float32Filterable' ) {
  41630. result = this.renderer.hasFeature( 'float32-filterable' );
  41631. } else if ( name === 'clipDistance' ) {
  41632. result = this.renderer.hasFeature( 'clip-distances' );
  41633. }
  41634. supports[ name ] = result;
  41635. }
  41636. return result;
  41637. }
  41638. _getWGSLMethod( method ) {
  41639. if ( wgslPolyfill[ method ] !== undefined ) {
  41640. this._include( method );
  41641. }
  41642. return wgslMethods[ method ];
  41643. }
  41644. _include( name ) {
  41645. const codeNode = wgslPolyfill[ name ];
  41646. codeNode.build( this );
  41647. if ( this.currentFunctionNode !== null ) {
  41648. this.currentFunctionNode.includes.push( codeNode );
  41649. }
  41650. return codeNode;
  41651. }
  41652. _getWGSLVertexCode( shaderData ) {
  41653. return `${ this.getSignature() }
  41654. // directives
  41655. ${shaderData.directives}
  41656. // uniforms
  41657. ${shaderData.uniforms}
  41658. // varyings
  41659. ${shaderData.varyings}
  41660. var<private> varyings : VaryingsStruct;
  41661. // codes
  41662. ${shaderData.codes}
  41663. @vertex
  41664. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  41665. // vars
  41666. ${shaderData.vars}
  41667. // flow
  41668. ${shaderData.flow}
  41669. return varyings;
  41670. }
  41671. `;
  41672. }
  41673. _getWGSLFragmentCode( shaderData ) {
  41674. return `${ this.getSignature() }
  41675. // global
  41676. ${ diagnostics }
  41677. // uniforms
  41678. ${shaderData.uniforms}
  41679. // structs
  41680. ${shaderData.structs}
  41681. // codes
  41682. ${shaderData.codes}
  41683. @fragment
  41684. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  41685. // vars
  41686. ${shaderData.vars}
  41687. // flow
  41688. ${shaderData.flow}
  41689. }
  41690. `;
  41691. }
  41692. _getWGSLComputeCode( shaderData, workgroupSize ) {
  41693. return `${ this.getSignature() }
  41694. // directives
  41695. ${shaderData.directives}
  41696. // system
  41697. var<private> instanceIndex : u32;
  41698. // locals
  41699. ${shaderData.scopedArrays}
  41700. // uniforms
  41701. ${shaderData.uniforms}
  41702. // codes
  41703. ${shaderData.codes}
  41704. @compute @workgroup_size( ${workgroupSize} )
  41705. fn main( ${shaderData.attributes} ) {
  41706. // system
  41707. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  41708. // vars
  41709. ${shaderData.vars}
  41710. // flow
  41711. ${shaderData.flow}
  41712. }
  41713. `;
  41714. }
  41715. _getWGSLStruct( name, vars ) {
  41716. return `
  41717. struct ${name} {
  41718. ${vars}
  41719. };`;
  41720. }
  41721. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  41722. const structName = name + 'Struct';
  41723. const structSnippet = this._getWGSLStruct( structName, vars );
  41724. return `${structSnippet}
  41725. @binding( ${binding} ) @group( ${group} )
  41726. var<${access}> ${name} : ${structName};`;
  41727. }
  41728. }
  41729. class WebGPUUtils {
  41730. constructor( backend ) {
  41731. this.backend = backend;
  41732. }
  41733. getCurrentDepthStencilFormat( renderContext ) {
  41734. let format;
  41735. if ( renderContext.depthTexture !== null ) {
  41736. format = this.getTextureFormatGPU( renderContext.depthTexture );
  41737. } else if ( renderContext.depth && renderContext.stencil ) {
  41738. format = GPUTextureFormat.Depth24PlusStencil8;
  41739. } else if ( renderContext.depth ) {
  41740. format = GPUTextureFormat.Depth24Plus;
  41741. }
  41742. return format;
  41743. }
  41744. getTextureFormatGPU( texture ) {
  41745. return this.backend.get( texture ).format;
  41746. }
  41747. getTextureSampleData( texture ) {
  41748. let samples;
  41749. if ( texture.isFramebufferTexture ) {
  41750. samples = 1;
  41751. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  41752. const renderer = this.backend.renderer;
  41753. const renderTarget = renderer.getRenderTarget();
  41754. samples = renderTarget ? renderTarget.samples : renderer.samples;
  41755. } else if ( texture.renderTarget ) {
  41756. samples = texture.renderTarget.samples;
  41757. }
  41758. samples = samples || 1;
  41759. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  41760. const primarySamples = isMSAA ? 1 : samples;
  41761. return { samples, primarySamples, isMSAA };
  41762. }
  41763. getCurrentColorFormat( renderContext ) {
  41764. let format;
  41765. if ( renderContext.textures !== null ) {
  41766. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  41767. } else {
  41768. format = this.getPreferredCanvasFormat(); // default context format
  41769. }
  41770. return format;
  41771. }
  41772. getCurrentColorSpace( renderContext ) {
  41773. if ( renderContext.textures !== null ) {
  41774. return renderContext.textures[ 0 ].colorSpace;
  41775. }
  41776. return this.backend.renderer.outputColorSpace;
  41777. }
  41778. getPrimitiveTopology( object, material ) {
  41779. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  41780. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  41781. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  41782. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  41783. }
  41784. getSampleCount( sampleCount ) {
  41785. let count = 1;
  41786. if ( sampleCount > 1 ) {
  41787. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  41788. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  41789. if ( count === 2 ) {
  41790. count = 4;
  41791. }
  41792. }
  41793. return count;
  41794. }
  41795. getSampleCountRenderContext( renderContext ) {
  41796. if ( renderContext.textures !== null ) {
  41797. return this.getSampleCount( renderContext.sampleCount );
  41798. }
  41799. return this.getSampleCount( this.backend.renderer.samples );
  41800. }
  41801. getPreferredCanvasFormat() {
  41802. // TODO: Remove this check when Quest 34.5 is out
  41803. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  41804. if ( navigator.userAgent.includes( 'Quest' ) ) {
  41805. return GPUTextureFormat.BGRA8Unorm;
  41806. } else {
  41807. return navigator.gpu.getPreferredCanvasFormat();
  41808. }
  41809. }
  41810. }
  41811. const typedArraysToVertexFormatPrefix = new Map( [
  41812. [ Int8Array, [ 'sint8', 'snorm8' ]],
  41813. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  41814. [ Int16Array, [ 'sint16', 'snorm16' ]],
  41815. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  41816. [ Int32Array, [ 'sint32', 'snorm32' ]],
  41817. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  41818. [ Float32Array, [ 'float32', ]],
  41819. ] );
  41820. const typedAttributeToVertexFormatPrefix = new Map( [
  41821. [ Float16BufferAttribute, [ 'float16', ]],
  41822. ] );
  41823. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  41824. [ Int32Array, 'sint32' ],
  41825. [ Int16Array, 'sint32' ], // patch for INT16
  41826. [ Uint32Array, 'uint32' ],
  41827. [ Uint16Array, 'uint32' ], // patch for UINT16
  41828. [ Float32Array, 'float32' ]
  41829. ] );
  41830. class WebGPUAttributeUtils {
  41831. constructor( backend ) {
  41832. this.backend = backend;
  41833. }
  41834. createAttribute( attribute, usage ) {
  41835. const bufferAttribute = this._getBufferAttribute( attribute );
  41836. const backend = this.backend;
  41837. const bufferData = backend.get( bufferAttribute );
  41838. let buffer = bufferData.buffer;
  41839. if ( buffer === undefined ) {
  41840. const device = backend.device;
  41841. let array = bufferAttribute.array;
  41842. // patch for INT16 and UINT16
  41843. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  41844. const tempArray = new Uint32Array( array.length );
  41845. for ( let i = 0; i < array.length; i ++ ) {
  41846. tempArray[ i ] = array[ i ];
  41847. }
  41848. array = tempArray;
  41849. }
  41850. bufferAttribute.array = array;
  41851. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  41852. array = new array.constructor( bufferAttribute.count * 4 );
  41853. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  41854. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  41855. }
  41856. // Update BufferAttribute
  41857. bufferAttribute.itemSize = 4;
  41858. bufferAttribute.array = array;
  41859. }
  41860. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  41861. buffer = device.createBuffer( {
  41862. label: bufferAttribute.name,
  41863. size: size,
  41864. usage: usage,
  41865. mappedAtCreation: true
  41866. } );
  41867. new array.constructor( buffer.getMappedRange() ).set( array );
  41868. buffer.unmap();
  41869. bufferData.buffer = buffer;
  41870. }
  41871. }
  41872. updateAttribute( attribute ) {
  41873. const bufferAttribute = this._getBufferAttribute( attribute );
  41874. const backend = this.backend;
  41875. const device = backend.device;
  41876. const buffer = backend.get( bufferAttribute ).buffer;
  41877. const array = bufferAttribute.array;
  41878. const isTypedArray = this._isTypedArray( array );
  41879. const updateRanges = bufferAttribute.updateRanges;
  41880. if ( updateRanges.length === 0 ) {
  41881. // Not using update ranges
  41882. device.queue.writeBuffer(
  41883. buffer,
  41884. 0,
  41885. array,
  41886. 0
  41887. );
  41888. } else {
  41889. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  41890. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  41891. const range = updateRanges[ i ];
  41892. const dataOffset = range.start * byteOffsetFactor;
  41893. const size = range.count * byteOffsetFactor;
  41894. device.queue.writeBuffer(
  41895. buffer,
  41896. 0,
  41897. array,
  41898. dataOffset,
  41899. size
  41900. );
  41901. }
  41902. bufferAttribute.clearUpdateRanges();
  41903. }
  41904. }
  41905. createShaderVertexBuffers( renderObject ) {
  41906. const attributes = renderObject.getAttributes();
  41907. const vertexBuffers = new Map();
  41908. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  41909. const geometryAttribute = attributes[ slot ];
  41910. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  41911. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  41912. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  41913. if ( vertexBufferLayout === undefined ) {
  41914. let arrayStride, stepMode;
  41915. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  41916. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  41917. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41918. } else {
  41919. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  41920. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  41921. }
  41922. // patch for INT16 and UINT16
  41923. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  41924. arrayStride = 4;
  41925. }
  41926. vertexBufferLayout = {
  41927. arrayStride,
  41928. attributes: [],
  41929. stepMode
  41930. };
  41931. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  41932. }
  41933. const format = this._getVertexFormat( geometryAttribute );
  41934. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  41935. vertexBufferLayout.attributes.push( {
  41936. shaderLocation: slot,
  41937. offset,
  41938. format
  41939. } );
  41940. }
  41941. return Array.from( vertexBuffers.values() );
  41942. }
  41943. destroyAttribute( attribute ) {
  41944. const backend = this.backend;
  41945. const data = backend.get( this._getBufferAttribute( attribute ) );
  41946. data.buffer.destroy();
  41947. backend.delete( attribute );
  41948. }
  41949. async getArrayBufferAsync( attribute ) {
  41950. const backend = this.backend;
  41951. const device = backend.device;
  41952. const data = backend.get( this._getBufferAttribute( attribute ) );
  41953. const bufferGPU = data.buffer;
  41954. const size = bufferGPU.size;
  41955. const readBufferGPU = device.createBuffer( {
  41956. label: `${ attribute.name }_readback`,
  41957. size,
  41958. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41959. } );
  41960. const cmdEncoder = device.createCommandEncoder( {
  41961. label: `readback_encoder_${ attribute.name }`
  41962. } );
  41963. cmdEncoder.copyBufferToBuffer(
  41964. bufferGPU,
  41965. 0,
  41966. readBufferGPU,
  41967. 0,
  41968. size
  41969. );
  41970. const gpuCommands = cmdEncoder.finish();
  41971. device.queue.submit( [ gpuCommands ] );
  41972. await readBufferGPU.mapAsync( GPUMapMode.READ );
  41973. const arrayBuffer = readBufferGPU.getMappedRange();
  41974. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  41975. readBufferGPU.unmap();
  41976. return dstBuffer.buffer;
  41977. }
  41978. _getVertexFormat( geometryAttribute ) {
  41979. const { itemSize, normalized } = geometryAttribute;
  41980. const ArrayType = geometryAttribute.array.constructor;
  41981. const AttributeType = geometryAttribute.constructor;
  41982. let format;
  41983. if ( itemSize === 1 ) {
  41984. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  41985. } else {
  41986. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  41987. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  41988. if ( prefix ) {
  41989. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  41990. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  41991. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  41992. if ( paddedItemSize % 1 ) {
  41993. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  41994. }
  41995. format = `${prefix}x${paddedItemSize}`;
  41996. }
  41997. }
  41998. if ( ! format ) {
  41999. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  42000. }
  42001. return format;
  42002. }
  42003. _isTypedArray( array ) {
  42004. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  42005. }
  42006. _getBufferAttribute( attribute ) {
  42007. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42008. return attribute;
  42009. }
  42010. }
  42011. class WebGPUBindingUtils {
  42012. constructor( backend ) {
  42013. this.backend = backend;
  42014. this.bindGroupLayoutCache = new WeakMap();
  42015. }
  42016. createBindingsLayout( bindGroup ) {
  42017. const backend = this.backend;
  42018. const device = backend.device;
  42019. const entries = [];
  42020. let index = 0;
  42021. for ( const binding of bindGroup.bindings ) {
  42022. const bindingGPU = {
  42023. binding: index ++,
  42024. visibility: binding.visibility
  42025. };
  42026. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  42027. const buffer = {}; // GPUBufferBindingLayout
  42028. if ( binding.isStorageBuffer ) {
  42029. if ( binding.visibility & 4 ) {
  42030. // compute
  42031. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  42032. buffer.type = GPUBufferBindingType.Storage;
  42033. } else {
  42034. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  42035. }
  42036. } else {
  42037. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  42038. }
  42039. }
  42040. bindingGPU.buffer = buffer;
  42041. } else if ( binding.isSampler ) {
  42042. const sampler = {}; // GPUSamplerBindingLayout
  42043. if ( binding.texture.isDepthTexture ) {
  42044. if ( binding.texture.compareFunction !== null ) {
  42045. sampler.type = 'comparison';
  42046. }
  42047. }
  42048. bindingGPU.sampler = sampler;
  42049. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  42050. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  42051. } else if ( binding.isSampledTexture && binding.store ) {
  42052. const storageTexture = {}; // GPUStorageTextureBindingLayout
  42053. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  42054. const access = binding.access;
  42055. if ( access === NodeAccess.READ_WRITE ) {
  42056. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  42057. } else if ( access === NodeAccess.WRITE_ONLY ) {
  42058. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  42059. } else {
  42060. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  42061. }
  42062. bindingGPU.storageTexture = storageTexture;
  42063. } else if ( binding.isSampledTexture ) {
  42064. const texture = {}; // GPUTextureBindingLayout
  42065. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  42066. if ( primarySamples > 1 ) {
  42067. texture.multisampled = true;
  42068. if ( ! binding.texture.isDepthTexture ) {
  42069. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  42070. }
  42071. }
  42072. if ( binding.texture.isDepthTexture ) {
  42073. texture.sampleType = GPUTextureSampleType.Depth;
  42074. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  42075. const type = binding.texture.type;
  42076. if ( type === IntType ) {
  42077. texture.sampleType = GPUTextureSampleType.SInt;
  42078. } else if ( type === UnsignedIntType ) {
  42079. texture.sampleType = GPUTextureSampleType.UInt;
  42080. } else if ( type === FloatType ) {
  42081. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  42082. texture.sampleType = GPUTextureSampleType.Float;
  42083. } else {
  42084. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  42085. }
  42086. }
  42087. }
  42088. if ( binding.isSampledCubeTexture ) {
  42089. texture.viewDimension = GPUTextureViewDimension.Cube;
  42090. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  42091. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  42092. } else if ( binding.isSampledTexture3D ) {
  42093. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  42094. }
  42095. bindingGPU.texture = texture;
  42096. } else {
  42097. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  42098. }
  42099. entries.push( bindingGPU );
  42100. }
  42101. return device.createBindGroupLayout( { entries } );
  42102. }
  42103. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  42104. const { backend, bindGroupLayoutCache } = this;
  42105. const bindingsData = backend.get( bindGroup );
  42106. // setup (static) binding layout and (dynamic) binding group
  42107. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  42108. if ( bindLayoutGPU === undefined ) {
  42109. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  42110. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  42111. }
  42112. let bindGroupGPU;
  42113. if ( cacheIndex > 0 ) {
  42114. if ( bindingsData.groups === undefined ) {
  42115. bindingsData.groups = [];
  42116. bindingsData.versions = [];
  42117. }
  42118. if ( bindingsData.versions[ cacheIndex ] === version ) {
  42119. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  42120. }
  42121. }
  42122. if ( bindGroupGPU === undefined ) {
  42123. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  42124. if ( cacheIndex > 0 ) {
  42125. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  42126. bindingsData.versions[ cacheIndex ] = version;
  42127. }
  42128. }
  42129. bindingsData.group = bindGroupGPU;
  42130. bindingsData.layout = bindLayoutGPU;
  42131. }
  42132. updateBinding( binding ) {
  42133. const backend = this.backend;
  42134. const device = backend.device;
  42135. const buffer = binding.buffer;
  42136. const bufferGPU = backend.get( binding ).buffer;
  42137. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  42138. }
  42139. createBindGroup( bindGroup, layoutGPU ) {
  42140. const backend = this.backend;
  42141. const device = backend.device;
  42142. let bindingPoint = 0;
  42143. const entriesGPU = [];
  42144. for ( const binding of bindGroup.bindings ) {
  42145. if ( binding.isUniformBuffer ) {
  42146. const bindingData = backend.get( binding );
  42147. if ( bindingData.buffer === undefined ) {
  42148. const byteLength = binding.byteLength;
  42149. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  42150. const bufferGPU = device.createBuffer( {
  42151. label: 'bindingBuffer_' + binding.name,
  42152. size: byteLength,
  42153. usage: usage
  42154. } );
  42155. bindingData.buffer = bufferGPU;
  42156. }
  42157. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  42158. } else if ( binding.isStorageBuffer ) {
  42159. const bindingData = backend.get( binding );
  42160. if ( bindingData.buffer === undefined ) {
  42161. const attribute = binding.attribute;
  42162. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  42163. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  42164. bindingData.buffer = backend.get( attribute ).buffer;
  42165. }
  42166. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  42167. } else if ( binding.isSampler ) {
  42168. const textureGPU = backend.get( binding.texture );
  42169. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  42170. } else if ( binding.isSampledTexture ) {
  42171. const textureData = backend.get( binding.texture );
  42172. let resourceGPU;
  42173. if ( textureData.externalTexture !== undefined ) {
  42174. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  42175. } else {
  42176. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  42177. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  42178. resourceGPU = textureData[ propertyName ];
  42179. if ( resourceGPU === undefined ) {
  42180. const aspectGPU = GPUTextureAspect.All;
  42181. let dimensionViewGPU;
  42182. if ( binding.isSampledCubeTexture ) {
  42183. dimensionViewGPU = GPUTextureViewDimension.Cube;
  42184. } else if ( binding.isSampledTexture3D ) {
  42185. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  42186. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  42187. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  42188. } else {
  42189. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  42190. }
  42191. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  42192. }
  42193. }
  42194. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  42195. }
  42196. bindingPoint ++;
  42197. }
  42198. return device.createBindGroup( {
  42199. label: 'bindGroup_' + bindGroup.name,
  42200. layout: layoutGPU,
  42201. entries: entriesGPU
  42202. } );
  42203. }
  42204. }
  42205. class WebGPUPipelineUtils {
  42206. constructor( backend ) {
  42207. this.backend = backend;
  42208. }
  42209. _getSampleCount( renderObjectContext ) {
  42210. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  42211. }
  42212. createRenderPipeline( renderObject, promises ) {
  42213. const { object, material, geometry, pipeline } = renderObject;
  42214. const { vertexProgram, fragmentProgram } = pipeline;
  42215. const backend = this.backend;
  42216. const device = backend.device;
  42217. const utils = backend.utils;
  42218. const pipelineData = backend.get( pipeline );
  42219. // bind group layouts
  42220. const bindGroupLayouts = [];
  42221. for ( const bindGroup of renderObject.getBindings() ) {
  42222. const bindingsData = backend.get( bindGroup );
  42223. bindGroupLayouts.push( bindingsData.layout );
  42224. }
  42225. // vertex buffers
  42226. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  42227. // blending
  42228. let blending;
  42229. if ( material.transparent === true && material.blending !== NoBlending ) {
  42230. blending = this._getBlending( material );
  42231. }
  42232. // stencil
  42233. let stencilFront = {};
  42234. if ( material.stencilWrite === true ) {
  42235. stencilFront = {
  42236. compare: this._getStencilCompare( material ),
  42237. failOp: this._getStencilOperation( material.stencilFail ),
  42238. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  42239. passOp: this._getStencilOperation( material.stencilZPass )
  42240. };
  42241. }
  42242. const colorWriteMask = this._getColorWriteMask( material );
  42243. const targets = [];
  42244. if ( renderObject.context.textures !== null ) {
  42245. const textures = renderObject.context.textures;
  42246. for ( let i = 0; i < textures.length; i ++ ) {
  42247. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  42248. targets.push( {
  42249. format: colorFormat,
  42250. blend: blending,
  42251. writeMask: colorWriteMask
  42252. } );
  42253. }
  42254. } else {
  42255. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  42256. targets.push( {
  42257. format: colorFormat,
  42258. blend: blending,
  42259. writeMask: colorWriteMask
  42260. } );
  42261. }
  42262. const vertexModule = backend.get( vertexProgram ).module;
  42263. const fragmentModule = backend.get( fragmentProgram ).module;
  42264. const primitiveState = this._getPrimitiveState( object, geometry, material );
  42265. const depthCompare = this._getDepthCompare( material );
  42266. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  42267. const sampleCount = this._getSampleCount( renderObject.context );
  42268. const pipelineDescriptor = {
  42269. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  42270. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  42271. fragment: Object.assign( {}, fragmentModule, { targets } ),
  42272. primitive: primitiveState,
  42273. multisample: {
  42274. count: sampleCount,
  42275. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  42276. },
  42277. layout: device.createPipelineLayout( {
  42278. bindGroupLayouts
  42279. } )
  42280. };
  42281. const depthStencil = {};
  42282. const renderDepth = renderObject.context.depth;
  42283. const renderStencil = renderObject.context.stencil;
  42284. if ( renderDepth === true || renderStencil === true ) {
  42285. if ( renderDepth === true ) {
  42286. depthStencil.format = depthStencilFormat;
  42287. depthStencil.depthWriteEnabled = material.depthWrite;
  42288. depthStencil.depthCompare = depthCompare;
  42289. }
  42290. if ( renderStencil === true ) {
  42291. depthStencil.stencilFront = stencilFront;
  42292. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  42293. depthStencil.stencilReadMask = material.stencilFuncMask;
  42294. depthStencil.stencilWriteMask = material.stencilWriteMask;
  42295. }
  42296. pipelineDescriptor.depthStencil = depthStencil;
  42297. }
  42298. if ( promises === null ) {
  42299. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  42300. } else {
  42301. const p = new Promise( ( resolve /*, reject*/ ) => {
  42302. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  42303. pipelineData.pipeline = pipeline;
  42304. resolve();
  42305. } );
  42306. } );
  42307. promises.push( p );
  42308. }
  42309. }
  42310. createBundleEncoder( renderContext ) {
  42311. const backend = this.backend;
  42312. const { utils, device } = backend;
  42313. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  42314. const colorFormat = utils.getCurrentColorFormat( renderContext );
  42315. const sampleCount = this._getSampleCount( renderContext );
  42316. const descriptor = {
  42317. label: 'renderBundleEncoder',
  42318. colorFormats: [ colorFormat ],
  42319. depthStencilFormat,
  42320. sampleCount
  42321. };
  42322. return device.createRenderBundleEncoder( descriptor );
  42323. }
  42324. createComputePipeline( pipeline, bindings ) {
  42325. const backend = this.backend;
  42326. const device = backend.device;
  42327. const computeProgram = backend.get( pipeline.computeProgram ).module;
  42328. const pipelineGPU = backend.get( pipeline );
  42329. // bind group layouts
  42330. const bindGroupLayouts = [];
  42331. for ( const bindingsGroup of bindings ) {
  42332. const bindingsData = backend.get( bindingsGroup );
  42333. bindGroupLayouts.push( bindingsData.layout );
  42334. }
  42335. pipelineGPU.pipeline = device.createComputePipeline( {
  42336. compute: computeProgram,
  42337. layout: device.createPipelineLayout( {
  42338. bindGroupLayouts
  42339. } )
  42340. } );
  42341. }
  42342. _getBlending( material ) {
  42343. let color, alpha;
  42344. const blending = material.blending;
  42345. const blendSrc = material.blendSrc;
  42346. const blendDst = material.blendDst;
  42347. const blendEquation = material.blendEquation;
  42348. if ( blending === CustomBlending ) {
  42349. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  42350. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  42351. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  42352. color = {
  42353. srcFactor: this._getBlendFactor( blendSrc ),
  42354. dstFactor: this._getBlendFactor( blendDst ),
  42355. operation: this._getBlendOperation( blendEquation )
  42356. };
  42357. alpha = {
  42358. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  42359. dstFactor: this._getBlendFactor( blendDstAlpha ),
  42360. operation: this._getBlendOperation( blendEquationAlpha )
  42361. };
  42362. } else {
  42363. const premultipliedAlpha = material.premultipliedAlpha;
  42364. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  42365. color = {
  42366. srcFactor: srcRGB,
  42367. dstFactor: dstRGB,
  42368. operation: GPUBlendOperation.Add
  42369. };
  42370. alpha = {
  42371. srcFactor: srcAlpha,
  42372. dstFactor: dstAlpha,
  42373. operation: GPUBlendOperation.Add
  42374. };
  42375. };
  42376. if ( premultipliedAlpha ) {
  42377. switch ( blending ) {
  42378. case NormalBlending:
  42379. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  42380. break;
  42381. case AdditiveBlending:
  42382. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  42383. break;
  42384. case SubtractiveBlending:
  42385. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  42386. break;
  42387. case MultiplyBlending:
  42388. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  42389. break;
  42390. }
  42391. } else {
  42392. switch ( blending ) {
  42393. case NormalBlending:
  42394. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  42395. break;
  42396. case AdditiveBlending:
  42397. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  42398. break;
  42399. case SubtractiveBlending:
  42400. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  42401. break;
  42402. case MultiplyBlending:
  42403. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  42404. break;
  42405. }
  42406. }
  42407. }
  42408. if ( color !== undefined && alpha !== undefined ) {
  42409. return { color, alpha };
  42410. } else {
  42411. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  42412. }
  42413. }
  42414. _getBlendFactor( blend ) {
  42415. let blendFactor;
  42416. switch ( blend ) {
  42417. case ZeroFactor:
  42418. blendFactor = GPUBlendFactor.Zero;
  42419. break;
  42420. case OneFactor:
  42421. blendFactor = GPUBlendFactor.One;
  42422. break;
  42423. case SrcColorFactor:
  42424. blendFactor = GPUBlendFactor.Src;
  42425. break;
  42426. case OneMinusSrcColorFactor:
  42427. blendFactor = GPUBlendFactor.OneMinusSrc;
  42428. break;
  42429. case SrcAlphaFactor:
  42430. blendFactor = GPUBlendFactor.SrcAlpha;
  42431. break;
  42432. case OneMinusSrcAlphaFactor:
  42433. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  42434. break;
  42435. case DstColorFactor:
  42436. blendFactor = GPUBlendFactor.Dst;
  42437. break;
  42438. case OneMinusDstColorFactor:
  42439. blendFactor = GPUBlendFactor.OneMinusDstColor;
  42440. break;
  42441. case DstAlphaFactor:
  42442. blendFactor = GPUBlendFactor.DstAlpha;
  42443. break;
  42444. case OneMinusDstAlphaFactor:
  42445. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  42446. break;
  42447. case SrcAlphaSaturateFactor:
  42448. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  42449. break;
  42450. case BlendColorFactor:
  42451. blendFactor = GPUBlendFactor.Constant;
  42452. break;
  42453. case OneMinusBlendColorFactor:
  42454. blendFactor = GPUBlendFactor.OneMinusConstant;
  42455. break;
  42456. default:
  42457. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  42458. }
  42459. return blendFactor;
  42460. }
  42461. _getStencilCompare( material ) {
  42462. let stencilCompare;
  42463. const stencilFunc = material.stencilFunc;
  42464. switch ( stencilFunc ) {
  42465. case NeverStencilFunc:
  42466. stencilCompare = GPUCompareFunction.Never;
  42467. break;
  42468. case AlwaysStencilFunc:
  42469. stencilCompare = GPUCompareFunction.Always;
  42470. break;
  42471. case LessStencilFunc:
  42472. stencilCompare = GPUCompareFunction.Less;
  42473. break;
  42474. case LessEqualStencilFunc:
  42475. stencilCompare = GPUCompareFunction.LessEqual;
  42476. break;
  42477. case EqualStencilFunc:
  42478. stencilCompare = GPUCompareFunction.Equal;
  42479. break;
  42480. case GreaterEqualStencilFunc:
  42481. stencilCompare = GPUCompareFunction.GreaterEqual;
  42482. break;
  42483. case GreaterStencilFunc:
  42484. stencilCompare = GPUCompareFunction.Greater;
  42485. break;
  42486. case NotEqualStencilFunc:
  42487. stencilCompare = GPUCompareFunction.NotEqual;
  42488. break;
  42489. default:
  42490. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  42491. }
  42492. return stencilCompare;
  42493. }
  42494. _getStencilOperation( op ) {
  42495. let stencilOperation;
  42496. switch ( op ) {
  42497. case KeepStencilOp:
  42498. stencilOperation = GPUStencilOperation.Keep;
  42499. break;
  42500. case ZeroStencilOp:
  42501. stencilOperation = GPUStencilOperation.Zero;
  42502. break;
  42503. case ReplaceStencilOp:
  42504. stencilOperation = GPUStencilOperation.Replace;
  42505. break;
  42506. case InvertStencilOp:
  42507. stencilOperation = GPUStencilOperation.Invert;
  42508. break;
  42509. case IncrementStencilOp:
  42510. stencilOperation = GPUStencilOperation.IncrementClamp;
  42511. break;
  42512. case DecrementStencilOp:
  42513. stencilOperation = GPUStencilOperation.DecrementClamp;
  42514. break;
  42515. case IncrementWrapStencilOp:
  42516. stencilOperation = GPUStencilOperation.IncrementWrap;
  42517. break;
  42518. case DecrementWrapStencilOp:
  42519. stencilOperation = GPUStencilOperation.DecrementWrap;
  42520. break;
  42521. default:
  42522. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  42523. }
  42524. return stencilOperation;
  42525. }
  42526. _getBlendOperation( blendEquation ) {
  42527. let blendOperation;
  42528. switch ( blendEquation ) {
  42529. case AddEquation:
  42530. blendOperation = GPUBlendOperation.Add;
  42531. break;
  42532. case SubtractEquation:
  42533. blendOperation = GPUBlendOperation.Subtract;
  42534. break;
  42535. case ReverseSubtractEquation:
  42536. blendOperation = GPUBlendOperation.ReverseSubtract;
  42537. break;
  42538. case MinEquation:
  42539. blendOperation = GPUBlendOperation.Min;
  42540. break;
  42541. case MaxEquation:
  42542. blendOperation = GPUBlendOperation.Max;
  42543. break;
  42544. default:
  42545. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  42546. }
  42547. return blendOperation;
  42548. }
  42549. _getPrimitiveState( object, geometry, material ) {
  42550. const descriptor = {};
  42551. const utils = this.backend.utils;
  42552. descriptor.topology = utils.getPrimitiveTopology( object, material );
  42553. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  42554. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  42555. }
  42556. switch ( material.side ) {
  42557. case FrontSide:
  42558. descriptor.frontFace = GPUFrontFace.CCW;
  42559. descriptor.cullMode = GPUCullMode.Back;
  42560. break;
  42561. case BackSide:
  42562. descriptor.frontFace = GPUFrontFace.CCW;
  42563. descriptor.cullMode = GPUCullMode.Front;
  42564. break;
  42565. case DoubleSide:
  42566. descriptor.frontFace = GPUFrontFace.CCW;
  42567. descriptor.cullMode = GPUCullMode.None;
  42568. break;
  42569. default:
  42570. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  42571. break;
  42572. }
  42573. return descriptor;
  42574. }
  42575. _getColorWriteMask( material ) {
  42576. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  42577. }
  42578. _getDepthCompare( material ) {
  42579. let depthCompare;
  42580. if ( material.depthTest === false ) {
  42581. depthCompare = GPUCompareFunction.Always;
  42582. } else {
  42583. const depthFunc = material.depthFunc;
  42584. switch ( depthFunc ) {
  42585. case NeverDepth:
  42586. depthCompare = GPUCompareFunction.Never;
  42587. break;
  42588. case AlwaysDepth:
  42589. depthCompare = GPUCompareFunction.Always;
  42590. break;
  42591. case LessDepth:
  42592. depthCompare = GPUCompareFunction.Less;
  42593. break;
  42594. case LessEqualDepth:
  42595. depthCompare = GPUCompareFunction.LessEqual;
  42596. break;
  42597. case EqualDepth:
  42598. depthCompare = GPUCompareFunction.Equal;
  42599. break;
  42600. case GreaterEqualDepth:
  42601. depthCompare = GPUCompareFunction.GreaterEqual;
  42602. break;
  42603. case GreaterDepth:
  42604. depthCompare = GPUCompareFunction.Greater;
  42605. break;
  42606. case NotEqualDepth:
  42607. depthCompare = GPUCompareFunction.NotEqual;
  42608. break;
  42609. default:
  42610. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  42611. }
  42612. }
  42613. return depthCompare;
  42614. }
  42615. }
  42616. /*// debugger tools
  42617. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  42618. //*/
  42619. /**
  42620. * A backend implementation targeting WebGPU.
  42621. *
  42622. * @private
  42623. * @augments Backend
  42624. */
  42625. class WebGPUBackend extends Backend {
  42626. /**
  42627. * Constructs a new WebGPU backend.
  42628. *
  42629. * @param {Object} parameters - The configuration parameter.
  42630. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  42631. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  42632. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  42633. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  42634. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  42635. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  42636. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses it WebGL 2 backend no matter if WebGPU is supported or not.
  42637. * @param {Boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  42638. * @param {String?} [parameters.powerPreference=null] - The power preference.
  42639. * @param {String?} [parameters.requiredLimits={}] - Specifies the limits that are required by the device request.
  42640. * The request will fail if the adapter cannot provide these limits.
  42641. */
  42642. constructor( parameters = {} ) {
  42643. super( parameters );
  42644. /**
  42645. * This flag can be used for type testing.
  42646. *
  42647. * @type {Boolean}
  42648. * @readonly
  42649. * @default true
  42650. */
  42651. this.isWebGPUBackend = true;
  42652. // some parameters require default values other than "undefined"
  42653. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  42654. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  42655. /**
  42656. * Whether to track timestamps with a Timestamp Query API or not.
  42657. *
  42658. * @type {Boolean}
  42659. * @default false
  42660. */
  42661. this.trackTimestamp = ( parameters.trackTimestamp === true );
  42662. /**
  42663. * A reference to the device.
  42664. *
  42665. * @type {GPUDevice?}
  42666. * @default null
  42667. */
  42668. this.device = null;
  42669. /**
  42670. * A reference to the context.
  42671. *
  42672. * @type {GPUCanvasContext?}
  42673. * @default null
  42674. */
  42675. this.context = null;
  42676. /**
  42677. * A reference to the color attachment of the default framebuffer.
  42678. *
  42679. * @type {GPUTexture?}
  42680. * @default null
  42681. */
  42682. this.colorBuffer = null;
  42683. /**
  42684. * A reference to the default render pass descriptor.
  42685. *
  42686. * @type {Object?}
  42687. * @default null
  42688. */
  42689. this.defaultRenderPassdescriptor = null;
  42690. /**
  42691. * A reference to a backend module holding common utility functions.
  42692. *
  42693. * @type {WebGPUUtils}
  42694. */
  42695. this.utils = new WebGPUUtils( this );
  42696. /**
  42697. * A reference to a backend module holding shader attribute-related
  42698. * utility functions.
  42699. *
  42700. * @type {WebGPUAttributeUtils}
  42701. */
  42702. this.attributeUtils = new WebGPUAttributeUtils( this );
  42703. /**
  42704. * A reference to a backend module holding shader binding-related
  42705. * utility functions.
  42706. *
  42707. * @type {WebGPUBindingUtils}
  42708. */
  42709. this.bindingUtils = new WebGPUBindingUtils( this );
  42710. /**
  42711. * A reference to a backend module holding shader pipeline-related
  42712. * utility functions.
  42713. *
  42714. * @type {WebGPUPipelineUtils}
  42715. */
  42716. this.pipelineUtils = new WebGPUPipelineUtils( this );
  42717. /**
  42718. * A reference to a backend module holding shader texture-related
  42719. * utility functions.
  42720. *
  42721. * @type {WebGPUTextureUtils}
  42722. */
  42723. this.textureUtils = new WebGPUTextureUtils( this );
  42724. /**
  42725. * A map that manages the resolve buffers for occlusion queries.
  42726. *
  42727. * @type {Map<Number,GPUBuffer>}
  42728. */
  42729. this.occludedResolveCache = new Map();
  42730. }
  42731. /**
  42732. * Initializes the backend so it is ready for usage.
  42733. *
  42734. * @async
  42735. * @param {Renderer} renderer - The renderer.
  42736. * @return {Promise} A Promise that resolves when the backend has been initialized.
  42737. */
  42738. async init( renderer ) {
  42739. await super.init( renderer );
  42740. //
  42741. const parameters = this.parameters;
  42742. // create the device if it is not passed with parameters
  42743. let device;
  42744. if ( parameters.device === undefined ) {
  42745. const adapterOptions = {
  42746. powerPreference: parameters.powerPreference
  42747. };
  42748. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  42749. if ( adapter === null ) {
  42750. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  42751. }
  42752. // feature support
  42753. const features = Object.values( GPUFeatureName );
  42754. const supportedFeatures = [];
  42755. for ( const name of features ) {
  42756. if ( adapter.features.has( name ) ) {
  42757. supportedFeatures.push( name );
  42758. }
  42759. }
  42760. const deviceDescriptor = {
  42761. requiredFeatures: supportedFeatures,
  42762. requiredLimits: parameters.requiredLimits
  42763. };
  42764. device = await adapter.requestDevice( deviceDescriptor );
  42765. } else {
  42766. device = parameters.device;
  42767. }
  42768. device.lost.then( ( info ) => {
  42769. const deviceLossInfo = {
  42770. api: 'WebGPU',
  42771. message: info.message || 'Unknown reason',
  42772. reason: info.reason || null,
  42773. originalEvent: info
  42774. };
  42775. renderer.onDeviceLost( deviceLossInfo );
  42776. } );
  42777. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  42778. this.device = device;
  42779. this.context = context;
  42780. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  42781. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  42782. this.context.configure( {
  42783. device: this.device,
  42784. format: this.utils.getPreferredCanvasFormat(),
  42785. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  42786. alphaMode: alphaMode
  42787. } );
  42788. this.updateSize();
  42789. }
  42790. /**
  42791. * The coordinate system of the backend.
  42792. *
  42793. * @type {Number}
  42794. * @readonly
  42795. */
  42796. get coordinateSystem() {
  42797. return WebGPUCoordinateSystem;
  42798. }
  42799. /**
  42800. * Transfers buffer data from a storage buffer attribute
  42801. * from the GPU to the CPU in context of compute shaders.
  42802. *
  42803. * @async
  42804. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42805. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42806. */
  42807. async getArrayBufferAsync( attribute ) {
  42808. return await this.attributeUtils.getArrayBufferAsync( attribute );
  42809. }
  42810. /**
  42811. * Returns the backend's rendering context.
  42812. *
  42813. * @return {GPUCanvasContext} The rendering context.
  42814. */
  42815. getContext() {
  42816. return this.context;
  42817. }
  42818. /**
  42819. * Returns the default render pass descriptor.
  42820. *
  42821. * In WebGPU, the default framebuffer must be configured
  42822. * like custom fraemebuffers so the backend needs a render
  42823. * pass descriptor even when rendering directly to screen.
  42824. *
  42825. * @private
  42826. * @return {Object} The render pass descriptor.
  42827. */
  42828. _getDefaultRenderPassDescriptor() {
  42829. let descriptor = this.defaultRenderPassdescriptor;
  42830. if ( descriptor === null ) {
  42831. const renderer = this.renderer;
  42832. descriptor = {
  42833. colorAttachments: [ {
  42834. view: null
  42835. } ],
  42836. };
  42837. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  42838. descriptor.depthStencilAttachment = {
  42839. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  42840. };
  42841. }
  42842. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42843. if ( this.renderer.samples > 0 ) {
  42844. colorAttachment.view = this.colorBuffer.createView();
  42845. } else {
  42846. colorAttachment.resolveTarget = undefined;
  42847. }
  42848. this.defaultRenderPassdescriptor = descriptor;
  42849. }
  42850. const colorAttachment = descriptor.colorAttachments[ 0 ];
  42851. if ( this.renderer.samples > 0 ) {
  42852. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  42853. } else {
  42854. colorAttachment.view = this.context.getCurrentTexture().createView();
  42855. }
  42856. return descriptor;
  42857. }
  42858. /**
  42859. * Returns the render pass descriptor for the given render context.
  42860. *
  42861. * @private
  42862. * @param {RenderContext} renderContext - The render context.
  42863. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  42864. * @return {Object} The render pass descriptor.
  42865. */
  42866. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  42867. const renderTarget = renderContext.renderTarget;
  42868. const renderTargetData = this.get( renderTarget );
  42869. let descriptors = renderTargetData.descriptors;
  42870. if ( descriptors === undefined ||
  42871. renderTargetData.width !== renderTarget.width ||
  42872. renderTargetData.height !== renderTarget.height ||
  42873. renderTargetData.dimensions !== renderTarget.dimensions ||
  42874. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  42875. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  42876. renderTargetData.samples !== renderTarget.samples ||
  42877. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  42878. ) {
  42879. descriptors = {};
  42880. renderTargetData.descriptors = descriptors;
  42881. // dispose
  42882. const onDispose = () => {
  42883. renderTarget.removeEventListener( 'dispose', onDispose );
  42884. this.delete( renderTarget );
  42885. };
  42886. renderTarget.addEventListener( 'dispose', onDispose );
  42887. }
  42888. const cacheKey = renderContext.getCacheKey();
  42889. let descriptor = descriptors[ cacheKey ];
  42890. if ( descriptor === undefined ) {
  42891. const textures = renderContext.textures;
  42892. const colorAttachments = [];
  42893. let sliceIndex;
  42894. for ( let i = 0; i < textures.length; i ++ ) {
  42895. const textureData = this.get( textures[ i ] );
  42896. const viewDescriptor = {
  42897. label: `colorAttachment_${ i }`,
  42898. baseMipLevel: renderContext.activeMipmapLevel,
  42899. mipLevelCount: 1,
  42900. baseArrayLayer: renderContext.activeCubeFace,
  42901. arrayLayerCount: 1,
  42902. dimension: GPUTextureViewDimension.TwoD
  42903. };
  42904. if ( renderTarget.isRenderTarget3D ) {
  42905. sliceIndex = renderContext.activeCubeFace;
  42906. viewDescriptor.baseArrayLayer = 0;
  42907. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  42908. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  42909. } else if ( renderTarget.isRenderTargetArray ) {
  42910. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  42911. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  42912. }
  42913. const textureView = textureData.texture.createView( viewDescriptor );
  42914. let view, resolveTarget;
  42915. if ( textureData.msaaTexture !== undefined ) {
  42916. view = textureData.msaaTexture.createView();
  42917. resolveTarget = textureView;
  42918. } else {
  42919. view = textureView;
  42920. resolveTarget = undefined;
  42921. }
  42922. colorAttachments.push( {
  42923. view,
  42924. depthSlice: sliceIndex,
  42925. resolveTarget,
  42926. loadOp: GPULoadOp.Load,
  42927. storeOp: GPUStoreOp.Store,
  42928. ...colorAttachmentsConfig
  42929. } );
  42930. }
  42931. descriptor = {
  42932. colorAttachments,
  42933. };
  42934. if ( renderContext.depth ) {
  42935. const depthTextureData = this.get( renderContext.depthTexture );
  42936. const depthStencilAttachment = {
  42937. view: depthTextureData.texture.createView()
  42938. };
  42939. descriptor.depthStencilAttachment = depthStencilAttachment;
  42940. }
  42941. descriptors[ cacheKey ] = descriptor;
  42942. renderTargetData.width = renderTarget.width;
  42943. renderTargetData.height = renderTarget.height;
  42944. renderTargetData.samples = renderTarget.samples;
  42945. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  42946. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  42947. renderTargetData.dimensions = renderTarget.dimensions;
  42948. renderTargetData.depthSlice = sliceIndex;
  42949. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  42950. }
  42951. return descriptor;
  42952. }
  42953. /**
  42954. * This method is executed at the beginning of a render call and prepares
  42955. * the WebGPU state for upcoming render calls
  42956. *
  42957. * @param {RenderContext} renderContext - The render context.
  42958. */
  42959. beginRender( renderContext ) {
  42960. const renderContextData = this.get( renderContext );
  42961. const device = this.device;
  42962. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42963. let occlusionQuerySet;
  42964. if ( occlusionQueryCount > 0 ) {
  42965. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  42966. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  42967. // Get a reference to the array of objects with queries. The renderContextData property
  42968. // can be changed by another render pass before the buffer.mapAsyc() completes.
  42969. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  42970. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  42971. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  42972. //
  42973. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  42974. renderContextData.occlusionQuerySet = occlusionQuerySet;
  42975. renderContextData.occlusionQueryIndex = 0;
  42976. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  42977. renderContextData.lastOcclusionObject = null;
  42978. }
  42979. let descriptor;
  42980. if ( renderContext.textures === null ) {
  42981. descriptor = this._getDefaultRenderPassDescriptor();
  42982. } else {
  42983. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  42984. }
  42985. this.initTimestampQuery( renderContext, descriptor );
  42986. descriptor.occlusionQuerySet = occlusionQuerySet;
  42987. const depthStencilAttachment = descriptor.depthStencilAttachment;
  42988. if ( renderContext.textures !== null ) {
  42989. const colorAttachments = descriptor.colorAttachments;
  42990. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  42991. const colorAttachment = colorAttachments[ i ];
  42992. if ( renderContext.clearColor ) {
  42993. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  42994. colorAttachment.loadOp = GPULoadOp.Clear;
  42995. colorAttachment.storeOp = GPUStoreOp.Store;
  42996. } else {
  42997. colorAttachment.loadOp = GPULoadOp.Load;
  42998. colorAttachment.storeOp = GPUStoreOp.Store;
  42999. }
  43000. }
  43001. } else {
  43002. const colorAttachment = descriptor.colorAttachments[ 0 ];
  43003. if ( renderContext.clearColor ) {
  43004. colorAttachment.clearValue = renderContext.clearColorValue;
  43005. colorAttachment.loadOp = GPULoadOp.Clear;
  43006. colorAttachment.storeOp = GPUStoreOp.Store;
  43007. } else {
  43008. colorAttachment.loadOp = GPULoadOp.Load;
  43009. colorAttachment.storeOp = GPUStoreOp.Store;
  43010. }
  43011. }
  43012. //
  43013. if ( renderContext.depth ) {
  43014. if ( renderContext.clearDepth ) {
  43015. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  43016. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  43017. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43018. } else {
  43019. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43020. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43021. }
  43022. }
  43023. if ( renderContext.stencil ) {
  43024. if ( renderContext.clearStencil ) {
  43025. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  43026. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  43027. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43028. } else {
  43029. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43030. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43031. }
  43032. }
  43033. //
  43034. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  43035. const currentPass = encoder.beginRenderPass( descriptor );
  43036. //
  43037. renderContextData.descriptor = descriptor;
  43038. renderContextData.encoder = encoder;
  43039. renderContextData.currentPass = currentPass;
  43040. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  43041. renderContextData.renderBundles = [];
  43042. //
  43043. if ( renderContext.viewport ) {
  43044. this.updateViewport( renderContext );
  43045. }
  43046. if ( renderContext.scissor ) {
  43047. const { x, y, width, height } = renderContext.scissorValue;
  43048. currentPass.setScissorRect( x, y, width, height );
  43049. }
  43050. }
  43051. /**
  43052. * This method is executed at the end of a render call and finalizes work
  43053. * after draw calls.
  43054. *
  43055. * @param {RenderContext} renderContext - The render context.
  43056. */
  43057. finishRender( renderContext ) {
  43058. const renderContextData = this.get( renderContext );
  43059. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43060. if ( renderContextData.renderBundles.length > 0 ) {
  43061. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  43062. }
  43063. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  43064. renderContextData.currentPass.endOcclusionQuery();
  43065. }
  43066. renderContextData.currentPass.end();
  43067. if ( occlusionQueryCount > 0 ) {
  43068. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  43069. //
  43070. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  43071. if ( queryResolveBuffer === undefined ) {
  43072. queryResolveBuffer = this.device.createBuffer(
  43073. {
  43074. size: bufferSize,
  43075. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  43076. }
  43077. );
  43078. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  43079. }
  43080. //
  43081. const readBuffer = this.device.createBuffer(
  43082. {
  43083. size: bufferSize,
  43084. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43085. }
  43086. );
  43087. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  43088. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  43089. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  43090. renderContextData.occlusionQueryBuffer = readBuffer;
  43091. //
  43092. this.resolveOccludedAsync( renderContext );
  43093. }
  43094. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  43095. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  43096. //
  43097. if ( renderContext.textures !== null ) {
  43098. const textures = renderContext.textures;
  43099. for ( let i = 0; i < textures.length; i ++ ) {
  43100. const texture = textures[ i ];
  43101. if ( texture.generateMipmaps === true ) {
  43102. this.textureUtils.generateMipmaps( texture );
  43103. }
  43104. }
  43105. }
  43106. }
  43107. /**
  43108. * Returns `true` if the given 3D object is fully occluded by other
  43109. * 3D objects in the scene.
  43110. *
  43111. * @param {RenderContext} renderContext - The render context.
  43112. * @param {Object3D} object - The 3D object to test.
  43113. * @return {Boolean} Whether the 3D object is fully occluded or not.
  43114. */
  43115. isOccluded( renderContext, object ) {
  43116. const renderContextData = this.get( renderContext );
  43117. return renderContextData.occluded && renderContextData.occluded.has( object );
  43118. }
  43119. /**
  43120. * This method processes the result of occlusion queries and writes it
  43121. * into render context data.
  43122. *
  43123. * @async
  43124. * @param {RenderContext} renderContext - The render context.
  43125. */
  43126. async resolveOccludedAsync( renderContext ) {
  43127. const renderContextData = this.get( renderContext );
  43128. // handle occlusion query results
  43129. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  43130. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  43131. const occluded = new WeakSet();
  43132. renderContextData.currentOcclusionQueryObjects = null;
  43133. renderContextData.currentOcclusionQueryBuffer = null;
  43134. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  43135. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  43136. const results = new BigUint64Array( buffer );
  43137. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  43138. if ( results[ i ] !== BigInt( 0 ) ) {
  43139. occluded.add( currentOcclusionQueryObjects[ i ] );
  43140. }
  43141. }
  43142. currentOcclusionQueryBuffer.destroy();
  43143. renderContextData.occluded = occluded;
  43144. }
  43145. }
  43146. /**
  43147. * Updates the viewport with the values from the given render context.
  43148. *
  43149. * @param {RenderContext} renderContext - The render context.
  43150. */
  43151. updateViewport( renderContext ) {
  43152. const { currentPass } = this.get( renderContext );
  43153. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  43154. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  43155. }
  43156. /**
  43157. * Performs a clear operation.
  43158. *
  43159. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  43160. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  43161. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  43162. * @param {RenderContext?} [renderTargetContext=null] - The render context of the current set render target.
  43163. */
  43164. clear( color, depth, stencil, renderTargetContext = null ) {
  43165. const device = this.device;
  43166. const renderer = this.renderer;
  43167. let colorAttachments = [];
  43168. let depthStencilAttachment;
  43169. let clearValue;
  43170. let supportsDepth;
  43171. let supportsStencil;
  43172. if ( color ) {
  43173. const clearColor = this.getClearColor();
  43174. if ( this.renderer.alpha === true ) {
  43175. // premultiply alpha
  43176. const a = clearColor.a;
  43177. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  43178. } else {
  43179. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  43180. }
  43181. }
  43182. if ( renderTargetContext === null ) {
  43183. supportsDepth = renderer.depth;
  43184. supportsStencil = renderer.stencil;
  43185. const descriptor = this._getDefaultRenderPassDescriptor();
  43186. if ( color ) {
  43187. colorAttachments = descriptor.colorAttachments;
  43188. const colorAttachment = colorAttachments[ 0 ];
  43189. colorAttachment.clearValue = clearValue;
  43190. colorAttachment.loadOp = GPULoadOp.Clear;
  43191. colorAttachment.storeOp = GPUStoreOp.Store;
  43192. }
  43193. if ( supportsDepth || supportsStencil ) {
  43194. depthStencilAttachment = descriptor.depthStencilAttachment;
  43195. }
  43196. } else {
  43197. supportsDepth = renderTargetContext.depth;
  43198. supportsStencil = renderTargetContext.stencil;
  43199. if ( color ) {
  43200. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear } );
  43201. colorAttachments = descriptor.colorAttachments;
  43202. }
  43203. if ( supportsDepth || supportsStencil ) {
  43204. const depthTextureData = this.get( renderTargetContext.depthTexture );
  43205. depthStencilAttachment = {
  43206. view: depthTextureData.texture.createView()
  43207. };
  43208. }
  43209. }
  43210. //
  43211. if ( supportsDepth ) {
  43212. if ( depth ) {
  43213. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  43214. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  43215. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43216. } else {
  43217. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43218. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  43219. }
  43220. }
  43221. //
  43222. if ( supportsStencil ) {
  43223. if ( stencil ) {
  43224. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  43225. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  43226. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43227. } else {
  43228. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43229. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  43230. }
  43231. }
  43232. //
  43233. const encoder = device.createCommandEncoder( {} );
  43234. const currentPass = encoder.beginRenderPass( {
  43235. colorAttachments,
  43236. depthStencilAttachment
  43237. } );
  43238. currentPass.end();
  43239. device.queue.submit( [ encoder.finish() ] );
  43240. }
  43241. // compute
  43242. /**
  43243. * This method is executed at the beginning of a compute call and
  43244. * prepares the state for upcoming compute tasks.
  43245. *
  43246. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43247. */
  43248. beginCompute( computeGroup ) {
  43249. const groupGPU = this.get( computeGroup );
  43250. const descriptor = {};
  43251. this.initTimestampQuery( computeGroup, descriptor );
  43252. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  43253. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  43254. }
  43255. /**
  43256. * Executes a compute command for the given compute node.
  43257. *
  43258. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  43259. * @param {Node} computeNode - The compute node.
  43260. * @param {Array<BindGroup>} bindings - The bindings.
  43261. * @param {ComputePipeline} pipeline - The compute pipeline.
  43262. */
  43263. compute( computeGroup, computeNode, bindings, pipeline ) {
  43264. const { passEncoderGPU } = this.get( computeGroup );
  43265. // pipeline
  43266. const pipelineGPU = this.get( pipeline ).pipeline;
  43267. passEncoderGPU.setPipeline( pipelineGPU );
  43268. // bind groups
  43269. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  43270. const bindGroup = bindings[ i ];
  43271. const bindingsData = this.get( bindGroup );
  43272. passEncoderGPU.setBindGroup( i, bindingsData.group );
  43273. }
  43274. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  43275. const computeNodeData = this.get( computeNode );
  43276. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  43277. const { dispatchSize } = computeNodeData;
  43278. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  43279. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  43280. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  43281. } else {
  43282. dispatchSize.x = computeNode.dispatchCount;
  43283. }
  43284. passEncoderGPU.dispatchWorkgroups(
  43285. dispatchSize.x,
  43286. dispatchSize.y,
  43287. dispatchSize.z
  43288. );
  43289. }
  43290. /**
  43291. * This method is executed at the end of a compute call and
  43292. * finalizes work after compute tasks.
  43293. *
  43294. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43295. */
  43296. finishCompute( computeGroup ) {
  43297. const groupData = this.get( computeGroup );
  43298. groupData.passEncoderGPU.end();
  43299. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  43300. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  43301. }
  43302. /**
  43303. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  43304. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  43305. *
  43306. * @async
  43307. * @return {Promise} A Promise that resolves when synchronization has been finished.
  43308. */
  43309. async waitForGPU() {
  43310. await this.device.queue.onSubmittedWorkDone();
  43311. }
  43312. // render object
  43313. /**
  43314. * Executes a draw command for the given render object.
  43315. *
  43316. * @param {RenderObject} renderObject - The render object to draw.
  43317. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  43318. */
  43319. draw( renderObject, info ) {
  43320. const { object, context, pipeline } = renderObject;
  43321. const bindings = renderObject.getBindings();
  43322. const renderContextData = this.get( context );
  43323. const pipelineGPU = this.get( pipeline ).pipeline;
  43324. const currentSets = renderContextData.currentSets;
  43325. const passEncoderGPU = renderContextData.currentPass;
  43326. const drawParams = renderObject.getDrawParameters();
  43327. if ( drawParams === null ) return;
  43328. // pipeline
  43329. if ( currentSets.pipeline !== pipelineGPU ) {
  43330. passEncoderGPU.setPipeline( pipelineGPU );
  43331. currentSets.pipeline = pipelineGPU;
  43332. }
  43333. // bind groups
  43334. const currentBindingGroups = currentSets.bindingGroups;
  43335. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  43336. const bindGroup = bindings[ i ];
  43337. const bindingsData = this.get( bindGroup );
  43338. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  43339. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  43340. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  43341. }
  43342. }
  43343. // attributes
  43344. const index = renderObject.getIndex();
  43345. const hasIndex = ( index !== null );
  43346. // index
  43347. if ( hasIndex === true ) {
  43348. if ( currentSets.index !== index ) {
  43349. const buffer = this.get( index ).buffer;
  43350. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  43351. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  43352. currentSets.index = index;
  43353. }
  43354. }
  43355. // vertex buffers
  43356. const vertexBuffers = renderObject.getVertexBuffers();
  43357. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  43358. const vertexBuffer = vertexBuffers[ i ];
  43359. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  43360. const buffer = this.get( vertexBuffer ).buffer;
  43361. passEncoderGPU.setVertexBuffer( i, buffer );
  43362. currentSets.attributes[ i ] = vertexBuffer;
  43363. }
  43364. }
  43365. // occlusion queries - handle multiple consecutive draw calls for an object
  43366. if ( renderContextData.occlusionQuerySet !== undefined ) {
  43367. const lastObject = renderContextData.lastOcclusionObject;
  43368. if ( lastObject !== object ) {
  43369. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  43370. passEncoderGPU.endOcclusionQuery();
  43371. renderContextData.occlusionQueryIndex ++;
  43372. }
  43373. if ( object.occlusionTest === true ) {
  43374. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  43375. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  43376. }
  43377. renderContextData.lastOcclusionObject = object;
  43378. }
  43379. }
  43380. // draw
  43381. if ( object.isBatchedMesh === true ) {
  43382. const starts = object._multiDrawStarts;
  43383. const counts = object._multiDrawCounts;
  43384. const drawCount = object._multiDrawCount;
  43385. const drawInstances = object._multiDrawInstances;
  43386. for ( let i = 0; i < drawCount; i ++ ) {
  43387. const count = drawInstances ? drawInstances[ i ] : 1;
  43388. const firstInstance = count > 1 ? 0 : i;
  43389. if ( hasIndex === true ) {
  43390. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  43391. } else {
  43392. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  43393. }
  43394. }
  43395. } else if ( hasIndex === true ) {
  43396. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  43397. const indirect = renderObject.getIndirect();
  43398. if ( indirect !== null ) {
  43399. const buffer = this.get( indirect ).buffer;
  43400. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  43401. } else {
  43402. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  43403. }
  43404. info.update( object, indexCount, instanceCount );
  43405. } else {
  43406. const { vertexCount, instanceCount, firstVertex } = drawParams;
  43407. const indirect = renderObject.getIndirect();
  43408. if ( indirect !== null ) {
  43409. const buffer = this.get( indirect ).buffer;
  43410. passEncoderGPU.drawIndirect( buffer, 0 );
  43411. } else {
  43412. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  43413. }
  43414. info.update( object, vertexCount, instanceCount );
  43415. }
  43416. }
  43417. // cache key
  43418. /**
  43419. * Returns `true` if the render pipeline requires an update.
  43420. *
  43421. * @param {RenderObject} renderObject - The render object.
  43422. * @return {Boolean} Whether the render pipeline requires an update or not.
  43423. */
  43424. needsRenderUpdate( renderObject ) {
  43425. const data = this.get( renderObject );
  43426. const { object, material } = renderObject;
  43427. const utils = this.utils;
  43428. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  43429. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  43430. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  43431. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  43432. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  43433. let needsUpdate = false;
  43434. if ( data.material !== material || data.materialVersion !== material.version ||
  43435. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  43436. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  43437. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  43438. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  43439. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  43440. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  43441. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  43442. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  43443. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  43444. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  43445. data.primitiveTopology !== primitiveTopology ||
  43446. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  43447. ) {
  43448. data.material = material; data.materialVersion = material.version;
  43449. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  43450. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  43451. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  43452. data.colorWrite = material.colorWrite;
  43453. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  43454. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  43455. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  43456. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  43457. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  43458. data.sampleCount = sampleCount;
  43459. data.colorSpace = colorSpace;
  43460. data.colorFormat = colorFormat;
  43461. data.depthStencilFormat = depthStencilFormat;
  43462. data.primitiveTopology = primitiveTopology;
  43463. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  43464. needsUpdate = true;
  43465. }
  43466. return needsUpdate;
  43467. }
  43468. /**
  43469. * Returns a cache key that is used to identify render pipelines.
  43470. *
  43471. * @param {RenderObject} renderObject - The render object.
  43472. * @return {String} The cache key.
  43473. */
  43474. getRenderCacheKey( renderObject ) {
  43475. const { object, material } = renderObject;
  43476. const utils = this.utils;
  43477. const renderContext = renderObject.context;
  43478. return [
  43479. material.transparent, material.blending, material.premultipliedAlpha,
  43480. material.blendSrc, material.blendDst, material.blendEquation,
  43481. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  43482. material.colorWrite,
  43483. material.depthWrite, material.depthTest, material.depthFunc,
  43484. material.stencilWrite, material.stencilFunc,
  43485. material.stencilFail, material.stencilZFail, material.stencilZPass,
  43486. material.stencilFuncMask, material.stencilWriteMask,
  43487. material.side,
  43488. utils.getSampleCountRenderContext( renderContext ),
  43489. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  43490. utils.getPrimitiveTopology( object, material ),
  43491. renderObject.getGeometryCacheKey(),
  43492. renderObject.clippingContextCacheKey
  43493. ].join();
  43494. }
  43495. // textures
  43496. /**
  43497. * Creates a sampler for the given texture.
  43498. *
  43499. * @param {Texture} texture - The texture to create the sampler for.
  43500. */
  43501. createSampler( texture ) {
  43502. this.textureUtils.createSampler( texture );
  43503. }
  43504. /**
  43505. * Destroys the sampler for the given texture.
  43506. *
  43507. * @param {Texture} texture - The texture to destroy the sampler for.
  43508. */
  43509. destroySampler( texture ) {
  43510. this.textureUtils.destroySampler( texture );
  43511. }
  43512. /**
  43513. * Creates a default texture for the given texture that can be used
  43514. * as a placeholder until the actual texture is ready for usage.
  43515. *
  43516. * @param {Texture} texture - The texture to create a default texture for.
  43517. */
  43518. createDefaultTexture( texture ) {
  43519. this.textureUtils.createDefaultTexture( texture );
  43520. }
  43521. /**
  43522. * Defines a texture on the GPU for the given texture object.
  43523. *
  43524. * @param {Texture} texture - The texture.
  43525. * @param {Object} [options={}] - Optional configuration parameter.
  43526. */
  43527. createTexture( texture, options ) {
  43528. this.textureUtils.createTexture( texture, options );
  43529. }
  43530. /**
  43531. * Uploads the updated texture data to the GPU.
  43532. *
  43533. * @param {Texture} texture - The texture.
  43534. * @param {Object} [options={}] - Optional configuration parameter.
  43535. */
  43536. updateTexture( texture, options ) {
  43537. this.textureUtils.updateTexture( texture, options );
  43538. }
  43539. /**
  43540. * Generates mipmaps for the given texture
  43541. *
  43542. * @param {Texture} texture - The texture.
  43543. */
  43544. generateMipmaps( texture ) {
  43545. this.textureUtils.generateMipmaps( texture );
  43546. }
  43547. /**
  43548. * Destroys the GPU data for the given texture object.
  43549. *
  43550. * @param {Texture} texture - The texture.
  43551. */
  43552. destroyTexture( texture ) {
  43553. this.textureUtils.destroyTexture( texture );
  43554. }
  43555. /**
  43556. * Returns texture data as a typed array.
  43557. *
  43558. * @param {Texture} texture - The texture to copy.
  43559. * @param {Number} x - The x coordinate of the copy origin.
  43560. * @param {Number} y - The y coordinate of the copy origin.
  43561. * @param {Number} width - The width of the copy.
  43562. * @param {Number} height - The height of the copy.
  43563. * @param {Number} faceIndex - The face index.
  43564. * @return {TypedArray} The texture data as a typed array.
  43565. */
  43566. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  43567. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  43568. }
  43569. /**
  43570. * Inits a time stamp query for the given render context.
  43571. *
  43572. * @param {RenderContext} renderContext - The render context.
  43573. * @param {Object} descriptor - The query descriptor.
  43574. */
  43575. initTimestampQuery( renderContext, descriptor ) {
  43576. if ( ! this.trackTimestamp ) return;
  43577. const renderContextData = this.get( renderContext );
  43578. if ( ! renderContextData.timeStampQuerySet ) {
  43579. const type = renderContext.isComputeNode ? 'compute' : 'render';
  43580. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  43581. const timestampWrites = {
  43582. querySet: timeStampQuerySet,
  43583. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  43584. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  43585. };
  43586. Object.assign( descriptor, { timestampWrites } );
  43587. renderContextData.timeStampQuerySet = timeStampQuerySet;
  43588. }
  43589. }
  43590. /**
  43591. * Prepares the timestamp buffer.
  43592. *
  43593. * @param {RenderContext} renderContext - The render context.
  43594. * @param {GPUCommandEncoder} encoder - The command encoder.
  43595. */
  43596. prepareTimestampBuffer( renderContext, encoder ) {
  43597. if ( ! this.trackTimestamp ) return;
  43598. const renderContextData = this.get( renderContext );
  43599. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  43600. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  43601. renderContextData.currentTimestampQueryBuffers = {
  43602. resolveBuffer: this.device.createBuffer( {
  43603. label: 'timestamp resolve buffer',
  43604. size: size,
  43605. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  43606. } ),
  43607. resultBuffer: this.device.createBuffer( {
  43608. label: 'timestamp result buffer',
  43609. size: size,
  43610. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  43611. } )
  43612. };
  43613. }
  43614. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  43615. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  43616. if ( resultBuffer.mapState === 'unmapped' ) {
  43617. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  43618. }
  43619. }
  43620. /**
  43621. * Resolves the time stamp for the given render context and type.
  43622. *
  43623. * @async
  43624. * @param {RenderContext} renderContext - The render context.
  43625. * @param {String} type - The render context.
  43626. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  43627. */
  43628. async resolveTimestampAsync( renderContext, type = 'render' ) {
  43629. if ( ! this.trackTimestamp ) return;
  43630. const renderContextData = this.get( renderContext );
  43631. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  43632. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  43633. if ( resultBuffer.mapState === 'unmapped' ) {
  43634. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  43635. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  43636. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  43637. this.renderer.info.updateTimestamp( type, duration );
  43638. resultBuffer.unmap();
  43639. } );
  43640. }
  43641. }
  43642. // node builder
  43643. /**
  43644. * Returns a node builder for the given render object.
  43645. *
  43646. * @param {RenderObject} object - The render object.
  43647. * @param {Renderer} renderer - The renderer.
  43648. * @return {WGSLNodeBuilder} The node builder.
  43649. */
  43650. createNodeBuilder( object, renderer ) {
  43651. return new WGSLNodeBuilder( object, renderer );
  43652. }
  43653. // program
  43654. /**
  43655. * Creates a shader program from the given programmable stage.
  43656. *
  43657. * @param {ProgrammableStage} program - The programmable stage.
  43658. */
  43659. createProgram( program ) {
  43660. const programGPU = this.get( program );
  43661. programGPU.module = {
  43662. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  43663. entryPoint: 'main'
  43664. };
  43665. }
  43666. /**
  43667. * Destroys the shader program of the given programmable stage.
  43668. *
  43669. * @param {ProgrammableStage} program - The programmable stage.
  43670. */
  43671. destroyProgram( program ) {
  43672. this.delete( program );
  43673. }
  43674. // pipelines
  43675. /**
  43676. * Creates a render pipeline for the given render object.
  43677. *
  43678. * @param {RenderObject} renderObject - The render object.
  43679. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  43680. */
  43681. createRenderPipeline( renderObject, promises ) {
  43682. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  43683. }
  43684. /**
  43685. * Creates a compute pipeline for the given compute node.
  43686. *
  43687. * @param {ComputePipeline} computePipeline - The compute pipeline.
  43688. * @param {Array<BindGroup>} bindings - The bindings.
  43689. */
  43690. createComputePipeline( computePipeline, bindings ) {
  43691. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  43692. }
  43693. /**
  43694. * Prepares the state for encoding render bundles.
  43695. *
  43696. * @param {RenderContext} renderContext - The render context.
  43697. */
  43698. beginBundle( renderContext ) {
  43699. const renderContextData = this.get( renderContext );
  43700. renderContextData._currentPass = renderContextData.currentPass;
  43701. renderContextData._currentSets = renderContextData.currentSets;
  43702. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  43703. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  43704. }
  43705. /**
  43706. * After processing render bundles this method finalizes related work.
  43707. *
  43708. * @param {RenderContext} renderContext - The render context.
  43709. * @param {RenderBundle} bundle - The render bundle.
  43710. */
  43711. finishBundle( renderContext, bundle ) {
  43712. const renderContextData = this.get( renderContext );
  43713. const bundleEncoder = renderContextData.currentPass;
  43714. const bundleGPU = bundleEncoder.finish();
  43715. this.get( bundle ).bundleGPU = bundleGPU;
  43716. // restore render pass state
  43717. renderContextData.currentSets = renderContextData._currentSets;
  43718. renderContextData.currentPass = renderContextData._currentPass;
  43719. }
  43720. /**
  43721. * Adds a render bundle to the render context data.
  43722. *
  43723. * @param {RenderContext} renderContext - The render context.
  43724. * @param {RenderBundle} bundle - The render bundle to add.
  43725. */
  43726. addBundle( renderContext, bundle ) {
  43727. const renderContextData = this.get( renderContext );
  43728. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  43729. }
  43730. // bindings
  43731. /**
  43732. * Creates bindings from the given bind group definition.
  43733. *
  43734. * @param {BindGroup} bindGroup - The bind group.
  43735. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43736. * @param {Number} cacheIndex - The cache index.
  43737. * @param {Number} version - The version.
  43738. */
  43739. createBindings( bindGroup, bindings, cacheIndex, version ) {
  43740. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  43741. }
  43742. /**
  43743. * Updates the given bind group definition.
  43744. *
  43745. * @param {BindGroup} bindGroup - The bind group.
  43746. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43747. * @param {Number} cacheIndex - The cache index.
  43748. * @param {Number} version - The version.
  43749. */
  43750. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  43751. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  43752. }
  43753. /**
  43754. * Updates a buffer binding.
  43755. *
  43756. * @param {Buffer} binding - The buffer binding to update.
  43757. */
  43758. updateBinding( binding ) {
  43759. this.bindingUtils.updateBinding( binding );
  43760. }
  43761. // attributes
  43762. /**
  43763. * Creates the buffer of an indexed shader attribute.
  43764. *
  43765. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  43766. */
  43767. createIndexAttribute( attribute ) {
  43768. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43769. }
  43770. /**
  43771. * Creates the buffer of a shader attribute.
  43772. *
  43773. * @param {BufferAttribute} attribute - The buffer attribute.
  43774. */
  43775. createAttribute( attribute ) {
  43776. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43777. }
  43778. /**
  43779. * Creates the buffer of a storage attribute.
  43780. *
  43781. * @param {BufferAttribute} attribute - The buffer attribute.
  43782. */
  43783. createStorageAttribute( attribute ) {
  43784. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43785. }
  43786. /**
  43787. * Creates the buffer of an indirect storage attribute.
  43788. *
  43789. * @param {BufferAttribute} attribute - The buffer attribute.
  43790. */
  43791. createIndirectStorageAttribute( attribute ) {
  43792. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  43793. }
  43794. /**
  43795. * Updates the buffer of a shader attribute.
  43796. *
  43797. * @param {BufferAttribute} attribute - The buffer attribute to update.
  43798. */
  43799. updateAttribute( attribute ) {
  43800. this.attributeUtils.updateAttribute( attribute );
  43801. }
  43802. /**
  43803. * Destroys the buffer of a shader attribute.
  43804. *
  43805. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  43806. */
  43807. destroyAttribute( attribute ) {
  43808. this.attributeUtils.destroyAttribute( attribute );
  43809. }
  43810. // canvas
  43811. /**
  43812. * Triggers an update of the default render pass descriptor.
  43813. */
  43814. updateSize() {
  43815. this.colorBuffer = this.textureUtils.getColorBuffer();
  43816. this.defaultRenderPassdescriptor = null;
  43817. }
  43818. // utils public
  43819. /**
  43820. * Returns the maximum anisotropy texture filtering value.
  43821. *
  43822. * @return {Number} The maximum anisotropy texture filtering value.
  43823. */
  43824. getMaxAnisotropy() {
  43825. return 16;
  43826. }
  43827. /**
  43828. * Checks if the given feature is supported by the backend.
  43829. *
  43830. * @param {String} name - The feature's name.
  43831. * @return {Boolean} Whether the feature is supported or not.
  43832. */
  43833. hasFeature( name ) {
  43834. return this.device.features.has( name );
  43835. }
  43836. /**
  43837. * Copies data of the given source texture to the given destination texture.
  43838. *
  43839. * @param {Texture} srcTexture - The source texture.
  43840. * @param {Texture} dstTexture - The destination texture.
  43841. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  43842. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  43843. * @param {Number} [level=0] - The mip level to copy.
  43844. */
  43845. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  43846. let dstX = 0;
  43847. let dstY = 0;
  43848. let dstLayer = 0;
  43849. let srcX = 0;
  43850. let srcY = 0;
  43851. let srcLayer = 0;
  43852. let srcWidth = srcTexture.image.width;
  43853. let srcHeight = srcTexture.image.height;
  43854. if ( srcRegion !== null ) {
  43855. srcX = srcRegion.x;
  43856. srcY = srcRegion.y;
  43857. srcLayer = srcRegion.z || 0;
  43858. srcWidth = srcRegion.width;
  43859. srcHeight = srcRegion.height;
  43860. }
  43861. if ( dstPosition !== null ) {
  43862. dstX = dstPosition.x;
  43863. dstY = dstPosition.y;
  43864. dstLayer = dstPosition.z || 0;
  43865. }
  43866. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  43867. const sourceGPU = this.get( srcTexture ).texture;
  43868. const destinationGPU = this.get( dstTexture ).texture;
  43869. encoder.copyTextureToTexture(
  43870. {
  43871. texture: sourceGPU,
  43872. mipLevel: level,
  43873. origin: { x: srcX, y: srcY, z: srcLayer }
  43874. },
  43875. {
  43876. texture: destinationGPU,
  43877. mipLevel: level,
  43878. origin: { x: dstX, y: dstY, z: dstLayer }
  43879. },
  43880. [
  43881. srcWidth,
  43882. srcHeight,
  43883. 1
  43884. ]
  43885. );
  43886. this.device.queue.submit( [ encoder.finish() ] );
  43887. }
  43888. /**
  43889. * Copies the current bound framebuffer to the given texture.
  43890. *
  43891. * @param {Texture} texture - The destination texture.
  43892. * @param {RenderContext} renderContext - The render context.
  43893. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  43894. */
  43895. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  43896. const renderContextData = this.get( renderContext );
  43897. let sourceGPU = null;
  43898. if ( renderContext.renderTarget ) {
  43899. if ( texture.isDepthTexture ) {
  43900. sourceGPU = this.get( renderContext.depthTexture ).texture;
  43901. } else {
  43902. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  43903. }
  43904. } else {
  43905. if ( texture.isDepthTexture ) {
  43906. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  43907. } else {
  43908. sourceGPU = this.context.getCurrentTexture();
  43909. }
  43910. }
  43911. const destinationGPU = this.get( texture ).texture;
  43912. if ( sourceGPU.format !== destinationGPU.format ) {
  43913. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  43914. return;
  43915. }
  43916. let encoder;
  43917. if ( renderContextData.currentPass ) {
  43918. renderContextData.currentPass.end();
  43919. encoder = renderContextData.encoder;
  43920. } else {
  43921. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  43922. }
  43923. encoder.copyTextureToTexture(
  43924. {
  43925. texture: sourceGPU,
  43926. origin: [ rectangle.x, rectangle.y, 0 ],
  43927. },
  43928. {
  43929. texture: destinationGPU
  43930. },
  43931. [
  43932. rectangle.z,
  43933. rectangle.w
  43934. ]
  43935. );
  43936. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  43937. if ( renderContextData.currentPass ) {
  43938. const { descriptor } = renderContextData;
  43939. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  43940. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  43941. }
  43942. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  43943. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  43944. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  43945. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  43946. if ( renderContext.viewport ) {
  43947. this.updateViewport( renderContext );
  43948. }
  43949. if ( renderContext.scissor ) {
  43950. const { x, y, width, height } = renderContext.scissorValue;
  43951. renderContextData.currentPass.setScissorRect( x, y, width, height );
  43952. }
  43953. } else {
  43954. this.device.queue.submit( [ encoder.finish() ] );
  43955. }
  43956. }
  43957. }
  43958. class IESSpotLight extends SpotLight {
  43959. constructor( color, intensity, distance, angle, penumbra, decay ) {
  43960. super( color, intensity, distance, angle, penumbra, decay );
  43961. this.iesMap = null;
  43962. }
  43963. copy( source, recursive ) {
  43964. super.copy( source, recursive );
  43965. this.iesMap = source.iesMap;
  43966. return this;
  43967. }
  43968. }
  43969. /**
  43970. * This version of a node library represents a basic version
  43971. * just focusing on lights and tone mapping techniques.
  43972. *
  43973. * @private
  43974. * @augments NodeLibrary
  43975. */
  43976. class BasicNodeLibrary extends NodeLibrary {
  43977. /**
  43978. * Constructs a new basic node library.
  43979. */
  43980. constructor() {
  43981. super();
  43982. this.addLight( PointLightNode, PointLight );
  43983. this.addLight( DirectionalLightNode, DirectionalLight );
  43984. this.addLight( RectAreaLightNode, RectAreaLight );
  43985. this.addLight( SpotLightNode, SpotLight );
  43986. this.addLight( AmbientLightNode, AmbientLight );
  43987. this.addLight( HemisphereLightNode, HemisphereLight );
  43988. this.addLight( LightProbeNode, LightProbe );
  43989. this.addLight( IESSpotLightNode, IESSpotLight );
  43990. this.addToneMapping( linearToneMapping, LinearToneMapping );
  43991. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  43992. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  43993. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  43994. this.addToneMapping( agxToneMapping, AgXToneMapping );
  43995. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  43996. }
  43997. }
  43998. /**
  43999. * This alternative version of {@link WebGPURenderer} only supports node materials.
  44000. * So classes like `MeshBasicMaterial` are not compatible.
  44001. *
  44002. * @augments module:Renderer~Renderer
  44003. */
  44004. class WebGPURenderer extends Renderer {
  44005. /**
  44006. * Constructs a new WebGPU renderer.
  44007. *
  44008. * @param {Object} parameters - The configuration parameter.
  44009. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  44010. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  44011. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  44012. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  44013. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  44014. * @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
  44015. * to overwrite the default.
  44016. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses it
  44017. * WebGL 2 backend no matter if WebGPU is supported or not.
  44018. */
  44019. constructor( parameters = {} ) {
  44020. let BackendClass;
  44021. if ( parameters.forceWebGL ) {
  44022. BackendClass = WebGLBackend;
  44023. } else {
  44024. BackendClass = WebGPUBackend;
  44025. parameters.getFallback = () => {
  44026. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  44027. return new WebGLBackend( parameters );
  44028. };
  44029. }
  44030. const backend = new BackendClass( parameters );
  44031. super( backend, parameters );
  44032. /**
  44033. * The generic default value is overwritten with the
  44034. * standard node library for type mapping. Material
  44035. * mapping is not supported with this version.
  44036. *
  44037. * @type {BasicNodeLibrary}
  44038. */
  44039. this.library = new BasicNodeLibrary();
  44040. /**
  44041. * This flag can be used for type testing.
  44042. *
  44043. * @type {Boolean}
  44044. * @readonly
  44045. * @default true
  44046. */
  44047. this.isWebGPURenderer = true;
  44048. }
  44049. }
  44050. /**
  44051. * A specialized group which eanbles applications access to the
  44052. * Render Bundle API of WebGPU. The group with all its descendant nodes
  44053. * are considered as one render bundle and processed as such by
  44054. * the renderer.
  44055. *
  44056. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  44057. * With a WebGL backend, the group can technically be rendered but without
  44058. * any performance improvements.
  44059. *
  44060. * @augments Group
  44061. */
  44062. class BundleGroup extends Group {
  44063. /**
  44064. * Constructs a new bundle group.
  44065. */
  44066. constructor() {
  44067. super();
  44068. /**
  44069. * This flag can be used for type testing.
  44070. *
  44071. * @type {Boolean}
  44072. * @readonly
  44073. * @default true
  44074. */
  44075. this.isBundleGroup = true;
  44076. /**
  44077. * This property is only relevant for detecting types
  44078. * during serialization/deserialization. It should always
  44079. * match the class name.
  44080. *
  44081. * @type {String}
  44082. * @readonly
  44083. * @default 'BundleGroup'
  44084. */
  44085. this.type = 'BundleGroup';
  44086. /**
  44087. * Whether the bundle is static or not. When set to `true`, the structure
  44088. * is assumed to be static and does not change. E.g. no new objects are
  44089. * added to the group
  44090. *
  44091. * If a change is required, an update can still be forced by setting the
  44092. * `needsUpdate` flag to `true`.
  44093. *
  44094. * @type {Boolean}
  44095. * @default true
  44096. */
  44097. this.static = true;
  44098. /**
  44099. * The bundle group's version.
  44100. *
  44101. * @type {Number}
  44102. * @readonly
  44103. * @default 0
  44104. */
  44105. this.version = 0;
  44106. }
  44107. /**
  44108. * Set this property to `true` when the bundle group has changed.
  44109. *
  44110. * @type {Boolean}
  44111. * @default false
  44112. * @param {Boolean} value
  44113. */
  44114. set needsUpdate( value ) {
  44115. if ( value === true ) this.version ++;
  44116. }
  44117. }
  44118. const _material = /*@__PURE__*/ new NodeMaterial();
  44119. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  44120. /**
  44121. * This module is responsible to manage the post processing setups in apps.
  44122. * You usually create a single instance of this class and use it to define
  44123. * the output of your post processing effect chain.
  44124. * ```js
  44125. * const postProcessing = new PostProcessing( renderer );
  44126. *
  44127. * const scenePass = pass( scene, camera );
  44128. *
  44129. * postProcessing.outputNode = scenePass;
  44130. * ```
  44131. */
  44132. class PostProcessing {
  44133. /**
  44134. * Constructs a new post processing management module.
  44135. *
  44136. * @param {Renderer} renderer - A reference to the renderer.
  44137. * @param {Node<vec4>} outputNode - An optional output node.
  44138. */
  44139. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  44140. /**
  44141. * A reference to the renderer.
  44142. *
  44143. * @type {Renderer}
  44144. */
  44145. this.renderer = renderer;
  44146. /**
  44147. * A node which defines the final output of the post
  44148. * processing. This is usually the last node in a chain
  44149. * of effect nodes.
  44150. *
  44151. * @type {Node<vec4>}
  44152. */
  44153. this.outputNode = outputNode;
  44154. /**
  44155. * Whether the default output tone mapping and color
  44156. * space transformation should be enabled or not.
  44157. *
  44158. * It is enabled by default by it must be disabled when
  44159. * effects must be executed after tone mapping and color
  44160. * space conversion. A typical example is FXAA which
  44161. * requires sRGB input.
  44162. *
  44163. * When set to `false`, the app must control the output
  44164. * transformation with `RenderOutputNode`.
  44165. *
  44166. * ```js
  44167. * const outputPass = renderOutput( scenePass );
  44168. * ```
  44169. *
  44170. * @type {Boolean}
  44171. */
  44172. this.outputColorTransform = true;
  44173. /**
  44174. * Must be set to `true` when the output node changes.
  44175. *
  44176. * @type {Node<vec4>}
  44177. */
  44178. this.needsUpdate = true;
  44179. _material.name = 'PostProcessing';
  44180. }
  44181. /**
  44182. * When `PostProcessing` is used to apply post processing effects,
  44183. * the application must use this version of `render()` inside
  44184. * its animation loop (not the one from the renderer).
  44185. */
  44186. render() {
  44187. this._update();
  44188. const renderer = this.renderer;
  44189. const toneMapping = renderer.toneMapping;
  44190. const outputColorSpace = renderer.outputColorSpace;
  44191. renderer.toneMapping = NoToneMapping;
  44192. renderer.outputColorSpace = LinearSRGBColorSpace;
  44193. //
  44194. _quadMesh.render( renderer );
  44195. //
  44196. renderer.toneMapping = toneMapping;
  44197. renderer.outputColorSpace = outputColorSpace;
  44198. }
  44199. /**
  44200. * Updates the state of the module.
  44201. *
  44202. * @private
  44203. */
  44204. _update() {
  44205. if ( this.needsUpdate === true ) {
  44206. const renderer = this.renderer;
  44207. const toneMapping = renderer.toneMapping;
  44208. const outputColorSpace = renderer.outputColorSpace;
  44209. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  44210. _quadMesh.material.needsUpdate = true;
  44211. this.needsUpdate = false;
  44212. }
  44213. }
  44214. /**
  44215. * When `PostProcessing` is used to apply post processing effects,
  44216. * the application must use this version of `renderAsync()` inside
  44217. * its animation loop (not the one from the renderer).
  44218. *
  44219. * @async
  44220. * @return {Promise} A Promise that resolves when the render has been finished.
  44221. */
  44222. async renderAsync() {
  44223. this._update();
  44224. const renderer = this.renderer;
  44225. const toneMapping = renderer.toneMapping;
  44226. const outputColorSpace = renderer.outputColorSpace;
  44227. renderer.toneMapping = NoToneMapping;
  44228. renderer.outputColorSpace = LinearSRGBColorSpace;
  44229. //
  44230. await _quadMesh.renderAsync( renderer );
  44231. //
  44232. renderer.toneMapping = toneMapping;
  44233. renderer.outputColorSpace = outputColorSpace;
  44234. }
  44235. }
  44236. /**
  44237. * This special type of texture is intended for compute shaders.
  44238. * It can be used to compute the data of a texture with a compute shader.
  44239. *
  44240. * Note: This type of texture can only be used with `WebGPURenderer`
  44241. * and a WebGPU backend.
  44242. *
  44243. * @augments Texture
  44244. */
  44245. class StorageTexture extends Texture {
  44246. /**
  44247. * Constructs a new storage texture.
  44248. *
  44249. * @param {Number} [width=1] - The storage texture's width.
  44250. * @param {Number} [height=1] - The storage texture's height.
  44251. */
  44252. constructor( width = 1, height = 1 ) {
  44253. super();
  44254. /**
  44255. * The image object which just represents the texture's dimension.
  44256. *
  44257. * @type {{width: Number, height:Number}}
  44258. */
  44259. this.image = { width, height };
  44260. /**
  44261. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  44262. *
  44263. * @type {Number}
  44264. */
  44265. this.magFilter = LinearFilter;
  44266. /**
  44267. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  44268. *
  44269. * @type {Number}
  44270. */
  44271. this.minFilter = LinearFilter;
  44272. /**
  44273. * This flag can be used for type testing.
  44274. *
  44275. * @type {Boolean}
  44276. * @readonly
  44277. * @default true
  44278. */
  44279. this.isStorageTexture = true;
  44280. }
  44281. }
  44282. /**
  44283. * This special type of buffer attribute is intended for compute shaders.
  44284. * It can be used to encode draw parameters for indirect draw calls.
  44285. *
  44286. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  44287. * and a WebGPU backend.
  44288. *
  44289. * @augments StorageBufferAttribute
  44290. */
  44291. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  44292. /**
  44293. * Constructs a new storage buffer attribute.
  44294. *
  44295. * @param {Number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  44296. * The subsequent parameter is then obsolete.
  44297. * @param {Number} itemSize - The item size.
  44298. */
  44299. constructor( count, itemSize ) {
  44300. super( count, itemSize, Uint32Array );
  44301. /**
  44302. * This flag can be used for type testing.
  44303. *
  44304. * @type {Boolean}
  44305. * @readonly
  44306. * @default true
  44307. */
  44308. this.isIndirectStorageBufferAttribute = true;
  44309. }
  44310. }
  44311. /**
  44312. * A loader for loading node objects in the three.js JSON Object/Scene format.
  44313. *
  44314. * @augments Loader
  44315. */
  44316. class NodeLoader extends Loader {
  44317. /**
  44318. * Constructs a new node loader.
  44319. *
  44320. * @param {LoadingManager?} manager - A reference to a loading manager.
  44321. */
  44322. constructor( manager ) {
  44323. super( manager );
  44324. /**
  44325. * Represents a dictionary of textures.
  44326. *
  44327. * @type {Object<String,Texture>}
  44328. */
  44329. this.textures = {};
  44330. /**
  44331. * Represents a dictionary of node types.
  44332. *
  44333. * @type {Object<String,Node.constructor>}
  44334. */
  44335. this.nodes = {};
  44336. }
  44337. /**
  44338. * Loads the node definitions from the given URL.
  44339. *
  44340. * @param {String} url - The path/URL of the file to be loaded.
  44341. * @param {Function} onLoad - Will be called when load completes.
  44342. * @param {Function} onProgress - Will be called while load progresses.
  44343. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  44344. */
  44345. load( url, onLoad, onProgress, onError ) {
  44346. const loader = new FileLoader( this.manager );
  44347. loader.setPath( this.path );
  44348. loader.setRequestHeader( this.requestHeader );
  44349. loader.setWithCredentials( this.withCredentials );
  44350. loader.load( url, ( text ) => {
  44351. try {
  44352. onLoad( this.parse( JSON.parse( text ) ) );
  44353. } catch ( e ) {
  44354. if ( onError ) {
  44355. onError( e );
  44356. } else {
  44357. console.error( e );
  44358. }
  44359. this.manager.itemError( url );
  44360. }
  44361. }, onProgress, onError );
  44362. }
  44363. /**
  44364. * Parse the node dependencies for the loaded node.
  44365. *
  44366. * @param {Object} json - The JSON definition
  44367. * @return {Object<String,Node>} A dictionary with node dependencies.
  44368. */
  44369. parseNodes( json ) {
  44370. const nodes = {};
  44371. if ( json !== undefined ) {
  44372. for ( const nodeJSON of json ) {
  44373. const { uuid, type } = nodeJSON;
  44374. nodes[ uuid ] = this.createNodeFromType( type );
  44375. nodes[ uuid ].uuid = uuid;
  44376. }
  44377. const meta = { nodes, textures: this.textures };
  44378. for ( const nodeJSON of json ) {
  44379. nodeJSON.meta = meta;
  44380. const node = nodes[ nodeJSON.uuid ];
  44381. node.deserialize( nodeJSON );
  44382. delete nodeJSON.meta;
  44383. }
  44384. }
  44385. return nodes;
  44386. }
  44387. /**
  44388. * Parses the node from the given JSON.
  44389. *
  44390. * @param {Object} json - The JSON definition
  44391. * @return {Node} The parsed node.
  44392. */
  44393. parse( json ) {
  44394. const node = this.createNodeFromType( json.type );
  44395. node.uuid = json.uuid;
  44396. const nodes = this.parseNodes( json.nodes );
  44397. const meta = { nodes, textures: this.textures };
  44398. json.meta = meta;
  44399. node.deserialize( json );
  44400. delete json.meta;
  44401. return node;
  44402. }
  44403. /**
  44404. * Defines the dictionary of textures.
  44405. *
  44406. * @param {Object<String,Texture>} value - The texture library defines as `<uuid,texture>`.
  44407. * @return {NodeLoader} A reference to this loader.
  44408. */
  44409. setTextures( value ) {
  44410. this.textures = value;
  44411. return this;
  44412. }
  44413. /**
  44414. * Defines the dictionary of node types.
  44415. *
  44416. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  44417. * @return {NodeLoader} A reference to this loader.
  44418. */
  44419. setNodes( value ) {
  44420. this.nodes = value;
  44421. return this;
  44422. }
  44423. /**
  44424. * Creates a node object from the given type.
  44425. *
  44426. * @param {String} type - The node type.
  44427. * @return {Node} The created node instance.
  44428. */
  44429. createNodeFromType( type ) {
  44430. if ( this.nodes[ type ] === undefined ) {
  44431. console.error( 'THREE.NodeLoader: Node type not found:', type );
  44432. return float();
  44433. }
  44434. return nodeObject( new this.nodes[ type ]() );
  44435. }
  44436. }
  44437. /**
  44438. * A special type of material loader for loading node materials.
  44439. *
  44440. * @augments MaterialLoader
  44441. */
  44442. class NodeMaterialLoader extends MaterialLoader {
  44443. /**
  44444. * Constructs a new node material loader.
  44445. *
  44446. * @param {LoadingManager?} manager - A reference to a loading manager.
  44447. */
  44448. constructor( manager ) {
  44449. super( manager );
  44450. /**
  44451. * Represents a dictionary of node types.
  44452. *
  44453. * @type {Object<String,Node.constructor>}
  44454. */
  44455. this.nodes = {};
  44456. /**
  44457. * Represents a dictionary of node material types.
  44458. *
  44459. * @type {Object<String,NodeMaterial.constructor>}
  44460. */
  44461. this.nodeMaterials = {};
  44462. }
  44463. /**
  44464. * Parses the node material from the given JSON.
  44465. *
  44466. * @param {Object} json - The JSON definition
  44467. * @return {NodeMaterial}. The parsed material.
  44468. */
  44469. parse( json ) {
  44470. const material = super.parse( json );
  44471. const nodes = this.nodes;
  44472. const inputNodes = json.inputNodes;
  44473. for ( const property in inputNodes ) {
  44474. const uuid = inputNodes[ property ];
  44475. material[ property ] = nodes[ uuid ];
  44476. }
  44477. return material;
  44478. }
  44479. /**
  44480. * Defines the dictionary of node types.
  44481. *
  44482. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  44483. * @return {NodeLoader} A reference to this loader.
  44484. */
  44485. setNodes( value ) {
  44486. this.nodes = value;
  44487. return this;
  44488. }
  44489. /**
  44490. * Defines the dictionary of node material types.
  44491. *
  44492. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  44493. * @return {NodeLoader} A reference to this loader.
  44494. */
  44495. setNodeMaterials( value ) {
  44496. this.nodeMaterials = value;
  44497. return this;
  44498. }
  44499. /**
  44500. * Creates a node material from the given type.
  44501. *
  44502. * @param {String} type - The node material type.
  44503. * @return {Node} The created node material instance.
  44504. */
  44505. createMaterialFromType( type ) {
  44506. const materialClass = this.nodeMaterials[ type ];
  44507. if ( materialClass !== undefined ) {
  44508. return new materialClass();
  44509. }
  44510. return super.createMaterialFromType( type );
  44511. }
  44512. }
  44513. /**
  44514. * A special type of object loader for loading 3D objects using
  44515. * node materials.
  44516. *
  44517. * @augments ObjectLoader
  44518. */
  44519. class NodeObjectLoader extends ObjectLoader {
  44520. /**
  44521. * Constructs a new node object loader.
  44522. *
  44523. * @param {LoadingManager?} manager - A reference to a loading manager.
  44524. */
  44525. constructor( manager ) {
  44526. super( manager );
  44527. /**
  44528. * Represents a dictionary of node types.
  44529. *
  44530. * @type {Object<String,Node.constructor>}
  44531. */
  44532. this.nodes = {};
  44533. /**
  44534. * Represents a dictionary of node material types.
  44535. *
  44536. * @type {Object<String,NodeMaterial.constructor>}
  44537. */
  44538. this.nodeMaterials = {};
  44539. /**
  44540. * A reference for holdng the `nodes` JSON property.
  44541. *
  44542. * @private
  44543. * @type {Object?}
  44544. */
  44545. this._nodesJSON = null;
  44546. }
  44547. /**
  44548. * Defines the dictionary of node types.
  44549. *
  44550. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  44551. * @return {NodeLoader} A reference to this loader.
  44552. */
  44553. setNodes( value ) {
  44554. this.nodes = value;
  44555. return this;
  44556. }
  44557. /**
  44558. * Defines the dictionary of node material types.
  44559. *
  44560. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  44561. * @return {NodeLoader} A reference to this loader.
  44562. */
  44563. setNodeMaterials( value ) {
  44564. this.nodeMaterials = value;
  44565. return this;
  44566. }
  44567. /**
  44568. * Parses the node objects from the given JSON.
  44569. *
  44570. * @param {Object} json - The JSON definition
  44571. * @param {Function} onLoad - The onLoad callback function.
  44572. * @return {Object3D}. The parsed 3D object.
  44573. */
  44574. parse( json, onLoad ) {
  44575. this._nodesJSON = json.nodes;
  44576. const data = super.parse( json, onLoad );
  44577. this._nodesJSON = null; // dispose
  44578. return data;
  44579. }
  44580. /**
  44581. * Parses the node objects from the given JSON and textures.
  44582. *
  44583. * @param {Object} json - The JSON definition
  44584. * @param {Object<String,Texture>} textures - The texture library.
  44585. * @return {Object<String,Node>}. The parsed nodes.
  44586. */
  44587. parseNodes( json, textures ) {
  44588. if ( json !== undefined ) {
  44589. const loader = new NodeLoader();
  44590. loader.setNodes( this.nodes );
  44591. loader.setTextures( textures );
  44592. return loader.parseNodes( json );
  44593. }
  44594. return {};
  44595. }
  44596. /**
  44597. * Parses the node objects from the given JSON and textures.
  44598. *
  44599. * @param {Object} json - The JSON definition
  44600. * @param {Object<String,Texture>} textures - The texture library.
  44601. * @return {Object<String,NodeMaterial>}. The parsed materials.
  44602. */
  44603. parseMaterials( json, textures ) {
  44604. const materials = {};
  44605. if ( json !== undefined ) {
  44606. const nodes = this.parseNodes( this._nodesJSON, textures );
  44607. const loader = new NodeMaterialLoader();
  44608. loader.setTextures( textures );
  44609. loader.setNodes( nodes );
  44610. loader.setNodeMaterials( this.nodeMaterials );
  44611. for ( let i = 0, l = json.length; i < l; i ++ ) {
  44612. const data = json[ i ];
  44613. materials[ data.uuid ] = loader.parse( data );
  44614. }
  44615. }
  44616. return materials;
  44617. }
  44618. }
  44619. /**
  44620. * In earlier three.js versions, clipping was defined globally
  44621. * on the renderer or on material level. This special version of
  44622. * `THREE.Group` allows to encode the clipping state into the scene
  44623. * graph. Meaning if you create an instance of this group, all
  44624. * descendant 3D objects will be affected by the respective clipping
  44625. * planes.
  44626. *
  44627. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  44628. *
  44629. * @augments Group
  44630. */
  44631. class ClippingGroup extends Group {
  44632. /**
  44633. * Constructs a new clipping group.
  44634. */
  44635. constructor() {
  44636. super();
  44637. /**
  44638. * This flag can be used for type testing.
  44639. *
  44640. * @type {Boolean}
  44641. * @readonly
  44642. * @default true
  44643. */
  44644. this.isClippingGroup = true;
  44645. /**
  44646. * An array with clipping planes.
  44647. *
  44648. * @type {Array<Plane>}
  44649. */
  44650. this.clippingPlanes = [];
  44651. /**
  44652. * Whether clipping should be enabled or not.
  44653. *
  44654. * @type {Boolean}
  44655. * @default true
  44656. */
  44657. this.enabled = true;
  44658. /**
  44659. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  44660. *
  44661. * @type {Boolean}
  44662. * @default false
  44663. */
  44664. this.clipIntersection = false;
  44665. /**
  44666. * Whether shadows should be clipped or not.
  44667. *
  44668. * @type {Boolean}
  44669. * @default false
  44670. */
  44671. this.clipShadows = false;
  44672. }
  44673. }
  44674. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayElementNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, InstancedPointsNodeMaterial, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoopNode, LuminanceAlphaFormat, LuminanceFormat, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, PropertyNode, QuadMesh, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号