three.webgpu.nodes.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '169dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap$1 = 0;
  14. const PCFShadowMap$1 = 1;
  15. const PCFSoftShadowMap$1 = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const ConstantColorFactor = 211;
  43. const OneMinusConstantColorFactor = 212;
  44. const ConstantAlphaFactor = 213;
  45. const OneMinusConstantAlphaFactor = 214;
  46. const NeverDepth = 0;
  47. const AlwaysDepth = 1;
  48. const LessDepth = 2;
  49. const LessEqualDepth = 3;
  50. const EqualDepth = 4;
  51. const GreaterEqualDepth = 5;
  52. const GreaterDepth = 6;
  53. const NotEqualDepth = 7;
  54. const MultiplyOperation = 0;
  55. const MixOperation = 1;
  56. const AddOperation = 2;
  57. const NoToneMapping = 0;
  58. const LinearToneMapping = 1;
  59. const ReinhardToneMapping = 2;
  60. const CineonToneMapping = 3;
  61. const ACESFilmicToneMapping = 4;
  62. const CustomToneMapping = 5;
  63. const AgXToneMapping = 6;
  64. const NeutralToneMapping = 7;
  65. const AttachedBindMode = 'attached';
  66. const DetachedBindMode = 'detached';
  67. const UVMapping = 300;
  68. const CubeReflectionMapping = 301;
  69. const CubeRefractionMapping = 302;
  70. const EquirectangularReflectionMapping = 303;
  71. const EquirectangularRefractionMapping = 304;
  72. const CubeUVReflectionMapping = 306;
  73. const RepeatWrapping = 1000;
  74. const ClampToEdgeWrapping = 1001;
  75. const MirroredRepeatWrapping = 1002;
  76. const NearestFilter = 1003;
  77. const NearestMipmapNearestFilter = 1004;
  78. const NearestMipMapNearestFilter = 1004;
  79. const NearestMipmapLinearFilter = 1005;
  80. const NearestMipMapLinearFilter = 1005;
  81. const LinearFilter = 1006;
  82. const LinearMipmapNearestFilter = 1007;
  83. const LinearMipMapNearestFilter = 1007;
  84. const LinearMipmapLinearFilter = 1008;
  85. const LinearMipMapLinearFilter = 1008;
  86. const UnsignedByteType = 1009;
  87. const ByteType = 1010;
  88. const ShortType = 1011;
  89. const UnsignedShortType = 1012;
  90. const IntType = 1013;
  91. const UnsignedIntType = 1014;
  92. const FloatType = 1015;
  93. const HalfFloatType = 1016;
  94. const UnsignedShort4444Type = 1017;
  95. const UnsignedShort5551Type = 1018;
  96. const UnsignedInt248Type = 1020;
  97. const UnsignedInt5999Type = 35902;
  98. const AlphaFormat = 1021;
  99. const RGBFormat = 1022;
  100. const RGBAFormat = 1023;
  101. const LuminanceFormat = 1024;
  102. const LuminanceAlphaFormat = 1025;
  103. const DepthFormat = 1026;
  104. const DepthStencilFormat = 1027;
  105. const RedFormat = 1028;
  106. const RedIntegerFormat = 1029;
  107. const RGFormat = 1030;
  108. const RGIntegerFormat = 1031;
  109. const RGBIntegerFormat = 1032;
  110. const RGBAIntegerFormat = 1033;
  111. const RGB_S3TC_DXT1_Format = 33776;
  112. const RGBA_S3TC_DXT1_Format = 33777;
  113. const RGBA_S3TC_DXT3_Format = 33778;
  114. const RGBA_S3TC_DXT5_Format = 33779;
  115. const RGB_PVRTC_4BPPV1_Format = 35840;
  116. const RGB_PVRTC_2BPPV1_Format = 35841;
  117. const RGBA_PVRTC_4BPPV1_Format = 35842;
  118. const RGBA_PVRTC_2BPPV1_Format = 35843;
  119. const RGB_ETC1_Format = 36196;
  120. const RGB_ETC2_Format = 37492;
  121. const RGBA_ETC2_EAC_Format = 37496;
  122. const RGBA_ASTC_4x4_Format = 37808;
  123. const RGBA_ASTC_5x4_Format = 37809;
  124. const RGBA_ASTC_5x5_Format = 37810;
  125. const RGBA_ASTC_6x5_Format = 37811;
  126. const RGBA_ASTC_6x6_Format = 37812;
  127. const RGBA_ASTC_8x5_Format = 37813;
  128. const RGBA_ASTC_8x6_Format = 37814;
  129. const RGBA_ASTC_8x8_Format = 37815;
  130. const RGBA_ASTC_10x5_Format = 37816;
  131. const RGBA_ASTC_10x6_Format = 37817;
  132. const RGBA_ASTC_10x8_Format = 37818;
  133. const RGBA_ASTC_10x10_Format = 37819;
  134. const RGBA_ASTC_12x10_Format = 37820;
  135. const RGBA_ASTC_12x12_Format = 37821;
  136. const RGBA_BPTC_Format = 36492;
  137. const RGB_BPTC_SIGNED_Format = 36494;
  138. const RGB_BPTC_UNSIGNED_Format = 36495;
  139. const RED_RGTC1_Format = 36283;
  140. const SIGNED_RED_RGTC1_Format = 36284;
  141. const RED_GREEN_RGTC2_Format = 36285;
  142. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  143. const LoopOnce = 2200;
  144. const LoopRepeat = 2201;
  145. const LoopPingPong = 2202;
  146. const InterpolateDiscrete = 2300;
  147. const InterpolateLinear = 2301;
  148. const InterpolateSmooth = 2302;
  149. const ZeroCurvatureEnding = 2400;
  150. const ZeroSlopeEnding = 2401;
  151. const WrapAroundEnding = 2402;
  152. const NormalAnimationBlendMode = 2500;
  153. const AdditiveAnimationBlendMode = 2501;
  154. const TrianglesDrawMode = 0;
  155. const TriangleStripDrawMode = 1;
  156. const TriangleFanDrawMode = 2;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const RGBDepthPacking = 3202;
  160. const RGDepthPacking = 3203;
  161. const TangentSpaceNormalMap = 0;
  162. const ObjectSpaceNormalMap = 1;
  163. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  164. const NoColorSpace = '';
  165. const SRGBColorSpace = 'srgb';
  166. const LinearSRGBColorSpace = 'srgb-linear';
  167. const DisplayP3ColorSpace = 'display-p3';
  168. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  169. const LinearTransfer = 'linear';
  170. const SRGBTransfer = 'srgb';
  171. const Rec709Primaries = 'rec709';
  172. const P3Primaries = 'p3';
  173. const ZeroStencilOp = 0;
  174. const KeepStencilOp = 7680;
  175. const ReplaceStencilOp = 7681;
  176. const IncrementStencilOp = 7682;
  177. const DecrementStencilOp = 7683;
  178. const IncrementWrapStencilOp = 34055;
  179. const DecrementWrapStencilOp = 34056;
  180. const InvertStencilOp = 5386;
  181. const NeverStencilFunc = 512;
  182. const LessStencilFunc = 513;
  183. const EqualStencilFunc = 514;
  184. const LessEqualStencilFunc = 515;
  185. const GreaterStencilFunc = 516;
  186. const NotEqualStencilFunc = 517;
  187. const GreaterEqualStencilFunc = 518;
  188. const AlwaysStencilFunc = 519;
  189. const NeverCompare = 512;
  190. const LessCompare = 513;
  191. const EqualCompare = 514;
  192. const LessEqualCompare = 515;
  193. const GreaterCompare = 516;
  194. const NotEqualCompare = 517;
  195. const GreaterEqualCompare = 518;
  196. const AlwaysCompare = 519;
  197. const StaticDrawUsage = 35044;
  198. const DynamicDrawUsage = 35048;
  199. const StreamDrawUsage = 35040;
  200. const StaticReadUsage = 35045;
  201. const DynamicReadUsage = 35049;
  202. const StreamReadUsage = 35041;
  203. const StaticCopyUsage = 35046;
  204. const DynamicCopyUsage = 35050;
  205. const StreamCopyUsage = 35042;
  206. const GLSL1 = '100';
  207. const GLSL3 = '300 es';
  208. const WebGLCoordinateSystem = 2000;
  209. const WebGPUCoordinateSystem = 2001;
  210. /**
  211. * https://github.com/mrdoob/eventdispatcher.js/
  212. */
  213. class EventDispatcher {
  214. addEventListener( type, listener ) {
  215. if ( this._listeners === undefined ) this._listeners = {};
  216. const listeners = this._listeners;
  217. if ( listeners[ type ] === undefined ) {
  218. listeners[ type ] = [];
  219. }
  220. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  221. listeners[ type ].push( listener );
  222. }
  223. }
  224. hasEventListener( type, listener ) {
  225. if ( this._listeners === undefined ) return false;
  226. const listeners = this._listeners;
  227. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  228. }
  229. removeEventListener( type, listener ) {
  230. if ( this._listeners === undefined ) return;
  231. const listeners = this._listeners;
  232. const listenerArray = listeners[ type ];
  233. if ( listenerArray !== undefined ) {
  234. const index = listenerArray.indexOf( listener );
  235. if ( index !== - 1 ) {
  236. listenerArray.splice( index, 1 );
  237. }
  238. }
  239. }
  240. dispatchEvent( event ) {
  241. if ( this._listeners === undefined ) return;
  242. const listeners = this._listeners;
  243. const listenerArray = listeners[ event.type ];
  244. if ( listenerArray !== undefined ) {
  245. event.target = this;
  246. // Make a copy, in case listeners are removed while iterating.
  247. const array = listenerArray.slice( 0 );
  248. for ( let i = 0, l = array.length; i < l; i ++ ) {
  249. array[ i ].call( this, event );
  250. }
  251. event.target = null;
  252. }
  253. }
  254. }
  255. const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];
  256. let _seed = 1234567;
  257. const DEG2RAD = Math.PI / 180;
  258. const RAD2DEG = 180 / Math.PI;
  259. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  260. function generateUUID() {
  261. const d0 = Math.random() * 0xffffffff | 0;
  262. const d1 = Math.random() * 0xffffffff | 0;
  263. const d2 = Math.random() * 0xffffffff | 0;
  264. const d3 = Math.random() * 0xffffffff | 0;
  265. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  266. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  267. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  268. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  269. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  270. return uuid.toLowerCase();
  271. }
  272. function clamp$1( value, min, max ) {
  273. return Math.max( min, Math.min( max, value ) );
  274. }
  275. // compute euclidean modulo of m % n
  276. // https://en.wikipedia.org/wiki/Modulo_operation
  277. function euclideanModulo( n, m ) {
  278. return ( ( n % m ) + m ) % m;
  279. }
  280. // Linear mapping from range <a1, a2> to range <b1, b2>
  281. function mapLinear( x, a1, a2, b1, b2 ) {
  282. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  283. }
  284. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  285. function inverseLerp( x, y, value ) {
  286. if ( x !== y ) {
  287. return ( value - x ) / ( y - x );
  288. } else {
  289. return 0;
  290. }
  291. }
  292. // https://en.wikipedia.org/wiki/Linear_interpolation
  293. function lerp( x, y, t ) {
  294. return ( 1 - t ) * x + t * y;
  295. }
  296. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  297. function damp( x, y, lambda, dt ) {
  298. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  299. }
  300. // https://www.desmos.com/calculator/vcsjnyz7x4
  301. function pingpong( x, length = 1 ) {
  302. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  303. }
  304. // http://en.wikipedia.org/wiki/Smoothstep
  305. function smoothstep$1( x, min, max ) {
  306. if ( x <= min ) return 0;
  307. if ( x >= max ) return 1;
  308. x = ( x - min ) / ( max - min );
  309. return x * x * ( 3 - 2 * x );
  310. }
  311. function smootherstep( x, min, max ) {
  312. if ( x <= min ) return 0;
  313. if ( x >= max ) return 1;
  314. x = ( x - min ) / ( max - min );
  315. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  316. }
  317. // Random integer from <low, high> interval
  318. function randInt( low, high ) {
  319. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  320. }
  321. // Random float from <low, high> interval
  322. function randFloat( low, high ) {
  323. return low + Math.random() * ( high - low );
  324. }
  325. // Random float from <-range/2, range/2> interval
  326. function randFloatSpread( range ) {
  327. return range * ( 0.5 - Math.random() );
  328. }
  329. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  330. function seededRandom( s ) {
  331. if ( s !== undefined ) _seed = s;
  332. // Mulberry32 generator
  333. let t = _seed += 0x6D2B79F5;
  334. t = Math.imul( t ^ t >>> 15, t | 1 );
  335. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  336. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  337. }
  338. function degToRad( degrees ) {
  339. return degrees * DEG2RAD;
  340. }
  341. function radToDeg( radians ) {
  342. return radians * RAD2DEG;
  343. }
  344. function isPowerOfTwo( value ) {
  345. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  346. }
  347. function ceilPowerOfTwo( value ) {
  348. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  349. }
  350. function floorPowerOfTwo( value ) {
  351. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  352. }
  353. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  354. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  355. // rotations are applied to the axes in the order specified by 'order'
  356. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  357. // angles are in radians
  358. const cos = Math.cos;
  359. const sin = Math.sin;
  360. const c2 = cos( b / 2 );
  361. const s2 = sin( b / 2 );
  362. const c13 = cos( ( a + c ) / 2 );
  363. const s13 = sin( ( a + c ) / 2 );
  364. const c1_3 = cos( ( a - c ) / 2 );
  365. const s1_3 = sin( ( a - c ) / 2 );
  366. const c3_1 = cos( ( c - a ) / 2 );
  367. const s3_1 = sin( ( c - a ) / 2 );
  368. switch ( order ) {
  369. case 'XYX':
  370. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  371. break;
  372. case 'YZY':
  373. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  374. break;
  375. case 'ZXZ':
  376. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  377. break;
  378. case 'XZX':
  379. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  380. break;
  381. case 'YXY':
  382. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  383. break;
  384. case 'ZYZ':
  385. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  386. break;
  387. default:
  388. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  389. }
  390. }
  391. function denormalize( value, array ) {
  392. switch ( array.constructor ) {
  393. case Float32Array:
  394. return value;
  395. case Uint32Array:
  396. return value / 4294967295.0;
  397. case Uint16Array:
  398. return value / 65535.0;
  399. case Uint8Array:
  400. return value / 255.0;
  401. case Int32Array:
  402. return Math.max( value / 2147483647.0, - 1.0 );
  403. case Int16Array:
  404. return Math.max( value / 32767.0, - 1.0 );
  405. case Int8Array:
  406. return Math.max( value / 127.0, - 1.0 );
  407. default:
  408. throw new Error( 'Invalid component type.' );
  409. }
  410. }
  411. function normalize$1( value, array ) {
  412. switch ( array.constructor ) {
  413. case Float32Array:
  414. return value;
  415. case Uint32Array:
  416. return Math.round( value * 4294967295.0 );
  417. case Uint16Array:
  418. return Math.round( value * 65535.0 );
  419. case Uint8Array:
  420. return Math.round( value * 255.0 );
  421. case Int32Array:
  422. return Math.round( value * 2147483647.0 );
  423. case Int16Array:
  424. return Math.round( value * 32767.0 );
  425. case Int8Array:
  426. return Math.round( value * 127.0 );
  427. default:
  428. throw new Error( 'Invalid component type.' );
  429. }
  430. }
  431. const MathUtils = {
  432. DEG2RAD: DEG2RAD,
  433. RAD2DEG: RAD2DEG,
  434. generateUUID: generateUUID,
  435. clamp: clamp$1,
  436. euclideanModulo: euclideanModulo,
  437. mapLinear: mapLinear,
  438. inverseLerp: inverseLerp,
  439. lerp: lerp,
  440. damp: damp,
  441. pingpong: pingpong,
  442. smoothstep: smoothstep$1,
  443. smootherstep: smootherstep,
  444. randInt: randInt,
  445. randFloat: randFloat,
  446. randFloatSpread: randFloatSpread,
  447. seededRandom: seededRandom,
  448. degToRad: degToRad,
  449. radToDeg: radToDeg,
  450. isPowerOfTwo: isPowerOfTwo,
  451. ceilPowerOfTwo: ceilPowerOfTwo,
  452. floorPowerOfTwo: floorPowerOfTwo,
  453. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  454. normalize: normalize$1,
  455. denormalize: denormalize
  456. };
  457. class Vector2 {
  458. constructor( x = 0, y = 0 ) {
  459. Vector2.prototype.isVector2 = true;
  460. this.x = x;
  461. this.y = y;
  462. }
  463. get width() {
  464. return this.x;
  465. }
  466. set width( value ) {
  467. this.x = value;
  468. }
  469. get height() {
  470. return this.y;
  471. }
  472. set height( value ) {
  473. this.y = value;
  474. }
  475. set( x, y ) {
  476. this.x = x;
  477. this.y = y;
  478. return this;
  479. }
  480. setScalar( scalar ) {
  481. this.x = scalar;
  482. this.y = scalar;
  483. return this;
  484. }
  485. setX( x ) {
  486. this.x = x;
  487. return this;
  488. }
  489. setY( y ) {
  490. this.y = y;
  491. return this;
  492. }
  493. setComponent( index, value ) {
  494. switch ( index ) {
  495. case 0: this.x = value; break;
  496. case 1: this.y = value; break;
  497. default: throw new Error( 'index is out of range: ' + index );
  498. }
  499. return this;
  500. }
  501. getComponent( index ) {
  502. switch ( index ) {
  503. case 0: return this.x;
  504. case 1: return this.y;
  505. default: throw new Error( 'index is out of range: ' + index );
  506. }
  507. }
  508. clone() {
  509. return new this.constructor( this.x, this.y );
  510. }
  511. copy( v ) {
  512. this.x = v.x;
  513. this.y = v.y;
  514. return this;
  515. }
  516. add( v ) {
  517. this.x += v.x;
  518. this.y += v.y;
  519. return this;
  520. }
  521. addScalar( s ) {
  522. this.x += s;
  523. this.y += s;
  524. return this;
  525. }
  526. addVectors( a, b ) {
  527. this.x = a.x + b.x;
  528. this.y = a.y + b.y;
  529. return this;
  530. }
  531. addScaledVector( v, s ) {
  532. this.x += v.x * s;
  533. this.y += v.y * s;
  534. return this;
  535. }
  536. sub( v ) {
  537. this.x -= v.x;
  538. this.y -= v.y;
  539. return this;
  540. }
  541. subScalar( s ) {
  542. this.x -= s;
  543. this.y -= s;
  544. return this;
  545. }
  546. subVectors( a, b ) {
  547. this.x = a.x - b.x;
  548. this.y = a.y - b.y;
  549. return this;
  550. }
  551. multiply( v ) {
  552. this.x *= v.x;
  553. this.y *= v.y;
  554. return this;
  555. }
  556. multiplyScalar( scalar ) {
  557. this.x *= scalar;
  558. this.y *= scalar;
  559. return this;
  560. }
  561. divide( v ) {
  562. this.x /= v.x;
  563. this.y /= v.y;
  564. return this;
  565. }
  566. divideScalar( scalar ) {
  567. return this.multiplyScalar( 1 / scalar );
  568. }
  569. applyMatrix3( m ) {
  570. const x = this.x, y = this.y;
  571. const e = m.elements;
  572. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  573. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  574. return this;
  575. }
  576. min( v ) {
  577. this.x = Math.min( this.x, v.x );
  578. this.y = Math.min( this.y, v.y );
  579. return this;
  580. }
  581. max( v ) {
  582. this.x = Math.max( this.x, v.x );
  583. this.y = Math.max( this.y, v.y );
  584. return this;
  585. }
  586. clamp( min, max ) {
  587. // assumes min < max, componentwise
  588. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  589. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  590. return this;
  591. }
  592. clampScalar( minVal, maxVal ) {
  593. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  594. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  595. return this;
  596. }
  597. clampLength( min, max ) {
  598. const length = this.length();
  599. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  600. }
  601. floor() {
  602. this.x = Math.floor( this.x );
  603. this.y = Math.floor( this.y );
  604. return this;
  605. }
  606. ceil() {
  607. this.x = Math.ceil( this.x );
  608. this.y = Math.ceil( this.y );
  609. return this;
  610. }
  611. round() {
  612. this.x = Math.round( this.x );
  613. this.y = Math.round( this.y );
  614. return this;
  615. }
  616. roundToZero() {
  617. this.x = Math.trunc( this.x );
  618. this.y = Math.trunc( this.y );
  619. return this;
  620. }
  621. negate() {
  622. this.x = - this.x;
  623. this.y = - this.y;
  624. return this;
  625. }
  626. dot( v ) {
  627. return this.x * v.x + this.y * v.y;
  628. }
  629. cross( v ) {
  630. return this.x * v.y - this.y * v.x;
  631. }
  632. lengthSq() {
  633. return this.x * this.x + this.y * this.y;
  634. }
  635. length() {
  636. return Math.sqrt( this.x * this.x + this.y * this.y );
  637. }
  638. manhattanLength() {
  639. return Math.abs( this.x ) + Math.abs( this.y );
  640. }
  641. normalize() {
  642. return this.divideScalar( this.length() || 1 );
  643. }
  644. angle() {
  645. // computes the angle in radians with respect to the positive x-axis
  646. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  647. return angle;
  648. }
  649. angleTo( v ) {
  650. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  651. if ( denominator === 0 ) return Math.PI / 2;
  652. const theta = this.dot( v ) / denominator;
  653. // clamp, to handle numerical problems
  654. return Math.acos( clamp$1( theta, - 1, 1 ) );
  655. }
  656. distanceTo( v ) {
  657. return Math.sqrt( this.distanceToSquared( v ) );
  658. }
  659. distanceToSquared( v ) {
  660. const dx = this.x - v.x, dy = this.y - v.y;
  661. return dx * dx + dy * dy;
  662. }
  663. manhattanDistanceTo( v ) {
  664. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  665. }
  666. setLength( length ) {
  667. return this.normalize().multiplyScalar( length );
  668. }
  669. lerp( v, alpha ) {
  670. this.x += ( v.x - this.x ) * alpha;
  671. this.y += ( v.y - this.y ) * alpha;
  672. return this;
  673. }
  674. lerpVectors( v1, v2, alpha ) {
  675. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  676. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  677. return this;
  678. }
  679. equals( v ) {
  680. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  681. }
  682. fromArray( array, offset = 0 ) {
  683. this.x = array[ offset ];
  684. this.y = array[ offset + 1 ];
  685. return this;
  686. }
  687. toArray( array = [], offset = 0 ) {
  688. array[ offset ] = this.x;
  689. array[ offset + 1 ] = this.y;
  690. return array;
  691. }
  692. fromBufferAttribute( attribute, index ) {
  693. this.x = attribute.getX( index );
  694. this.y = attribute.getY( index );
  695. return this;
  696. }
  697. rotateAround( center, angle ) {
  698. const c = Math.cos( angle ), s = Math.sin( angle );
  699. const x = this.x - center.x;
  700. const y = this.y - center.y;
  701. this.x = x * c - y * s + center.x;
  702. this.y = x * s + y * c + center.y;
  703. return this;
  704. }
  705. random() {
  706. this.x = Math.random();
  707. this.y = Math.random();
  708. return this;
  709. }
  710. *[ Symbol.iterator ]() {
  711. yield this.x;
  712. yield this.y;
  713. }
  714. }
  715. class Matrix3 {
  716. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  717. Matrix3.prototype.isMatrix3 = true;
  718. this.elements = [
  719. 1, 0, 0,
  720. 0, 1, 0,
  721. 0, 0, 1
  722. ];
  723. if ( n11 !== undefined ) {
  724. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  725. }
  726. }
  727. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  728. const te = this.elements;
  729. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  730. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  731. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  732. return this;
  733. }
  734. identity() {
  735. this.set(
  736. 1, 0, 0,
  737. 0, 1, 0,
  738. 0, 0, 1
  739. );
  740. return this;
  741. }
  742. copy( m ) {
  743. const te = this.elements;
  744. const me = m.elements;
  745. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  746. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  747. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  748. return this;
  749. }
  750. extractBasis( xAxis, yAxis, zAxis ) {
  751. xAxis.setFromMatrix3Column( this, 0 );
  752. yAxis.setFromMatrix3Column( this, 1 );
  753. zAxis.setFromMatrix3Column( this, 2 );
  754. return this;
  755. }
  756. setFromMatrix4( m ) {
  757. const me = m.elements;
  758. this.set(
  759. me[ 0 ], me[ 4 ], me[ 8 ],
  760. me[ 1 ], me[ 5 ], me[ 9 ],
  761. me[ 2 ], me[ 6 ], me[ 10 ]
  762. );
  763. return this;
  764. }
  765. multiply( m ) {
  766. return this.multiplyMatrices( this, m );
  767. }
  768. premultiply( m ) {
  769. return this.multiplyMatrices( m, this );
  770. }
  771. multiplyMatrices( a, b ) {
  772. const ae = a.elements;
  773. const be = b.elements;
  774. const te = this.elements;
  775. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  776. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  777. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  778. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  779. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  780. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  781. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  782. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  783. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  784. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  785. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  786. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  787. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  788. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  789. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  790. return this;
  791. }
  792. multiplyScalar( s ) {
  793. const te = this.elements;
  794. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  795. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  796. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  797. return this;
  798. }
  799. determinant() {
  800. const te = this.elements;
  801. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  802. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  803. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  804. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  805. }
  806. invert() {
  807. const te = this.elements,
  808. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  809. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  810. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  811. t11 = n33 * n22 - n32 * n23,
  812. t12 = n32 * n13 - n33 * n12,
  813. t13 = n23 * n12 - n22 * n13,
  814. det = n11 * t11 + n21 * t12 + n31 * t13;
  815. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  816. const detInv = 1 / det;
  817. te[ 0 ] = t11 * detInv;
  818. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  819. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  820. te[ 3 ] = t12 * detInv;
  821. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  822. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  823. te[ 6 ] = t13 * detInv;
  824. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  825. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  826. return this;
  827. }
  828. transpose() {
  829. let tmp;
  830. const m = this.elements;
  831. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  832. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  833. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  834. return this;
  835. }
  836. getNormalMatrix( matrix4 ) {
  837. return this.setFromMatrix4( matrix4 ).invert().transpose();
  838. }
  839. transposeIntoArray( r ) {
  840. const m = this.elements;
  841. r[ 0 ] = m[ 0 ];
  842. r[ 1 ] = m[ 3 ];
  843. r[ 2 ] = m[ 6 ];
  844. r[ 3 ] = m[ 1 ];
  845. r[ 4 ] = m[ 4 ];
  846. r[ 5 ] = m[ 7 ];
  847. r[ 6 ] = m[ 2 ];
  848. r[ 7 ] = m[ 5 ];
  849. r[ 8 ] = m[ 8 ];
  850. return this;
  851. }
  852. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  853. const c = Math.cos( rotation );
  854. const s = Math.sin( rotation );
  855. this.set(
  856. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  857. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  858. 0, 0, 1
  859. );
  860. return this;
  861. }
  862. //
  863. scale( sx, sy ) {
  864. this.premultiply( _m3.makeScale( sx, sy ) );
  865. return this;
  866. }
  867. rotate( theta ) {
  868. this.premultiply( _m3.makeRotation( - theta ) );
  869. return this;
  870. }
  871. translate( tx, ty ) {
  872. this.premultiply( _m3.makeTranslation( tx, ty ) );
  873. return this;
  874. }
  875. // for 2D Transforms
  876. makeTranslation( x, y ) {
  877. if ( x.isVector2 ) {
  878. this.set(
  879. 1, 0, x.x,
  880. 0, 1, x.y,
  881. 0, 0, 1
  882. );
  883. } else {
  884. this.set(
  885. 1, 0, x,
  886. 0, 1, y,
  887. 0, 0, 1
  888. );
  889. }
  890. return this;
  891. }
  892. makeRotation( theta ) {
  893. // counterclockwise
  894. const c = Math.cos( theta );
  895. const s = Math.sin( theta );
  896. this.set(
  897. c, - s, 0,
  898. s, c, 0,
  899. 0, 0, 1
  900. );
  901. return this;
  902. }
  903. makeScale( x, y ) {
  904. this.set(
  905. x, 0, 0,
  906. 0, y, 0,
  907. 0, 0, 1
  908. );
  909. return this;
  910. }
  911. //
  912. equals( matrix ) {
  913. const te = this.elements;
  914. const me = matrix.elements;
  915. for ( let i = 0; i < 9; i ++ ) {
  916. if ( te[ i ] !== me[ i ] ) return false;
  917. }
  918. return true;
  919. }
  920. fromArray( array, offset = 0 ) {
  921. for ( let i = 0; i < 9; i ++ ) {
  922. this.elements[ i ] = array[ i + offset ];
  923. }
  924. return this;
  925. }
  926. toArray( array = [], offset = 0 ) {
  927. const te = this.elements;
  928. array[ offset ] = te[ 0 ];
  929. array[ offset + 1 ] = te[ 1 ];
  930. array[ offset + 2 ] = te[ 2 ];
  931. array[ offset + 3 ] = te[ 3 ];
  932. array[ offset + 4 ] = te[ 4 ];
  933. array[ offset + 5 ] = te[ 5 ];
  934. array[ offset + 6 ] = te[ 6 ];
  935. array[ offset + 7 ] = te[ 7 ];
  936. array[ offset + 8 ] = te[ 8 ];
  937. return array;
  938. }
  939. clone() {
  940. return new this.constructor().fromArray( this.elements );
  941. }
  942. }
  943. const _m3 = /*@__PURE__*/ new Matrix3();
  944. function arrayNeedsUint32$1( array ) {
  945. // assumes larger values usually on last
  946. for ( let i = array.length - 1; i >= 0; -- i ) {
  947. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  948. }
  949. return false;
  950. }
  951. const TYPED_ARRAYS = {
  952. Int8Array: Int8Array,
  953. Uint8Array: Uint8Array,
  954. Uint8ClampedArray: Uint8ClampedArray,
  955. Int16Array: Int16Array,
  956. Uint16Array: Uint16Array,
  957. Int32Array: Int32Array,
  958. Uint32Array: Uint32Array,
  959. Float32Array: Float32Array,
  960. Float64Array: Float64Array
  961. };
  962. function getTypedArray( type, buffer ) {
  963. return new TYPED_ARRAYS[ type ]( buffer );
  964. }
  965. function createElementNS( name ) {
  966. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  967. }
  968. function createCanvasElement() {
  969. const canvas = createElementNS( 'canvas' );
  970. canvas.style.display = 'block';
  971. return canvas;
  972. }
  973. const _cache$2 = {};
  974. function warnOnce( message ) {
  975. if ( message in _cache$2 ) return;
  976. _cache$2[ message ] = true;
  977. console.warn( message );
  978. }
  979. /**
  980. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  981. * or clipping. Based on W3C specifications for sRGB and Display P3,
  982. * and ICC specifications for the D50 connection space. Values in/out
  983. * are _linear_ sRGB and _linear_ Display P3.
  984. *
  985. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  986. *
  987. * Reference:
  988. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  989. */
  990. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  991. 0.8224621, 0.177538, 0.0,
  992. 0.0331941, 0.9668058, 0.0,
  993. 0.0170827, 0.0723974, 0.9105199,
  994. );
  995. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  996. 1.2249401, - 0.2249404, 0.0,
  997. - 0.0420569, 1.0420571, 0.0,
  998. - 0.0196376, - 0.0786361, 1.0982735
  999. );
  1000. /**
  1001. * Defines supported color spaces by transfer function and primaries,
  1002. * and provides conversions to/from the Linear-sRGB reference space.
  1003. */
  1004. const COLOR_SPACES = {
  1005. [ LinearSRGBColorSpace ]: {
  1006. transfer: LinearTransfer,
  1007. primaries: Rec709Primaries,
  1008. luminanceCoefficients: [ 0.2126, 0.7152, 0.0722 ],
  1009. toReference: ( color ) => color,
  1010. fromReference: ( color ) => color,
  1011. },
  1012. [ SRGBColorSpace ]: {
  1013. transfer: SRGBTransfer,
  1014. primaries: Rec709Primaries,
  1015. luminanceCoefficients: [ 0.2126, 0.7152, 0.0722 ],
  1016. toReference: ( color ) => color.convertSRGBToLinear(),
  1017. fromReference: ( color ) => color.convertLinearToSRGB(),
  1018. },
  1019. [ LinearDisplayP3ColorSpace ]: {
  1020. transfer: LinearTransfer,
  1021. primaries: P3Primaries,
  1022. luminanceCoefficients: [ 0.2289, 0.6917, 0.0793 ],
  1023. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1024. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1025. },
  1026. [ DisplayP3ColorSpace ]: {
  1027. transfer: SRGBTransfer,
  1028. primaries: P3Primaries,
  1029. luminanceCoefficients: [ 0.2289, 0.6917, 0.0793 ],
  1030. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1031. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1032. },
  1033. };
  1034. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1035. const ColorManagement = {
  1036. enabled: true,
  1037. _workingColorSpace: LinearSRGBColorSpace,
  1038. get workingColorSpace() {
  1039. return this._workingColorSpace;
  1040. },
  1041. set workingColorSpace( colorSpace ) {
  1042. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1043. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1044. }
  1045. this._workingColorSpace = colorSpace;
  1046. },
  1047. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1048. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1049. return color;
  1050. }
  1051. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1052. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1053. return targetFromReference( sourceToReference( color ) );
  1054. },
  1055. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1056. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1057. },
  1058. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1059. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1060. },
  1061. getPrimaries: function ( colorSpace ) {
  1062. return COLOR_SPACES[ colorSpace ].primaries;
  1063. },
  1064. getTransfer: function ( colorSpace ) {
  1065. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1066. return COLOR_SPACES[ colorSpace ].transfer;
  1067. },
  1068. getLuminanceCoefficients: function ( target, colorSpace = this._workingColorSpace ) {
  1069. return target.fromArray( COLOR_SPACES[ colorSpace ].luminanceCoefficients );
  1070. },
  1071. };
  1072. function SRGBToLinear( c ) {
  1073. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1074. }
  1075. function LinearToSRGB( c ) {
  1076. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1077. }
  1078. let _canvas;
  1079. class ImageUtils {
  1080. static getDataURL( image ) {
  1081. if ( /^data:/i.test( image.src ) ) {
  1082. return image.src;
  1083. }
  1084. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1085. return image.src;
  1086. }
  1087. let canvas;
  1088. if ( image instanceof HTMLCanvasElement ) {
  1089. canvas = image;
  1090. } else {
  1091. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1092. _canvas.width = image.width;
  1093. _canvas.height = image.height;
  1094. const context = _canvas.getContext( '2d' );
  1095. if ( image instanceof ImageData ) {
  1096. context.putImageData( image, 0, 0 );
  1097. } else {
  1098. context.drawImage( image, 0, 0, image.width, image.height );
  1099. }
  1100. canvas = _canvas;
  1101. }
  1102. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1103. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1104. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1105. } else {
  1106. return canvas.toDataURL( 'image/png' );
  1107. }
  1108. }
  1109. static sRGBToLinear( image ) {
  1110. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1111. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1112. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1113. const canvas = createElementNS( 'canvas' );
  1114. canvas.width = image.width;
  1115. canvas.height = image.height;
  1116. const context = canvas.getContext( '2d' );
  1117. context.drawImage( image, 0, 0, image.width, image.height );
  1118. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1119. const data = imageData.data;
  1120. for ( let i = 0; i < data.length; i ++ ) {
  1121. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1122. }
  1123. context.putImageData( imageData, 0, 0 );
  1124. return canvas;
  1125. } else if ( image.data ) {
  1126. const data = image.data.slice( 0 );
  1127. for ( let i = 0; i < data.length; i ++ ) {
  1128. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1129. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1130. } else {
  1131. // assuming float
  1132. data[ i ] = SRGBToLinear( data[ i ] );
  1133. }
  1134. }
  1135. return {
  1136. data: data,
  1137. width: image.width,
  1138. height: image.height
  1139. };
  1140. } else {
  1141. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1142. return image;
  1143. }
  1144. }
  1145. }
  1146. let _sourceId = 0;
  1147. class Source {
  1148. constructor( data = null ) {
  1149. this.isSource = true;
  1150. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1151. this.uuid = generateUUID();
  1152. this.data = data;
  1153. this.dataReady = true;
  1154. this.version = 0;
  1155. }
  1156. set needsUpdate( value ) {
  1157. if ( value === true ) this.version ++;
  1158. }
  1159. toJSON( meta ) {
  1160. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1161. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1162. return meta.images[ this.uuid ];
  1163. }
  1164. const output = {
  1165. uuid: this.uuid,
  1166. url: ''
  1167. };
  1168. const data = this.data;
  1169. if ( data !== null ) {
  1170. let url;
  1171. if ( Array.isArray( data ) ) {
  1172. // cube texture
  1173. url = [];
  1174. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1175. if ( data[ i ].isDataTexture ) {
  1176. url.push( serializeImage( data[ i ].image ) );
  1177. } else {
  1178. url.push( serializeImage( data[ i ] ) );
  1179. }
  1180. }
  1181. } else {
  1182. // texture
  1183. url = serializeImage( data );
  1184. }
  1185. output.url = url;
  1186. }
  1187. if ( ! isRootObject ) {
  1188. meta.images[ this.uuid ] = output;
  1189. }
  1190. return output;
  1191. }
  1192. }
  1193. function serializeImage( image ) {
  1194. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1195. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1196. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1197. // default images
  1198. return ImageUtils.getDataURL( image );
  1199. } else {
  1200. if ( image.data ) {
  1201. // images of DataTexture
  1202. return {
  1203. data: Array.from( image.data ),
  1204. width: image.width,
  1205. height: image.height,
  1206. type: image.data.constructor.name
  1207. };
  1208. } else {
  1209. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1210. return {};
  1211. }
  1212. }
  1213. }
  1214. let _textureId = 0;
  1215. class Texture extends EventDispatcher {
  1216. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {
  1217. super();
  1218. this.isTexture = true;
  1219. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1220. this.uuid = generateUUID();
  1221. this.name = '';
  1222. this.source = new Source( image );
  1223. this.mipmaps = [];
  1224. this.mapping = mapping;
  1225. this.channel = 0;
  1226. this.wrapS = wrapS;
  1227. this.wrapT = wrapT;
  1228. this.magFilter = magFilter;
  1229. this.minFilter = minFilter;
  1230. this.anisotropy = anisotropy;
  1231. this.format = format;
  1232. this.internalFormat = null;
  1233. this.type = type;
  1234. this.offset = new Vector2( 0, 0 );
  1235. this.repeat = new Vector2( 1, 1 );
  1236. this.center = new Vector2( 0, 0 );
  1237. this.rotation = 0;
  1238. this.matrixAutoUpdate = true;
  1239. this.matrix = new Matrix3();
  1240. this.generateMipmaps = true;
  1241. this.premultiplyAlpha = false;
  1242. this.flipY = true;
  1243. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1244. this.colorSpace = colorSpace;
  1245. this.userData = {};
  1246. this.version = 0;
  1247. this.onUpdate = null;
  1248. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1249. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1250. }
  1251. get image() {
  1252. return this.source.data;
  1253. }
  1254. set image( value = null ) {
  1255. this.source.data = value;
  1256. }
  1257. updateMatrix() {
  1258. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1259. }
  1260. clone() {
  1261. return new this.constructor().copy( this );
  1262. }
  1263. copy( source ) {
  1264. this.name = source.name;
  1265. this.source = source.source;
  1266. this.mipmaps = source.mipmaps.slice( 0 );
  1267. this.mapping = source.mapping;
  1268. this.channel = source.channel;
  1269. this.wrapS = source.wrapS;
  1270. this.wrapT = source.wrapT;
  1271. this.magFilter = source.magFilter;
  1272. this.minFilter = source.minFilter;
  1273. this.anisotropy = source.anisotropy;
  1274. this.format = source.format;
  1275. this.internalFormat = source.internalFormat;
  1276. this.type = source.type;
  1277. this.offset.copy( source.offset );
  1278. this.repeat.copy( source.repeat );
  1279. this.center.copy( source.center );
  1280. this.rotation = source.rotation;
  1281. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1282. this.matrix.copy( source.matrix );
  1283. this.generateMipmaps = source.generateMipmaps;
  1284. this.premultiplyAlpha = source.premultiplyAlpha;
  1285. this.flipY = source.flipY;
  1286. this.unpackAlignment = source.unpackAlignment;
  1287. this.colorSpace = source.colorSpace;
  1288. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1289. this.needsUpdate = true;
  1290. return this;
  1291. }
  1292. toJSON( meta ) {
  1293. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1294. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1295. return meta.textures[ this.uuid ];
  1296. }
  1297. const output = {
  1298. metadata: {
  1299. version: 4.6,
  1300. type: 'Texture',
  1301. generator: 'Texture.toJSON'
  1302. },
  1303. uuid: this.uuid,
  1304. name: this.name,
  1305. image: this.source.toJSON( meta ).uuid,
  1306. mapping: this.mapping,
  1307. channel: this.channel,
  1308. repeat: [ this.repeat.x, this.repeat.y ],
  1309. offset: [ this.offset.x, this.offset.y ],
  1310. center: [ this.center.x, this.center.y ],
  1311. rotation: this.rotation,
  1312. wrap: [ this.wrapS, this.wrapT ],
  1313. format: this.format,
  1314. internalFormat: this.internalFormat,
  1315. type: this.type,
  1316. colorSpace: this.colorSpace,
  1317. minFilter: this.minFilter,
  1318. magFilter: this.magFilter,
  1319. anisotropy: this.anisotropy,
  1320. flipY: this.flipY,
  1321. generateMipmaps: this.generateMipmaps,
  1322. premultiplyAlpha: this.premultiplyAlpha,
  1323. unpackAlignment: this.unpackAlignment
  1324. };
  1325. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1326. if ( ! isRootObject ) {
  1327. meta.textures[ this.uuid ] = output;
  1328. }
  1329. return output;
  1330. }
  1331. dispose() {
  1332. this.dispatchEvent( { type: 'dispose' } );
  1333. }
  1334. transformUv( uv ) {
  1335. if ( this.mapping !== UVMapping ) return uv;
  1336. uv.applyMatrix3( this.matrix );
  1337. if ( uv.x < 0 || uv.x > 1 ) {
  1338. switch ( this.wrapS ) {
  1339. case RepeatWrapping:
  1340. uv.x = uv.x - Math.floor( uv.x );
  1341. break;
  1342. case ClampToEdgeWrapping:
  1343. uv.x = uv.x < 0 ? 0 : 1;
  1344. break;
  1345. case MirroredRepeatWrapping:
  1346. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1347. uv.x = Math.ceil( uv.x ) - uv.x;
  1348. } else {
  1349. uv.x = uv.x - Math.floor( uv.x );
  1350. }
  1351. break;
  1352. }
  1353. }
  1354. if ( uv.y < 0 || uv.y > 1 ) {
  1355. switch ( this.wrapT ) {
  1356. case RepeatWrapping:
  1357. uv.y = uv.y - Math.floor( uv.y );
  1358. break;
  1359. case ClampToEdgeWrapping:
  1360. uv.y = uv.y < 0 ? 0 : 1;
  1361. break;
  1362. case MirroredRepeatWrapping:
  1363. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1364. uv.y = Math.ceil( uv.y ) - uv.y;
  1365. } else {
  1366. uv.y = uv.y - Math.floor( uv.y );
  1367. }
  1368. break;
  1369. }
  1370. }
  1371. if ( this.flipY ) {
  1372. uv.y = 1 - uv.y;
  1373. }
  1374. return uv;
  1375. }
  1376. set needsUpdate( value ) {
  1377. if ( value === true ) {
  1378. this.version ++;
  1379. this.source.needsUpdate = true;
  1380. }
  1381. }
  1382. set needsPMREMUpdate( value ) {
  1383. if ( value === true ) {
  1384. this.pmremVersion ++;
  1385. }
  1386. }
  1387. }
  1388. Texture.DEFAULT_IMAGE = null;
  1389. Texture.DEFAULT_MAPPING = UVMapping;
  1390. Texture.DEFAULT_ANISOTROPY = 1;
  1391. class Vector4 {
  1392. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1393. Vector4.prototype.isVector4 = true;
  1394. this.x = x;
  1395. this.y = y;
  1396. this.z = z;
  1397. this.w = w;
  1398. }
  1399. get width() {
  1400. return this.z;
  1401. }
  1402. set width( value ) {
  1403. this.z = value;
  1404. }
  1405. get height() {
  1406. return this.w;
  1407. }
  1408. set height( value ) {
  1409. this.w = value;
  1410. }
  1411. set( x, y, z, w ) {
  1412. this.x = x;
  1413. this.y = y;
  1414. this.z = z;
  1415. this.w = w;
  1416. return this;
  1417. }
  1418. setScalar( scalar ) {
  1419. this.x = scalar;
  1420. this.y = scalar;
  1421. this.z = scalar;
  1422. this.w = scalar;
  1423. return this;
  1424. }
  1425. setX( x ) {
  1426. this.x = x;
  1427. return this;
  1428. }
  1429. setY( y ) {
  1430. this.y = y;
  1431. return this;
  1432. }
  1433. setZ( z ) {
  1434. this.z = z;
  1435. return this;
  1436. }
  1437. setW( w ) {
  1438. this.w = w;
  1439. return this;
  1440. }
  1441. setComponent( index, value ) {
  1442. switch ( index ) {
  1443. case 0: this.x = value; break;
  1444. case 1: this.y = value; break;
  1445. case 2: this.z = value; break;
  1446. case 3: this.w = value; break;
  1447. default: throw new Error( 'index is out of range: ' + index );
  1448. }
  1449. return this;
  1450. }
  1451. getComponent( index ) {
  1452. switch ( index ) {
  1453. case 0: return this.x;
  1454. case 1: return this.y;
  1455. case 2: return this.z;
  1456. case 3: return this.w;
  1457. default: throw new Error( 'index is out of range: ' + index );
  1458. }
  1459. }
  1460. clone() {
  1461. return new this.constructor( this.x, this.y, this.z, this.w );
  1462. }
  1463. copy( v ) {
  1464. this.x = v.x;
  1465. this.y = v.y;
  1466. this.z = v.z;
  1467. this.w = ( v.w !== undefined ) ? v.w : 1;
  1468. return this;
  1469. }
  1470. add( v ) {
  1471. this.x += v.x;
  1472. this.y += v.y;
  1473. this.z += v.z;
  1474. this.w += v.w;
  1475. return this;
  1476. }
  1477. addScalar( s ) {
  1478. this.x += s;
  1479. this.y += s;
  1480. this.z += s;
  1481. this.w += s;
  1482. return this;
  1483. }
  1484. addVectors( a, b ) {
  1485. this.x = a.x + b.x;
  1486. this.y = a.y + b.y;
  1487. this.z = a.z + b.z;
  1488. this.w = a.w + b.w;
  1489. return this;
  1490. }
  1491. addScaledVector( v, s ) {
  1492. this.x += v.x * s;
  1493. this.y += v.y * s;
  1494. this.z += v.z * s;
  1495. this.w += v.w * s;
  1496. return this;
  1497. }
  1498. sub( v ) {
  1499. this.x -= v.x;
  1500. this.y -= v.y;
  1501. this.z -= v.z;
  1502. this.w -= v.w;
  1503. return this;
  1504. }
  1505. subScalar( s ) {
  1506. this.x -= s;
  1507. this.y -= s;
  1508. this.z -= s;
  1509. this.w -= s;
  1510. return this;
  1511. }
  1512. subVectors( a, b ) {
  1513. this.x = a.x - b.x;
  1514. this.y = a.y - b.y;
  1515. this.z = a.z - b.z;
  1516. this.w = a.w - b.w;
  1517. return this;
  1518. }
  1519. multiply( v ) {
  1520. this.x *= v.x;
  1521. this.y *= v.y;
  1522. this.z *= v.z;
  1523. this.w *= v.w;
  1524. return this;
  1525. }
  1526. multiplyScalar( scalar ) {
  1527. this.x *= scalar;
  1528. this.y *= scalar;
  1529. this.z *= scalar;
  1530. this.w *= scalar;
  1531. return this;
  1532. }
  1533. applyMatrix4( m ) {
  1534. const x = this.x, y = this.y, z = this.z, w = this.w;
  1535. const e = m.elements;
  1536. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1537. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1538. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1539. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1540. return this;
  1541. }
  1542. divideScalar( scalar ) {
  1543. return this.multiplyScalar( 1 / scalar );
  1544. }
  1545. setAxisAngleFromQuaternion( q ) {
  1546. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1547. // q is assumed to be normalized
  1548. this.w = 2 * Math.acos( q.w );
  1549. const s = Math.sqrt( 1 - q.w * q.w );
  1550. if ( s < 0.0001 ) {
  1551. this.x = 1;
  1552. this.y = 0;
  1553. this.z = 0;
  1554. } else {
  1555. this.x = q.x / s;
  1556. this.y = q.y / s;
  1557. this.z = q.z / s;
  1558. }
  1559. return this;
  1560. }
  1561. setAxisAngleFromRotationMatrix( m ) {
  1562. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1563. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1564. let angle, x, y, z; // variables for result
  1565. const epsilon = 0.01, // margin to allow for rounding errors
  1566. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1567. te = m.elements,
  1568. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1569. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1570. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1571. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1572. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1573. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1574. // singularity found
  1575. // first check for identity matrix which must have +1 for all terms
  1576. // in leading diagonal and zero in other terms
  1577. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1578. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1579. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1580. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1581. // this singularity is identity matrix so angle = 0
  1582. this.set( 1, 0, 0, 0 );
  1583. return this; // zero angle, arbitrary axis
  1584. }
  1585. // otherwise this singularity is angle = 180
  1586. angle = Math.PI;
  1587. const xx = ( m11 + 1 ) / 2;
  1588. const yy = ( m22 + 1 ) / 2;
  1589. const zz = ( m33 + 1 ) / 2;
  1590. const xy = ( m12 + m21 ) / 4;
  1591. const xz = ( m13 + m31 ) / 4;
  1592. const yz = ( m23 + m32 ) / 4;
  1593. if ( ( xx > yy ) && ( xx > zz ) ) {
  1594. // m11 is the largest diagonal term
  1595. if ( xx < epsilon ) {
  1596. x = 0;
  1597. y = 0.707106781;
  1598. z = 0.707106781;
  1599. } else {
  1600. x = Math.sqrt( xx );
  1601. y = xy / x;
  1602. z = xz / x;
  1603. }
  1604. } else if ( yy > zz ) {
  1605. // m22 is the largest diagonal term
  1606. if ( yy < epsilon ) {
  1607. x = 0.707106781;
  1608. y = 0;
  1609. z = 0.707106781;
  1610. } else {
  1611. y = Math.sqrt( yy );
  1612. x = xy / y;
  1613. z = yz / y;
  1614. }
  1615. } else {
  1616. // m33 is the largest diagonal term so base result on this
  1617. if ( zz < epsilon ) {
  1618. x = 0.707106781;
  1619. y = 0.707106781;
  1620. z = 0;
  1621. } else {
  1622. z = Math.sqrt( zz );
  1623. x = xz / z;
  1624. y = yz / z;
  1625. }
  1626. }
  1627. this.set( x, y, z, angle );
  1628. return this; // return 180 deg rotation
  1629. }
  1630. // as we have reached here there are no singularities so we can handle normally
  1631. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1632. ( m13 - m31 ) * ( m13 - m31 ) +
  1633. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1634. if ( Math.abs( s ) < 0.001 ) s = 1;
  1635. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1636. // caught by singularity test above, but I've left it in just in case
  1637. this.x = ( m32 - m23 ) / s;
  1638. this.y = ( m13 - m31 ) / s;
  1639. this.z = ( m21 - m12 ) / s;
  1640. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1641. return this;
  1642. }
  1643. setFromMatrixPosition( m ) {
  1644. const e = m.elements;
  1645. this.x = e[ 12 ];
  1646. this.y = e[ 13 ];
  1647. this.z = e[ 14 ];
  1648. this.w = e[ 15 ];
  1649. return this;
  1650. }
  1651. min( v ) {
  1652. this.x = Math.min( this.x, v.x );
  1653. this.y = Math.min( this.y, v.y );
  1654. this.z = Math.min( this.z, v.z );
  1655. this.w = Math.min( this.w, v.w );
  1656. return this;
  1657. }
  1658. max( v ) {
  1659. this.x = Math.max( this.x, v.x );
  1660. this.y = Math.max( this.y, v.y );
  1661. this.z = Math.max( this.z, v.z );
  1662. this.w = Math.max( this.w, v.w );
  1663. return this;
  1664. }
  1665. clamp( min, max ) {
  1666. // assumes min < max, componentwise
  1667. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1668. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1669. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1670. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1671. return this;
  1672. }
  1673. clampScalar( minVal, maxVal ) {
  1674. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1675. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1676. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1677. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1678. return this;
  1679. }
  1680. clampLength( min, max ) {
  1681. const length = this.length();
  1682. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1683. }
  1684. floor() {
  1685. this.x = Math.floor( this.x );
  1686. this.y = Math.floor( this.y );
  1687. this.z = Math.floor( this.z );
  1688. this.w = Math.floor( this.w );
  1689. return this;
  1690. }
  1691. ceil() {
  1692. this.x = Math.ceil( this.x );
  1693. this.y = Math.ceil( this.y );
  1694. this.z = Math.ceil( this.z );
  1695. this.w = Math.ceil( this.w );
  1696. return this;
  1697. }
  1698. round() {
  1699. this.x = Math.round( this.x );
  1700. this.y = Math.round( this.y );
  1701. this.z = Math.round( this.z );
  1702. this.w = Math.round( this.w );
  1703. return this;
  1704. }
  1705. roundToZero() {
  1706. this.x = Math.trunc( this.x );
  1707. this.y = Math.trunc( this.y );
  1708. this.z = Math.trunc( this.z );
  1709. this.w = Math.trunc( this.w );
  1710. return this;
  1711. }
  1712. negate() {
  1713. this.x = - this.x;
  1714. this.y = - this.y;
  1715. this.z = - this.z;
  1716. this.w = - this.w;
  1717. return this;
  1718. }
  1719. dot( v ) {
  1720. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1721. }
  1722. lengthSq() {
  1723. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1724. }
  1725. length() {
  1726. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1727. }
  1728. manhattanLength() {
  1729. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1730. }
  1731. normalize() {
  1732. return this.divideScalar( this.length() || 1 );
  1733. }
  1734. setLength( length ) {
  1735. return this.normalize().multiplyScalar( length );
  1736. }
  1737. lerp( v, alpha ) {
  1738. this.x += ( v.x - this.x ) * alpha;
  1739. this.y += ( v.y - this.y ) * alpha;
  1740. this.z += ( v.z - this.z ) * alpha;
  1741. this.w += ( v.w - this.w ) * alpha;
  1742. return this;
  1743. }
  1744. lerpVectors( v1, v2, alpha ) {
  1745. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1746. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1747. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1748. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1749. return this;
  1750. }
  1751. equals( v ) {
  1752. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1753. }
  1754. fromArray( array, offset = 0 ) {
  1755. this.x = array[ offset ];
  1756. this.y = array[ offset + 1 ];
  1757. this.z = array[ offset + 2 ];
  1758. this.w = array[ offset + 3 ];
  1759. return this;
  1760. }
  1761. toArray( array = [], offset = 0 ) {
  1762. array[ offset ] = this.x;
  1763. array[ offset + 1 ] = this.y;
  1764. array[ offset + 2 ] = this.z;
  1765. array[ offset + 3 ] = this.w;
  1766. return array;
  1767. }
  1768. fromBufferAttribute( attribute, index ) {
  1769. this.x = attribute.getX( index );
  1770. this.y = attribute.getY( index );
  1771. this.z = attribute.getZ( index );
  1772. this.w = attribute.getW( index );
  1773. return this;
  1774. }
  1775. random() {
  1776. this.x = Math.random();
  1777. this.y = Math.random();
  1778. this.z = Math.random();
  1779. this.w = Math.random();
  1780. return this;
  1781. }
  1782. *[ Symbol.iterator ]() {
  1783. yield this.x;
  1784. yield this.y;
  1785. yield this.z;
  1786. yield this.w;
  1787. }
  1788. }
  1789. /*
  1790. In options, we can specify:
  1791. * Texture parameters for an auto-generated target texture
  1792. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1793. */
  1794. class RenderTarget extends EventDispatcher {
  1795. constructor( width = 1, height = 1, options = {} ) {
  1796. super();
  1797. this.isRenderTarget = true;
  1798. this.width = width;
  1799. this.height = height;
  1800. this.depth = 1;
  1801. this.scissor = new Vector4( 0, 0, width, height );
  1802. this.scissorTest = false;
  1803. this.viewport = new Vector4( 0, 0, width, height );
  1804. const image = { width: width, height: height, depth: 1 };
  1805. options = Object.assign( {
  1806. generateMipmaps: false,
  1807. internalFormat: null,
  1808. minFilter: LinearFilter,
  1809. depthBuffer: true,
  1810. stencilBuffer: false,
  1811. resolveDepthBuffer: true,
  1812. resolveStencilBuffer: true,
  1813. depthTexture: null,
  1814. samples: 0,
  1815. count: 1
  1816. }, options );
  1817. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1818. texture.flipY = false;
  1819. texture.generateMipmaps = options.generateMipmaps;
  1820. texture.internalFormat = options.internalFormat;
  1821. this.textures = [];
  1822. const count = options.count;
  1823. for ( let i = 0; i < count; i ++ ) {
  1824. this.textures[ i ] = texture.clone();
  1825. this.textures[ i ].isRenderTargetTexture = true;
  1826. }
  1827. this.depthBuffer = options.depthBuffer;
  1828. this.stencilBuffer = options.stencilBuffer;
  1829. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1830. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1831. this.depthTexture = options.depthTexture;
  1832. this.samples = options.samples;
  1833. }
  1834. get texture() {
  1835. return this.textures[ 0 ];
  1836. }
  1837. set texture( value ) {
  1838. this.textures[ 0 ] = value;
  1839. }
  1840. setSize( width, height, depth = 1 ) {
  1841. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1842. this.width = width;
  1843. this.height = height;
  1844. this.depth = depth;
  1845. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1846. this.textures[ i ].image.width = width;
  1847. this.textures[ i ].image.height = height;
  1848. this.textures[ i ].image.depth = depth;
  1849. }
  1850. this.dispose();
  1851. }
  1852. this.viewport.set( 0, 0, width, height );
  1853. this.scissor.set( 0, 0, width, height );
  1854. }
  1855. clone() {
  1856. return new this.constructor().copy( this );
  1857. }
  1858. copy( source ) {
  1859. this.width = source.width;
  1860. this.height = source.height;
  1861. this.depth = source.depth;
  1862. this.scissor.copy( source.scissor );
  1863. this.scissorTest = source.scissorTest;
  1864. this.viewport.copy( source.viewport );
  1865. this.textures.length = 0;
  1866. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1867. this.textures[ i ] = source.textures[ i ].clone();
  1868. this.textures[ i ].isRenderTargetTexture = true;
  1869. }
  1870. // ensure image object is not shared, see #20328
  1871. const image = Object.assign( {}, source.texture.image );
  1872. this.texture.source = new Source( image );
  1873. this.depthBuffer = source.depthBuffer;
  1874. this.stencilBuffer = source.stencilBuffer;
  1875. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1876. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1877. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1878. this.samples = source.samples;
  1879. return this;
  1880. }
  1881. dispose() {
  1882. this.dispatchEvent( { type: 'dispose' } );
  1883. }
  1884. }
  1885. class WebGLRenderTarget extends RenderTarget {
  1886. constructor( width = 1, height = 1, options = {} ) {
  1887. super( width, height, options );
  1888. this.isWebGLRenderTarget = true;
  1889. }
  1890. }
  1891. class DataArrayTexture extends Texture {
  1892. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1893. super( null );
  1894. this.isDataArrayTexture = true;
  1895. this.image = { data, width, height, depth };
  1896. this.magFilter = NearestFilter;
  1897. this.minFilter = NearestFilter;
  1898. this.wrapR = ClampToEdgeWrapping;
  1899. this.generateMipmaps = false;
  1900. this.flipY = false;
  1901. this.unpackAlignment = 1;
  1902. this.layerUpdates = new Set();
  1903. }
  1904. addLayerUpdate( layerIndex ) {
  1905. this.layerUpdates.add( layerIndex );
  1906. }
  1907. clearLayerUpdates() {
  1908. this.layerUpdates.clear();
  1909. }
  1910. }
  1911. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1912. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1913. super( width, height, options );
  1914. this.isWebGLArrayRenderTarget = true;
  1915. this.depth = depth;
  1916. this.texture = new DataArrayTexture( null, width, height, depth );
  1917. this.texture.isRenderTargetTexture = true;
  1918. }
  1919. }
  1920. class Data3DTexture extends Texture {
  1921. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1922. // We're going to add .setXXX() methods for setting properties later.
  1923. // Users can still set in DataTexture3D directly.
  1924. //
  1925. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1926. // texture.anisotropy = 16;
  1927. //
  1928. // See #14839
  1929. super( null );
  1930. this.isData3DTexture = true;
  1931. this.image = { data, width, height, depth };
  1932. this.magFilter = NearestFilter;
  1933. this.minFilter = NearestFilter;
  1934. this.wrapR = ClampToEdgeWrapping;
  1935. this.generateMipmaps = false;
  1936. this.flipY = false;
  1937. this.unpackAlignment = 1;
  1938. }
  1939. }
  1940. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1941. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1942. super( width, height, options );
  1943. this.isWebGL3DRenderTarget = true;
  1944. this.depth = depth;
  1945. this.texture = new Data3DTexture( null, width, height, depth );
  1946. this.texture.isRenderTargetTexture = true;
  1947. }
  1948. }
  1949. class Quaternion {
  1950. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1951. this.isQuaternion = true;
  1952. this._x = x;
  1953. this._y = y;
  1954. this._z = z;
  1955. this._w = w;
  1956. }
  1957. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1958. // fuzz-free, array-based Quaternion SLERP operation
  1959. let x0 = src0[ srcOffset0 + 0 ],
  1960. y0 = src0[ srcOffset0 + 1 ],
  1961. z0 = src0[ srcOffset0 + 2 ],
  1962. w0 = src0[ srcOffset0 + 3 ];
  1963. const x1 = src1[ srcOffset1 + 0 ],
  1964. y1 = src1[ srcOffset1 + 1 ],
  1965. z1 = src1[ srcOffset1 + 2 ],
  1966. w1 = src1[ srcOffset1 + 3 ];
  1967. if ( t === 0 ) {
  1968. dst[ dstOffset + 0 ] = x0;
  1969. dst[ dstOffset + 1 ] = y0;
  1970. dst[ dstOffset + 2 ] = z0;
  1971. dst[ dstOffset + 3 ] = w0;
  1972. return;
  1973. }
  1974. if ( t === 1 ) {
  1975. dst[ dstOffset + 0 ] = x1;
  1976. dst[ dstOffset + 1 ] = y1;
  1977. dst[ dstOffset + 2 ] = z1;
  1978. dst[ dstOffset + 3 ] = w1;
  1979. return;
  1980. }
  1981. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1982. let s = 1 - t;
  1983. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1984. dir = ( cos >= 0 ? 1 : - 1 ),
  1985. sqrSin = 1 - cos * cos;
  1986. // Skip the Slerp for tiny steps to avoid numeric problems:
  1987. if ( sqrSin > Number.EPSILON ) {
  1988. const sin = Math.sqrt( sqrSin ),
  1989. len = Math.atan2( sin, cos * dir );
  1990. s = Math.sin( s * len ) / sin;
  1991. t = Math.sin( t * len ) / sin;
  1992. }
  1993. const tDir = t * dir;
  1994. x0 = x0 * s + x1 * tDir;
  1995. y0 = y0 * s + y1 * tDir;
  1996. z0 = z0 * s + z1 * tDir;
  1997. w0 = w0 * s + w1 * tDir;
  1998. // Normalize in case we just did a lerp:
  1999. if ( s === 1 - t ) {
  2000. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2001. x0 *= f;
  2002. y0 *= f;
  2003. z0 *= f;
  2004. w0 *= f;
  2005. }
  2006. }
  2007. dst[ dstOffset ] = x0;
  2008. dst[ dstOffset + 1 ] = y0;
  2009. dst[ dstOffset + 2 ] = z0;
  2010. dst[ dstOffset + 3 ] = w0;
  2011. }
  2012. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2013. const x0 = src0[ srcOffset0 ];
  2014. const y0 = src0[ srcOffset0 + 1 ];
  2015. const z0 = src0[ srcOffset0 + 2 ];
  2016. const w0 = src0[ srcOffset0 + 3 ];
  2017. const x1 = src1[ srcOffset1 ];
  2018. const y1 = src1[ srcOffset1 + 1 ];
  2019. const z1 = src1[ srcOffset1 + 2 ];
  2020. const w1 = src1[ srcOffset1 + 3 ];
  2021. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2022. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2023. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2024. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2025. return dst;
  2026. }
  2027. get x() {
  2028. return this._x;
  2029. }
  2030. set x( value ) {
  2031. this._x = value;
  2032. this._onChangeCallback();
  2033. }
  2034. get y() {
  2035. return this._y;
  2036. }
  2037. set y( value ) {
  2038. this._y = value;
  2039. this._onChangeCallback();
  2040. }
  2041. get z() {
  2042. return this._z;
  2043. }
  2044. set z( value ) {
  2045. this._z = value;
  2046. this._onChangeCallback();
  2047. }
  2048. get w() {
  2049. return this._w;
  2050. }
  2051. set w( value ) {
  2052. this._w = value;
  2053. this._onChangeCallback();
  2054. }
  2055. set( x, y, z, w ) {
  2056. this._x = x;
  2057. this._y = y;
  2058. this._z = z;
  2059. this._w = w;
  2060. this._onChangeCallback();
  2061. return this;
  2062. }
  2063. clone() {
  2064. return new this.constructor( this._x, this._y, this._z, this._w );
  2065. }
  2066. copy( quaternion ) {
  2067. this._x = quaternion.x;
  2068. this._y = quaternion.y;
  2069. this._z = quaternion.z;
  2070. this._w = quaternion.w;
  2071. this._onChangeCallback();
  2072. return this;
  2073. }
  2074. setFromEuler( euler, update = true ) {
  2075. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2076. // http://www.mathworks.com/matlabcentral/fileexchange/
  2077. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2078. // content/SpinCalc.m
  2079. const cos = Math.cos;
  2080. const sin = Math.sin;
  2081. const c1 = cos( x / 2 );
  2082. const c2 = cos( y / 2 );
  2083. const c3 = cos( z / 2 );
  2084. const s1 = sin( x / 2 );
  2085. const s2 = sin( y / 2 );
  2086. const s3 = sin( z / 2 );
  2087. switch ( order ) {
  2088. case 'XYZ':
  2089. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2090. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2091. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2092. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2093. break;
  2094. case 'YXZ':
  2095. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2096. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2097. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2098. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2099. break;
  2100. case 'ZXY':
  2101. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2102. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2103. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2104. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2105. break;
  2106. case 'ZYX':
  2107. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2108. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2109. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2110. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2111. break;
  2112. case 'YZX':
  2113. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2114. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2115. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2116. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2117. break;
  2118. case 'XZY':
  2119. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2120. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2121. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2122. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2123. break;
  2124. default:
  2125. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2126. }
  2127. if ( update === true ) this._onChangeCallback();
  2128. return this;
  2129. }
  2130. setFromAxisAngle( axis, angle ) {
  2131. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2132. // assumes axis is normalized
  2133. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2134. this._x = axis.x * s;
  2135. this._y = axis.y * s;
  2136. this._z = axis.z * s;
  2137. this._w = Math.cos( halfAngle );
  2138. this._onChangeCallback();
  2139. return this;
  2140. }
  2141. setFromRotationMatrix( m ) {
  2142. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2143. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2144. const te = m.elements,
  2145. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2146. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2147. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2148. trace = m11 + m22 + m33;
  2149. if ( trace > 0 ) {
  2150. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2151. this._w = 0.25 / s;
  2152. this._x = ( m32 - m23 ) * s;
  2153. this._y = ( m13 - m31 ) * s;
  2154. this._z = ( m21 - m12 ) * s;
  2155. } else if ( m11 > m22 && m11 > m33 ) {
  2156. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2157. this._w = ( m32 - m23 ) / s;
  2158. this._x = 0.25 * s;
  2159. this._y = ( m12 + m21 ) / s;
  2160. this._z = ( m13 + m31 ) / s;
  2161. } else if ( m22 > m33 ) {
  2162. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2163. this._w = ( m13 - m31 ) / s;
  2164. this._x = ( m12 + m21 ) / s;
  2165. this._y = 0.25 * s;
  2166. this._z = ( m23 + m32 ) / s;
  2167. } else {
  2168. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2169. this._w = ( m21 - m12 ) / s;
  2170. this._x = ( m13 + m31 ) / s;
  2171. this._y = ( m23 + m32 ) / s;
  2172. this._z = 0.25 * s;
  2173. }
  2174. this._onChangeCallback();
  2175. return this;
  2176. }
  2177. setFromUnitVectors( vFrom, vTo ) {
  2178. // assumes direction vectors vFrom and vTo are normalized
  2179. let r = vFrom.dot( vTo ) + 1;
  2180. if ( r < Number.EPSILON ) {
  2181. // vFrom and vTo point in opposite directions
  2182. r = 0;
  2183. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2184. this._x = - vFrom.y;
  2185. this._y = vFrom.x;
  2186. this._z = 0;
  2187. this._w = r;
  2188. } else {
  2189. this._x = 0;
  2190. this._y = - vFrom.z;
  2191. this._z = vFrom.y;
  2192. this._w = r;
  2193. }
  2194. } else {
  2195. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2196. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2197. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2198. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2199. this._w = r;
  2200. }
  2201. return this.normalize();
  2202. }
  2203. angleTo( q ) {
  2204. return 2 * Math.acos( Math.abs( clamp$1( this.dot( q ), - 1, 1 ) ) );
  2205. }
  2206. rotateTowards( q, step ) {
  2207. const angle = this.angleTo( q );
  2208. if ( angle === 0 ) return this;
  2209. const t = Math.min( 1, step / angle );
  2210. this.slerp( q, t );
  2211. return this;
  2212. }
  2213. identity() {
  2214. return this.set( 0, 0, 0, 1 );
  2215. }
  2216. invert() {
  2217. // quaternion is assumed to have unit length
  2218. return this.conjugate();
  2219. }
  2220. conjugate() {
  2221. this._x *= - 1;
  2222. this._y *= - 1;
  2223. this._z *= - 1;
  2224. this._onChangeCallback();
  2225. return this;
  2226. }
  2227. dot( v ) {
  2228. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2229. }
  2230. lengthSq() {
  2231. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2232. }
  2233. length() {
  2234. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2235. }
  2236. normalize() {
  2237. let l = this.length();
  2238. if ( l === 0 ) {
  2239. this._x = 0;
  2240. this._y = 0;
  2241. this._z = 0;
  2242. this._w = 1;
  2243. } else {
  2244. l = 1 / l;
  2245. this._x = this._x * l;
  2246. this._y = this._y * l;
  2247. this._z = this._z * l;
  2248. this._w = this._w * l;
  2249. }
  2250. this._onChangeCallback();
  2251. return this;
  2252. }
  2253. multiply( q ) {
  2254. return this.multiplyQuaternions( this, q );
  2255. }
  2256. premultiply( q ) {
  2257. return this.multiplyQuaternions( q, this );
  2258. }
  2259. multiplyQuaternions( a, b ) {
  2260. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2261. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2262. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2263. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2264. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2265. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2266. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2267. this._onChangeCallback();
  2268. return this;
  2269. }
  2270. slerp( qb, t ) {
  2271. if ( t === 0 ) return this;
  2272. if ( t === 1 ) return this.copy( qb );
  2273. const x = this._x, y = this._y, z = this._z, w = this._w;
  2274. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2275. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2276. if ( cosHalfTheta < 0 ) {
  2277. this._w = - qb._w;
  2278. this._x = - qb._x;
  2279. this._y = - qb._y;
  2280. this._z = - qb._z;
  2281. cosHalfTheta = - cosHalfTheta;
  2282. } else {
  2283. this.copy( qb );
  2284. }
  2285. if ( cosHalfTheta >= 1.0 ) {
  2286. this._w = w;
  2287. this._x = x;
  2288. this._y = y;
  2289. this._z = z;
  2290. return this;
  2291. }
  2292. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2293. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2294. const s = 1 - t;
  2295. this._w = s * w + t * this._w;
  2296. this._x = s * x + t * this._x;
  2297. this._y = s * y + t * this._y;
  2298. this._z = s * z + t * this._z;
  2299. this.normalize(); // normalize calls _onChangeCallback()
  2300. return this;
  2301. }
  2302. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2303. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2304. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2305. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2306. this._w = ( w * ratioA + this._w * ratioB );
  2307. this._x = ( x * ratioA + this._x * ratioB );
  2308. this._y = ( y * ratioA + this._y * ratioB );
  2309. this._z = ( z * ratioA + this._z * ratioB );
  2310. this._onChangeCallback();
  2311. return this;
  2312. }
  2313. slerpQuaternions( qa, qb, t ) {
  2314. return this.copy( qa ).slerp( qb, t );
  2315. }
  2316. random() {
  2317. // sets this quaternion to a uniform random unit quaternnion
  2318. // Ken Shoemake
  2319. // Uniform random rotations
  2320. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2321. const theta1 = 2 * Math.PI * Math.random();
  2322. const theta2 = 2 * Math.PI * Math.random();
  2323. const x0 = Math.random();
  2324. const r1 = Math.sqrt( 1 - x0 );
  2325. const r2 = Math.sqrt( x0 );
  2326. return this.set(
  2327. r1 * Math.sin( theta1 ),
  2328. r1 * Math.cos( theta1 ),
  2329. r2 * Math.sin( theta2 ),
  2330. r2 * Math.cos( theta2 ),
  2331. );
  2332. }
  2333. equals( quaternion ) {
  2334. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2335. }
  2336. fromArray( array, offset = 0 ) {
  2337. this._x = array[ offset ];
  2338. this._y = array[ offset + 1 ];
  2339. this._z = array[ offset + 2 ];
  2340. this._w = array[ offset + 3 ];
  2341. this._onChangeCallback();
  2342. return this;
  2343. }
  2344. toArray( array = [], offset = 0 ) {
  2345. array[ offset ] = this._x;
  2346. array[ offset + 1 ] = this._y;
  2347. array[ offset + 2 ] = this._z;
  2348. array[ offset + 3 ] = this._w;
  2349. return array;
  2350. }
  2351. fromBufferAttribute( attribute, index ) {
  2352. this._x = attribute.getX( index );
  2353. this._y = attribute.getY( index );
  2354. this._z = attribute.getZ( index );
  2355. this._w = attribute.getW( index );
  2356. this._onChangeCallback();
  2357. return this;
  2358. }
  2359. toJSON() {
  2360. return this.toArray();
  2361. }
  2362. _onChange( callback ) {
  2363. this._onChangeCallback = callback;
  2364. return this;
  2365. }
  2366. _onChangeCallback() {}
  2367. *[ Symbol.iterator ]() {
  2368. yield this._x;
  2369. yield this._y;
  2370. yield this._z;
  2371. yield this._w;
  2372. }
  2373. }
  2374. class Vector3 {
  2375. constructor( x = 0, y = 0, z = 0 ) {
  2376. Vector3.prototype.isVector3 = true;
  2377. this.x = x;
  2378. this.y = y;
  2379. this.z = z;
  2380. }
  2381. set( x, y, z ) {
  2382. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2383. this.x = x;
  2384. this.y = y;
  2385. this.z = z;
  2386. return this;
  2387. }
  2388. setScalar( scalar ) {
  2389. this.x = scalar;
  2390. this.y = scalar;
  2391. this.z = scalar;
  2392. return this;
  2393. }
  2394. setX( x ) {
  2395. this.x = x;
  2396. return this;
  2397. }
  2398. setY( y ) {
  2399. this.y = y;
  2400. return this;
  2401. }
  2402. setZ( z ) {
  2403. this.z = z;
  2404. return this;
  2405. }
  2406. setComponent( index, value ) {
  2407. switch ( index ) {
  2408. case 0: this.x = value; break;
  2409. case 1: this.y = value; break;
  2410. case 2: this.z = value; break;
  2411. default: throw new Error( 'index is out of range: ' + index );
  2412. }
  2413. return this;
  2414. }
  2415. getComponent( index ) {
  2416. switch ( index ) {
  2417. case 0: return this.x;
  2418. case 1: return this.y;
  2419. case 2: return this.z;
  2420. default: throw new Error( 'index is out of range: ' + index );
  2421. }
  2422. }
  2423. clone() {
  2424. return new this.constructor( this.x, this.y, this.z );
  2425. }
  2426. copy( v ) {
  2427. this.x = v.x;
  2428. this.y = v.y;
  2429. this.z = v.z;
  2430. return this;
  2431. }
  2432. add( v ) {
  2433. this.x += v.x;
  2434. this.y += v.y;
  2435. this.z += v.z;
  2436. return this;
  2437. }
  2438. addScalar( s ) {
  2439. this.x += s;
  2440. this.y += s;
  2441. this.z += s;
  2442. return this;
  2443. }
  2444. addVectors( a, b ) {
  2445. this.x = a.x + b.x;
  2446. this.y = a.y + b.y;
  2447. this.z = a.z + b.z;
  2448. return this;
  2449. }
  2450. addScaledVector( v, s ) {
  2451. this.x += v.x * s;
  2452. this.y += v.y * s;
  2453. this.z += v.z * s;
  2454. return this;
  2455. }
  2456. sub( v ) {
  2457. this.x -= v.x;
  2458. this.y -= v.y;
  2459. this.z -= v.z;
  2460. return this;
  2461. }
  2462. subScalar( s ) {
  2463. this.x -= s;
  2464. this.y -= s;
  2465. this.z -= s;
  2466. return this;
  2467. }
  2468. subVectors( a, b ) {
  2469. this.x = a.x - b.x;
  2470. this.y = a.y - b.y;
  2471. this.z = a.z - b.z;
  2472. return this;
  2473. }
  2474. multiply( v ) {
  2475. this.x *= v.x;
  2476. this.y *= v.y;
  2477. this.z *= v.z;
  2478. return this;
  2479. }
  2480. multiplyScalar( scalar ) {
  2481. this.x *= scalar;
  2482. this.y *= scalar;
  2483. this.z *= scalar;
  2484. return this;
  2485. }
  2486. multiplyVectors( a, b ) {
  2487. this.x = a.x * b.x;
  2488. this.y = a.y * b.y;
  2489. this.z = a.z * b.z;
  2490. return this;
  2491. }
  2492. applyEuler( euler ) {
  2493. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2494. }
  2495. applyAxisAngle( axis, angle ) {
  2496. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2497. }
  2498. applyMatrix3( m ) {
  2499. const x = this.x, y = this.y, z = this.z;
  2500. const e = m.elements;
  2501. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2502. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2503. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2504. return this;
  2505. }
  2506. applyNormalMatrix( m ) {
  2507. return this.applyMatrix3( m ).normalize();
  2508. }
  2509. applyMatrix4( m ) {
  2510. const x = this.x, y = this.y, z = this.z;
  2511. const e = m.elements;
  2512. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2513. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2514. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2515. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2516. return this;
  2517. }
  2518. applyQuaternion( q ) {
  2519. // quaternion q is assumed to have unit length
  2520. const vx = this.x, vy = this.y, vz = this.z;
  2521. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2522. // t = 2 * cross( q.xyz, v );
  2523. const tx = 2 * ( qy * vz - qz * vy );
  2524. const ty = 2 * ( qz * vx - qx * vz );
  2525. const tz = 2 * ( qx * vy - qy * vx );
  2526. // v + q.w * t + cross( q.xyz, t );
  2527. this.x = vx + qw * tx + qy * tz - qz * ty;
  2528. this.y = vy + qw * ty + qz * tx - qx * tz;
  2529. this.z = vz + qw * tz + qx * ty - qy * tx;
  2530. return this;
  2531. }
  2532. project( camera ) {
  2533. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2534. }
  2535. unproject( camera ) {
  2536. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2537. }
  2538. transformDirection( m ) {
  2539. // input: THREE.Matrix4 affine matrix
  2540. // vector interpreted as a direction
  2541. const x = this.x, y = this.y, z = this.z;
  2542. const e = m.elements;
  2543. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2544. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2545. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2546. return this.normalize();
  2547. }
  2548. divide( v ) {
  2549. this.x /= v.x;
  2550. this.y /= v.y;
  2551. this.z /= v.z;
  2552. return this;
  2553. }
  2554. divideScalar( scalar ) {
  2555. return this.multiplyScalar( 1 / scalar );
  2556. }
  2557. min( v ) {
  2558. this.x = Math.min( this.x, v.x );
  2559. this.y = Math.min( this.y, v.y );
  2560. this.z = Math.min( this.z, v.z );
  2561. return this;
  2562. }
  2563. max( v ) {
  2564. this.x = Math.max( this.x, v.x );
  2565. this.y = Math.max( this.y, v.y );
  2566. this.z = Math.max( this.z, v.z );
  2567. return this;
  2568. }
  2569. clamp( min, max ) {
  2570. // assumes min < max, componentwise
  2571. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2572. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2573. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2574. return this;
  2575. }
  2576. clampScalar( minVal, maxVal ) {
  2577. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2578. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2579. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2580. return this;
  2581. }
  2582. clampLength( min, max ) {
  2583. const length = this.length();
  2584. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2585. }
  2586. floor() {
  2587. this.x = Math.floor( this.x );
  2588. this.y = Math.floor( this.y );
  2589. this.z = Math.floor( this.z );
  2590. return this;
  2591. }
  2592. ceil() {
  2593. this.x = Math.ceil( this.x );
  2594. this.y = Math.ceil( this.y );
  2595. this.z = Math.ceil( this.z );
  2596. return this;
  2597. }
  2598. round() {
  2599. this.x = Math.round( this.x );
  2600. this.y = Math.round( this.y );
  2601. this.z = Math.round( this.z );
  2602. return this;
  2603. }
  2604. roundToZero() {
  2605. this.x = Math.trunc( this.x );
  2606. this.y = Math.trunc( this.y );
  2607. this.z = Math.trunc( this.z );
  2608. return this;
  2609. }
  2610. negate() {
  2611. this.x = - this.x;
  2612. this.y = - this.y;
  2613. this.z = - this.z;
  2614. return this;
  2615. }
  2616. dot( v ) {
  2617. return this.x * v.x + this.y * v.y + this.z * v.z;
  2618. }
  2619. // TODO lengthSquared?
  2620. lengthSq() {
  2621. return this.x * this.x + this.y * this.y + this.z * this.z;
  2622. }
  2623. length() {
  2624. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2625. }
  2626. manhattanLength() {
  2627. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2628. }
  2629. normalize() {
  2630. return this.divideScalar( this.length() || 1 );
  2631. }
  2632. setLength( length ) {
  2633. return this.normalize().multiplyScalar( length );
  2634. }
  2635. lerp( v, alpha ) {
  2636. this.x += ( v.x - this.x ) * alpha;
  2637. this.y += ( v.y - this.y ) * alpha;
  2638. this.z += ( v.z - this.z ) * alpha;
  2639. return this;
  2640. }
  2641. lerpVectors( v1, v2, alpha ) {
  2642. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2643. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2644. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2645. return this;
  2646. }
  2647. cross( v ) {
  2648. return this.crossVectors( this, v );
  2649. }
  2650. crossVectors( a, b ) {
  2651. const ax = a.x, ay = a.y, az = a.z;
  2652. const bx = b.x, by = b.y, bz = b.z;
  2653. this.x = ay * bz - az * by;
  2654. this.y = az * bx - ax * bz;
  2655. this.z = ax * by - ay * bx;
  2656. return this;
  2657. }
  2658. projectOnVector( v ) {
  2659. const denominator = v.lengthSq();
  2660. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2661. const scalar = v.dot( this ) / denominator;
  2662. return this.copy( v ).multiplyScalar( scalar );
  2663. }
  2664. projectOnPlane( planeNormal ) {
  2665. _vector$c.copy( this ).projectOnVector( planeNormal );
  2666. return this.sub( _vector$c );
  2667. }
  2668. reflect( normal ) {
  2669. // reflect incident vector off plane orthogonal to normal
  2670. // normal is assumed to have unit length
  2671. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2672. }
  2673. angleTo( v ) {
  2674. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2675. if ( denominator === 0 ) return Math.PI / 2;
  2676. const theta = this.dot( v ) / denominator;
  2677. // clamp, to handle numerical problems
  2678. return Math.acos( clamp$1( theta, - 1, 1 ) );
  2679. }
  2680. distanceTo( v ) {
  2681. return Math.sqrt( this.distanceToSquared( v ) );
  2682. }
  2683. distanceToSquared( v ) {
  2684. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2685. return dx * dx + dy * dy + dz * dz;
  2686. }
  2687. manhattanDistanceTo( v ) {
  2688. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2689. }
  2690. setFromSpherical( s ) {
  2691. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2692. }
  2693. setFromSphericalCoords( radius, phi, theta ) {
  2694. const sinPhiRadius = Math.sin( phi ) * radius;
  2695. this.x = sinPhiRadius * Math.sin( theta );
  2696. this.y = Math.cos( phi ) * radius;
  2697. this.z = sinPhiRadius * Math.cos( theta );
  2698. return this;
  2699. }
  2700. setFromCylindrical( c ) {
  2701. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2702. }
  2703. setFromCylindricalCoords( radius, theta, y ) {
  2704. this.x = radius * Math.sin( theta );
  2705. this.y = y;
  2706. this.z = radius * Math.cos( theta );
  2707. return this;
  2708. }
  2709. setFromMatrixPosition( m ) {
  2710. const e = m.elements;
  2711. this.x = e[ 12 ];
  2712. this.y = e[ 13 ];
  2713. this.z = e[ 14 ];
  2714. return this;
  2715. }
  2716. setFromMatrixScale( m ) {
  2717. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2718. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2719. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2720. this.x = sx;
  2721. this.y = sy;
  2722. this.z = sz;
  2723. return this;
  2724. }
  2725. setFromMatrixColumn( m, index ) {
  2726. return this.fromArray( m.elements, index * 4 );
  2727. }
  2728. setFromMatrix3Column( m, index ) {
  2729. return this.fromArray( m.elements, index * 3 );
  2730. }
  2731. setFromEuler( e ) {
  2732. this.x = e._x;
  2733. this.y = e._y;
  2734. this.z = e._z;
  2735. return this;
  2736. }
  2737. setFromColor( c ) {
  2738. this.x = c.r;
  2739. this.y = c.g;
  2740. this.z = c.b;
  2741. return this;
  2742. }
  2743. equals( v ) {
  2744. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2745. }
  2746. fromArray( array, offset = 0 ) {
  2747. this.x = array[ offset ];
  2748. this.y = array[ offset + 1 ];
  2749. this.z = array[ offset + 2 ];
  2750. return this;
  2751. }
  2752. toArray( array = [], offset = 0 ) {
  2753. array[ offset ] = this.x;
  2754. array[ offset + 1 ] = this.y;
  2755. array[ offset + 2 ] = this.z;
  2756. return array;
  2757. }
  2758. fromBufferAttribute( attribute, index ) {
  2759. this.x = attribute.getX( index );
  2760. this.y = attribute.getY( index );
  2761. this.z = attribute.getZ( index );
  2762. return this;
  2763. }
  2764. random() {
  2765. this.x = Math.random();
  2766. this.y = Math.random();
  2767. this.z = Math.random();
  2768. return this;
  2769. }
  2770. randomDirection() {
  2771. // https://mathworld.wolfram.com/SpherePointPicking.html
  2772. const theta = Math.random() * Math.PI * 2;
  2773. const u = Math.random() * 2 - 1;
  2774. const c = Math.sqrt( 1 - u * u );
  2775. this.x = c * Math.cos( theta );
  2776. this.y = u;
  2777. this.z = c * Math.sin( theta );
  2778. return this;
  2779. }
  2780. *[ Symbol.iterator ]() {
  2781. yield this.x;
  2782. yield this.y;
  2783. yield this.z;
  2784. }
  2785. }
  2786. const _vector$c = /*@__PURE__*/ new Vector3();
  2787. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2788. class Box3 {
  2789. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2790. this.isBox3 = true;
  2791. this.min = min;
  2792. this.max = max;
  2793. }
  2794. set( min, max ) {
  2795. this.min.copy( min );
  2796. this.max.copy( max );
  2797. return this;
  2798. }
  2799. setFromArray( array ) {
  2800. this.makeEmpty();
  2801. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2802. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2803. }
  2804. return this;
  2805. }
  2806. setFromBufferAttribute( attribute ) {
  2807. this.makeEmpty();
  2808. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2809. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2810. }
  2811. return this;
  2812. }
  2813. setFromPoints( points ) {
  2814. this.makeEmpty();
  2815. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2816. this.expandByPoint( points[ i ] );
  2817. }
  2818. return this;
  2819. }
  2820. setFromCenterAndSize( center, size ) {
  2821. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2822. this.min.copy( center ).sub( halfSize );
  2823. this.max.copy( center ).add( halfSize );
  2824. return this;
  2825. }
  2826. setFromObject( object, precise = false ) {
  2827. this.makeEmpty();
  2828. return this.expandByObject( object, precise );
  2829. }
  2830. clone() {
  2831. return new this.constructor().copy( this );
  2832. }
  2833. copy( box ) {
  2834. this.min.copy( box.min );
  2835. this.max.copy( box.max );
  2836. return this;
  2837. }
  2838. makeEmpty() {
  2839. this.min.x = this.min.y = this.min.z = + Infinity;
  2840. this.max.x = this.max.y = this.max.z = - Infinity;
  2841. return this;
  2842. }
  2843. isEmpty() {
  2844. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2845. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2846. }
  2847. getCenter( target ) {
  2848. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2849. }
  2850. getSize( target ) {
  2851. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2852. }
  2853. expandByPoint( point ) {
  2854. this.min.min( point );
  2855. this.max.max( point );
  2856. return this;
  2857. }
  2858. expandByVector( vector ) {
  2859. this.min.sub( vector );
  2860. this.max.add( vector );
  2861. return this;
  2862. }
  2863. expandByScalar( scalar ) {
  2864. this.min.addScalar( - scalar );
  2865. this.max.addScalar( scalar );
  2866. return this;
  2867. }
  2868. expandByObject( object, precise = false ) {
  2869. // Computes the world-axis-aligned bounding box of an object (including its children),
  2870. // accounting for both the object's, and children's, world transforms
  2871. object.updateWorldMatrix( false, false );
  2872. const geometry = object.geometry;
  2873. if ( geometry !== undefined ) {
  2874. const positionAttribute = geometry.getAttribute( 'position' );
  2875. // precise AABB computation based on vertex data requires at least a position attribute.
  2876. // instancing isn't supported so far and uses the normal (conservative) code path.
  2877. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2878. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2879. if ( object.isMesh === true ) {
  2880. object.getVertexPosition( i, _vector$b );
  2881. } else {
  2882. _vector$b.fromBufferAttribute( positionAttribute, i );
  2883. }
  2884. _vector$b.applyMatrix4( object.matrixWorld );
  2885. this.expandByPoint( _vector$b );
  2886. }
  2887. } else {
  2888. if ( object.boundingBox !== undefined ) {
  2889. // object-level bounding box
  2890. if ( object.boundingBox === null ) {
  2891. object.computeBoundingBox();
  2892. }
  2893. _box$4.copy( object.boundingBox );
  2894. } else {
  2895. // geometry-level bounding box
  2896. if ( geometry.boundingBox === null ) {
  2897. geometry.computeBoundingBox();
  2898. }
  2899. _box$4.copy( geometry.boundingBox );
  2900. }
  2901. _box$4.applyMatrix4( object.matrixWorld );
  2902. this.union( _box$4 );
  2903. }
  2904. }
  2905. const children = object.children;
  2906. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2907. this.expandByObject( children[ i ], precise );
  2908. }
  2909. return this;
  2910. }
  2911. containsPoint( point ) {
  2912. return point.x >= this.min.x && point.x <= this.max.x &&
  2913. point.y >= this.min.y && point.y <= this.max.y &&
  2914. point.z >= this.min.z && point.z <= this.max.z;
  2915. }
  2916. containsBox( box ) {
  2917. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2918. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2919. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2920. }
  2921. getParameter( point, target ) {
  2922. // This can potentially have a divide by zero if the box
  2923. // has a size dimension of 0.
  2924. return target.set(
  2925. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2926. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2927. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2928. );
  2929. }
  2930. intersectsBox( box ) {
  2931. // using 6 splitting planes to rule out intersections.
  2932. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  2933. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  2934. box.max.z >= this.min.z && box.min.z <= this.max.z;
  2935. }
  2936. intersectsSphere( sphere ) {
  2937. // Find the point on the AABB closest to the sphere center.
  2938. this.clampPoint( sphere.center, _vector$b );
  2939. // If that point is inside the sphere, the AABB and sphere intersect.
  2940. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2941. }
  2942. intersectsPlane( plane ) {
  2943. // We compute the minimum and maximum dot product values. If those values
  2944. // are on the same side (back or front) of the plane, then there is no intersection.
  2945. let min, max;
  2946. if ( plane.normal.x > 0 ) {
  2947. min = plane.normal.x * this.min.x;
  2948. max = plane.normal.x * this.max.x;
  2949. } else {
  2950. min = plane.normal.x * this.max.x;
  2951. max = plane.normal.x * this.min.x;
  2952. }
  2953. if ( plane.normal.y > 0 ) {
  2954. min += plane.normal.y * this.min.y;
  2955. max += plane.normal.y * this.max.y;
  2956. } else {
  2957. min += plane.normal.y * this.max.y;
  2958. max += plane.normal.y * this.min.y;
  2959. }
  2960. if ( plane.normal.z > 0 ) {
  2961. min += plane.normal.z * this.min.z;
  2962. max += plane.normal.z * this.max.z;
  2963. } else {
  2964. min += plane.normal.z * this.max.z;
  2965. max += plane.normal.z * this.min.z;
  2966. }
  2967. return ( min <= - plane.constant && max >= - plane.constant );
  2968. }
  2969. intersectsTriangle( triangle ) {
  2970. if ( this.isEmpty() ) {
  2971. return false;
  2972. }
  2973. // compute box center and extents
  2974. this.getCenter( _center );
  2975. _extents.subVectors( this.max, _center );
  2976. // translate triangle to aabb origin
  2977. _v0$2.subVectors( triangle.a, _center );
  2978. _v1$7.subVectors( triangle.b, _center );
  2979. _v2$4.subVectors( triangle.c, _center );
  2980. // compute edge vectors for triangle
  2981. _f0.subVectors( _v1$7, _v0$2 );
  2982. _f1.subVectors( _v2$4, _v1$7 );
  2983. _f2.subVectors( _v0$2, _v2$4 );
  2984. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2985. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  2986. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2987. let axes = [
  2988. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2989. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2990. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2991. ];
  2992. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2993. return false;
  2994. }
  2995. // test 3 face normals from the aabb
  2996. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2997. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2998. return false;
  2999. }
  3000. // finally testing the face normal of the triangle
  3001. // use already existing triangle edge vectors here
  3002. _triangleNormal.crossVectors( _f0, _f1 );
  3003. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3004. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3005. }
  3006. clampPoint( point, target ) {
  3007. return target.copy( point ).clamp( this.min, this.max );
  3008. }
  3009. distanceToPoint( point ) {
  3010. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3011. }
  3012. getBoundingSphere( target ) {
  3013. if ( this.isEmpty() ) {
  3014. target.makeEmpty();
  3015. } else {
  3016. this.getCenter( target.center );
  3017. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3018. }
  3019. return target;
  3020. }
  3021. intersect( box ) {
  3022. this.min.max( box.min );
  3023. this.max.min( box.max );
  3024. // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  3025. if ( this.isEmpty() ) this.makeEmpty();
  3026. return this;
  3027. }
  3028. union( box ) {
  3029. this.min.min( box.min );
  3030. this.max.max( box.max );
  3031. return this;
  3032. }
  3033. applyMatrix4( matrix ) {
  3034. // transform of empty box is an empty box.
  3035. if ( this.isEmpty() ) return this;
  3036. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3037. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3038. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3039. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3040. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3041. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3042. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3043. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3044. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3045. this.setFromPoints( _points );
  3046. return this;
  3047. }
  3048. translate( offset ) {
  3049. this.min.add( offset );
  3050. this.max.add( offset );
  3051. return this;
  3052. }
  3053. equals( box ) {
  3054. return box.min.equals( this.min ) && box.max.equals( this.max );
  3055. }
  3056. }
  3057. const _points = [
  3058. /*@__PURE__*/ new Vector3(),
  3059. /*@__PURE__*/ new Vector3(),
  3060. /*@__PURE__*/ new Vector3(),
  3061. /*@__PURE__*/ new Vector3(),
  3062. /*@__PURE__*/ new Vector3(),
  3063. /*@__PURE__*/ new Vector3(),
  3064. /*@__PURE__*/ new Vector3(),
  3065. /*@__PURE__*/ new Vector3()
  3066. ];
  3067. const _vector$b = /*@__PURE__*/ new Vector3();
  3068. const _box$4 = /*@__PURE__*/ new Box3();
  3069. // triangle centered vertices
  3070. const _v0$2 = /*@__PURE__*/ new Vector3();
  3071. const _v1$7 = /*@__PURE__*/ new Vector3();
  3072. const _v2$4 = /*@__PURE__*/ new Vector3();
  3073. // triangle edge vectors
  3074. const _f0 = /*@__PURE__*/ new Vector3();
  3075. const _f1 = /*@__PURE__*/ new Vector3();
  3076. const _f2 = /*@__PURE__*/ new Vector3();
  3077. const _center = /*@__PURE__*/ new Vector3();
  3078. const _extents = /*@__PURE__*/ new Vector3();
  3079. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3080. const _testAxis = /*@__PURE__*/ new Vector3();
  3081. function satForAxes( axes, v0, v1, v2, extents ) {
  3082. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3083. _testAxis.fromArray( axes, i );
  3084. // project the aabb onto the separating axis
  3085. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3086. // project all 3 vertices of the triangle onto the separating axis
  3087. const p0 = v0.dot( _testAxis );
  3088. const p1 = v1.dot( _testAxis );
  3089. const p2 = v2.dot( _testAxis );
  3090. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3091. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3092. // points of the projected triangle are outside the projected half-length of the aabb
  3093. // the axis is separating and we can exit
  3094. return false;
  3095. }
  3096. }
  3097. return true;
  3098. }
  3099. const _box$3 = /*@__PURE__*/ new Box3();
  3100. const _v1$6 = /*@__PURE__*/ new Vector3();
  3101. const _v2$3 = /*@__PURE__*/ new Vector3();
  3102. class Sphere {
  3103. constructor( center = new Vector3(), radius = - 1 ) {
  3104. this.isSphere = true;
  3105. this.center = center;
  3106. this.radius = radius;
  3107. }
  3108. set( center, radius ) {
  3109. this.center.copy( center );
  3110. this.radius = radius;
  3111. return this;
  3112. }
  3113. setFromPoints( points, optionalCenter ) {
  3114. const center = this.center;
  3115. if ( optionalCenter !== undefined ) {
  3116. center.copy( optionalCenter );
  3117. } else {
  3118. _box$3.setFromPoints( points ).getCenter( center );
  3119. }
  3120. let maxRadiusSq = 0;
  3121. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3122. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3123. }
  3124. this.radius = Math.sqrt( maxRadiusSq );
  3125. return this;
  3126. }
  3127. copy( sphere ) {
  3128. this.center.copy( sphere.center );
  3129. this.radius = sphere.radius;
  3130. return this;
  3131. }
  3132. isEmpty() {
  3133. return ( this.radius < 0 );
  3134. }
  3135. makeEmpty() {
  3136. this.center.set( 0, 0, 0 );
  3137. this.radius = - 1;
  3138. return this;
  3139. }
  3140. containsPoint( point ) {
  3141. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3142. }
  3143. distanceToPoint( point ) {
  3144. return ( point.distanceTo( this.center ) - this.radius );
  3145. }
  3146. intersectsSphere( sphere ) {
  3147. const radiusSum = this.radius + sphere.radius;
  3148. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3149. }
  3150. intersectsBox( box ) {
  3151. return box.intersectsSphere( this );
  3152. }
  3153. intersectsPlane( plane ) {
  3154. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3155. }
  3156. clampPoint( point, target ) {
  3157. const deltaLengthSq = this.center.distanceToSquared( point );
  3158. target.copy( point );
  3159. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3160. target.sub( this.center ).normalize();
  3161. target.multiplyScalar( this.radius ).add( this.center );
  3162. }
  3163. return target;
  3164. }
  3165. getBoundingBox( target ) {
  3166. if ( this.isEmpty() ) {
  3167. // Empty sphere produces empty bounding box
  3168. target.makeEmpty();
  3169. return target;
  3170. }
  3171. target.set( this.center, this.center );
  3172. target.expandByScalar( this.radius );
  3173. return target;
  3174. }
  3175. applyMatrix4( matrix ) {
  3176. this.center.applyMatrix4( matrix );
  3177. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3178. return this;
  3179. }
  3180. translate( offset ) {
  3181. this.center.add( offset );
  3182. return this;
  3183. }
  3184. expandByPoint( point ) {
  3185. if ( this.isEmpty() ) {
  3186. this.center.copy( point );
  3187. this.radius = 0;
  3188. return this;
  3189. }
  3190. _v1$6.subVectors( point, this.center );
  3191. const lengthSq = _v1$6.lengthSq();
  3192. if ( lengthSq > ( this.radius * this.radius ) ) {
  3193. // calculate the minimal sphere
  3194. const length = Math.sqrt( lengthSq );
  3195. const delta = ( length - this.radius ) * 0.5;
  3196. this.center.addScaledVector( _v1$6, delta / length );
  3197. this.radius += delta;
  3198. }
  3199. return this;
  3200. }
  3201. union( sphere ) {
  3202. if ( sphere.isEmpty() ) {
  3203. return this;
  3204. }
  3205. if ( this.isEmpty() ) {
  3206. this.copy( sphere );
  3207. return this;
  3208. }
  3209. if ( this.center.equals( sphere.center ) === true ) {
  3210. this.radius = Math.max( this.radius, sphere.radius );
  3211. } else {
  3212. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3213. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3214. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3215. }
  3216. return this;
  3217. }
  3218. equals( sphere ) {
  3219. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3220. }
  3221. clone() {
  3222. return new this.constructor().copy( this );
  3223. }
  3224. }
  3225. const _vector$a = /*@__PURE__*/ new Vector3();
  3226. const _segCenter = /*@__PURE__*/ new Vector3();
  3227. const _segDir = /*@__PURE__*/ new Vector3();
  3228. const _diff = /*@__PURE__*/ new Vector3();
  3229. const _edge1 = /*@__PURE__*/ new Vector3();
  3230. const _edge2 = /*@__PURE__*/ new Vector3();
  3231. const _normal$2 = /*@__PURE__*/ new Vector3();
  3232. class Ray {
  3233. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3234. this.origin = origin;
  3235. this.direction = direction;
  3236. }
  3237. set( origin, direction ) {
  3238. this.origin.copy( origin );
  3239. this.direction.copy( direction );
  3240. return this;
  3241. }
  3242. copy( ray ) {
  3243. this.origin.copy( ray.origin );
  3244. this.direction.copy( ray.direction );
  3245. return this;
  3246. }
  3247. at( t, target ) {
  3248. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3249. }
  3250. lookAt( v ) {
  3251. this.direction.copy( v ).sub( this.origin ).normalize();
  3252. return this;
  3253. }
  3254. recast( t ) {
  3255. this.origin.copy( this.at( t, _vector$a ) );
  3256. return this;
  3257. }
  3258. closestPointToPoint( point, target ) {
  3259. target.subVectors( point, this.origin );
  3260. const directionDistance = target.dot( this.direction );
  3261. if ( directionDistance < 0 ) {
  3262. return target.copy( this.origin );
  3263. }
  3264. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3265. }
  3266. distanceToPoint( point ) {
  3267. return Math.sqrt( this.distanceSqToPoint( point ) );
  3268. }
  3269. distanceSqToPoint( point ) {
  3270. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3271. // point behind the ray
  3272. if ( directionDistance < 0 ) {
  3273. return this.origin.distanceToSquared( point );
  3274. }
  3275. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3276. return _vector$a.distanceToSquared( point );
  3277. }
  3278. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3279. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3280. // It returns the min distance between the ray and the segment
  3281. // defined by v0 and v1
  3282. // It can also set two optional targets :
  3283. // - The closest point on the ray
  3284. // - The closest point on the segment
  3285. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3286. _segDir.copy( v1 ).sub( v0 ).normalize();
  3287. _diff.copy( this.origin ).sub( _segCenter );
  3288. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3289. const a01 = - this.direction.dot( _segDir );
  3290. const b0 = _diff.dot( this.direction );
  3291. const b1 = - _diff.dot( _segDir );
  3292. const c = _diff.lengthSq();
  3293. const det = Math.abs( 1 - a01 * a01 );
  3294. let s0, s1, sqrDist, extDet;
  3295. if ( det > 0 ) {
  3296. // The ray and segment are not parallel.
  3297. s0 = a01 * b1 - b0;
  3298. s1 = a01 * b0 - b1;
  3299. extDet = segExtent * det;
  3300. if ( s0 >= 0 ) {
  3301. if ( s1 >= - extDet ) {
  3302. if ( s1 <= extDet ) {
  3303. // region 0
  3304. // Minimum at interior points of ray and segment.
  3305. const invDet = 1 / det;
  3306. s0 *= invDet;
  3307. s1 *= invDet;
  3308. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3309. } else {
  3310. // region 1
  3311. s1 = segExtent;
  3312. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3313. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3314. }
  3315. } else {
  3316. // region 5
  3317. s1 = - segExtent;
  3318. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3319. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3320. }
  3321. } else {
  3322. if ( s1 <= - extDet ) {
  3323. // region 4
  3324. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3325. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3326. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3327. } else if ( s1 <= extDet ) {
  3328. // region 3
  3329. s0 = 0;
  3330. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3331. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3332. } else {
  3333. // region 2
  3334. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3335. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3336. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3337. }
  3338. }
  3339. } else {
  3340. // Ray and segment are parallel.
  3341. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3342. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3343. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3344. }
  3345. if ( optionalPointOnRay ) {
  3346. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3347. }
  3348. if ( optionalPointOnSegment ) {
  3349. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3350. }
  3351. return sqrDist;
  3352. }
  3353. intersectSphere( sphere, target ) {
  3354. _vector$a.subVectors( sphere.center, this.origin );
  3355. const tca = _vector$a.dot( this.direction );
  3356. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3357. const radius2 = sphere.radius * sphere.radius;
  3358. if ( d2 > radius2 ) return null;
  3359. const thc = Math.sqrt( radius2 - d2 );
  3360. // t0 = first intersect point - entrance on front of sphere
  3361. const t0 = tca - thc;
  3362. // t1 = second intersect point - exit point on back of sphere
  3363. const t1 = tca + thc;
  3364. // test to see if t1 is behind the ray - if so, return null
  3365. if ( t1 < 0 ) return null;
  3366. // test to see if t0 is behind the ray:
  3367. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3368. // in order to always return an intersect point that is in front of the ray.
  3369. if ( t0 < 0 ) return this.at( t1, target );
  3370. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3371. return this.at( t0, target );
  3372. }
  3373. intersectsSphere( sphere ) {
  3374. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3375. }
  3376. distanceToPlane( plane ) {
  3377. const denominator = plane.normal.dot( this.direction );
  3378. if ( denominator === 0 ) {
  3379. // line is coplanar, return origin
  3380. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3381. return 0;
  3382. }
  3383. // Null is preferable to undefined since undefined means.... it is undefined
  3384. return null;
  3385. }
  3386. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3387. // Return if the ray never intersects the plane
  3388. return t >= 0 ? t : null;
  3389. }
  3390. intersectPlane( plane, target ) {
  3391. const t = this.distanceToPlane( plane );
  3392. if ( t === null ) {
  3393. return null;
  3394. }
  3395. return this.at( t, target );
  3396. }
  3397. intersectsPlane( plane ) {
  3398. // check if the ray lies on the plane first
  3399. const distToPoint = plane.distanceToPoint( this.origin );
  3400. if ( distToPoint === 0 ) {
  3401. return true;
  3402. }
  3403. const denominator = plane.normal.dot( this.direction );
  3404. if ( denominator * distToPoint < 0 ) {
  3405. return true;
  3406. }
  3407. // ray origin is behind the plane (and is pointing behind it)
  3408. return false;
  3409. }
  3410. intersectBox( box, target ) {
  3411. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3412. const invdirx = 1 / this.direction.x,
  3413. invdiry = 1 / this.direction.y,
  3414. invdirz = 1 / this.direction.z;
  3415. const origin = this.origin;
  3416. if ( invdirx >= 0 ) {
  3417. tmin = ( box.min.x - origin.x ) * invdirx;
  3418. tmax = ( box.max.x - origin.x ) * invdirx;
  3419. } else {
  3420. tmin = ( box.max.x - origin.x ) * invdirx;
  3421. tmax = ( box.min.x - origin.x ) * invdirx;
  3422. }
  3423. if ( invdiry >= 0 ) {
  3424. tymin = ( box.min.y - origin.y ) * invdiry;
  3425. tymax = ( box.max.y - origin.y ) * invdiry;
  3426. } else {
  3427. tymin = ( box.max.y - origin.y ) * invdiry;
  3428. tymax = ( box.min.y - origin.y ) * invdiry;
  3429. }
  3430. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3431. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3432. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3433. if ( invdirz >= 0 ) {
  3434. tzmin = ( box.min.z - origin.z ) * invdirz;
  3435. tzmax = ( box.max.z - origin.z ) * invdirz;
  3436. } else {
  3437. tzmin = ( box.max.z - origin.z ) * invdirz;
  3438. tzmax = ( box.min.z - origin.z ) * invdirz;
  3439. }
  3440. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3441. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3442. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3443. //return point closest to the ray (positive side)
  3444. if ( tmax < 0 ) return null;
  3445. return this.at( tmin >= 0 ? tmin : tmax, target );
  3446. }
  3447. intersectsBox( box ) {
  3448. return this.intersectBox( box, _vector$a ) !== null;
  3449. }
  3450. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3451. // Compute the offset origin, edges, and normal.
  3452. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3453. _edge1.subVectors( b, a );
  3454. _edge2.subVectors( c, a );
  3455. _normal$2.crossVectors( _edge1, _edge2 );
  3456. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3457. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3458. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3459. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3460. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3461. let DdN = this.direction.dot( _normal$2 );
  3462. let sign;
  3463. if ( DdN > 0 ) {
  3464. if ( backfaceCulling ) return null;
  3465. sign = 1;
  3466. } else if ( DdN < 0 ) {
  3467. sign = - 1;
  3468. DdN = - DdN;
  3469. } else {
  3470. return null;
  3471. }
  3472. _diff.subVectors( this.origin, a );
  3473. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3474. // b1 < 0, no intersection
  3475. if ( DdQxE2 < 0 ) {
  3476. return null;
  3477. }
  3478. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3479. // b2 < 0, no intersection
  3480. if ( DdE1xQ < 0 ) {
  3481. return null;
  3482. }
  3483. // b1+b2 > 1, no intersection
  3484. if ( DdQxE2 + DdE1xQ > DdN ) {
  3485. return null;
  3486. }
  3487. // Line intersects triangle, check if ray does.
  3488. const QdN = - sign * _diff.dot( _normal$2 );
  3489. // t < 0, no intersection
  3490. if ( QdN < 0 ) {
  3491. return null;
  3492. }
  3493. // Ray intersects triangle.
  3494. return this.at( QdN / DdN, target );
  3495. }
  3496. applyMatrix4( matrix4 ) {
  3497. this.origin.applyMatrix4( matrix4 );
  3498. this.direction.transformDirection( matrix4 );
  3499. return this;
  3500. }
  3501. equals( ray ) {
  3502. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3503. }
  3504. clone() {
  3505. return new this.constructor().copy( this );
  3506. }
  3507. }
  3508. class Matrix4 {
  3509. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3510. Matrix4.prototype.isMatrix4 = true;
  3511. this.elements = [
  3512. 1, 0, 0, 0,
  3513. 0, 1, 0, 0,
  3514. 0, 0, 1, 0,
  3515. 0, 0, 0, 1
  3516. ];
  3517. if ( n11 !== undefined ) {
  3518. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3519. }
  3520. }
  3521. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3522. const te = this.elements;
  3523. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3524. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3525. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3526. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3527. return this;
  3528. }
  3529. identity() {
  3530. this.set(
  3531. 1, 0, 0, 0,
  3532. 0, 1, 0, 0,
  3533. 0, 0, 1, 0,
  3534. 0, 0, 0, 1
  3535. );
  3536. return this;
  3537. }
  3538. clone() {
  3539. return new Matrix4().fromArray( this.elements );
  3540. }
  3541. copy( m ) {
  3542. const te = this.elements;
  3543. const me = m.elements;
  3544. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3545. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3546. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3547. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3548. return this;
  3549. }
  3550. copyPosition( m ) {
  3551. const te = this.elements, me = m.elements;
  3552. te[ 12 ] = me[ 12 ];
  3553. te[ 13 ] = me[ 13 ];
  3554. te[ 14 ] = me[ 14 ];
  3555. return this;
  3556. }
  3557. setFromMatrix3( m ) {
  3558. const me = m.elements;
  3559. this.set(
  3560. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3561. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3562. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3563. 0, 0, 0, 1
  3564. );
  3565. return this;
  3566. }
  3567. extractBasis( xAxis, yAxis, zAxis ) {
  3568. xAxis.setFromMatrixColumn( this, 0 );
  3569. yAxis.setFromMatrixColumn( this, 1 );
  3570. zAxis.setFromMatrixColumn( this, 2 );
  3571. return this;
  3572. }
  3573. makeBasis( xAxis, yAxis, zAxis ) {
  3574. this.set(
  3575. xAxis.x, yAxis.x, zAxis.x, 0,
  3576. xAxis.y, yAxis.y, zAxis.y, 0,
  3577. xAxis.z, yAxis.z, zAxis.z, 0,
  3578. 0, 0, 0, 1
  3579. );
  3580. return this;
  3581. }
  3582. extractRotation( m ) {
  3583. // this method does not support reflection matrices
  3584. const te = this.elements;
  3585. const me = m.elements;
  3586. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3587. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3588. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3589. te[ 0 ] = me[ 0 ] * scaleX;
  3590. te[ 1 ] = me[ 1 ] * scaleX;
  3591. te[ 2 ] = me[ 2 ] * scaleX;
  3592. te[ 3 ] = 0;
  3593. te[ 4 ] = me[ 4 ] * scaleY;
  3594. te[ 5 ] = me[ 5 ] * scaleY;
  3595. te[ 6 ] = me[ 6 ] * scaleY;
  3596. te[ 7 ] = 0;
  3597. te[ 8 ] = me[ 8 ] * scaleZ;
  3598. te[ 9 ] = me[ 9 ] * scaleZ;
  3599. te[ 10 ] = me[ 10 ] * scaleZ;
  3600. te[ 11 ] = 0;
  3601. te[ 12 ] = 0;
  3602. te[ 13 ] = 0;
  3603. te[ 14 ] = 0;
  3604. te[ 15 ] = 1;
  3605. return this;
  3606. }
  3607. makeRotationFromEuler( euler ) {
  3608. const te = this.elements;
  3609. const x = euler.x, y = euler.y, z = euler.z;
  3610. const a = Math.cos( x ), b = Math.sin( x );
  3611. const c = Math.cos( y ), d = Math.sin( y );
  3612. const e = Math.cos( z ), f = Math.sin( z );
  3613. if ( euler.order === 'XYZ' ) {
  3614. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3615. te[ 0 ] = c * e;
  3616. te[ 4 ] = - c * f;
  3617. te[ 8 ] = d;
  3618. te[ 1 ] = af + be * d;
  3619. te[ 5 ] = ae - bf * d;
  3620. te[ 9 ] = - b * c;
  3621. te[ 2 ] = bf - ae * d;
  3622. te[ 6 ] = be + af * d;
  3623. te[ 10 ] = a * c;
  3624. } else if ( euler.order === 'YXZ' ) {
  3625. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3626. te[ 0 ] = ce + df * b;
  3627. te[ 4 ] = de * b - cf;
  3628. te[ 8 ] = a * d;
  3629. te[ 1 ] = a * f;
  3630. te[ 5 ] = a * e;
  3631. te[ 9 ] = - b;
  3632. te[ 2 ] = cf * b - de;
  3633. te[ 6 ] = df + ce * b;
  3634. te[ 10 ] = a * c;
  3635. } else if ( euler.order === 'ZXY' ) {
  3636. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3637. te[ 0 ] = ce - df * b;
  3638. te[ 4 ] = - a * f;
  3639. te[ 8 ] = de + cf * b;
  3640. te[ 1 ] = cf + de * b;
  3641. te[ 5 ] = a * e;
  3642. te[ 9 ] = df - ce * b;
  3643. te[ 2 ] = - a * d;
  3644. te[ 6 ] = b;
  3645. te[ 10 ] = a * c;
  3646. } else if ( euler.order === 'ZYX' ) {
  3647. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3648. te[ 0 ] = c * e;
  3649. te[ 4 ] = be * d - af;
  3650. te[ 8 ] = ae * d + bf;
  3651. te[ 1 ] = c * f;
  3652. te[ 5 ] = bf * d + ae;
  3653. te[ 9 ] = af * d - be;
  3654. te[ 2 ] = - d;
  3655. te[ 6 ] = b * c;
  3656. te[ 10 ] = a * c;
  3657. } else if ( euler.order === 'YZX' ) {
  3658. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3659. te[ 0 ] = c * e;
  3660. te[ 4 ] = bd - ac * f;
  3661. te[ 8 ] = bc * f + ad;
  3662. te[ 1 ] = f;
  3663. te[ 5 ] = a * e;
  3664. te[ 9 ] = - b * e;
  3665. te[ 2 ] = - d * e;
  3666. te[ 6 ] = ad * f + bc;
  3667. te[ 10 ] = ac - bd * f;
  3668. } else if ( euler.order === 'XZY' ) {
  3669. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3670. te[ 0 ] = c * e;
  3671. te[ 4 ] = - f;
  3672. te[ 8 ] = d * e;
  3673. te[ 1 ] = ac * f + bd;
  3674. te[ 5 ] = a * e;
  3675. te[ 9 ] = ad * f - bc;
  3676. te[ 2 ] = bc * f - ad;
  3677. te[ 6 ] = b * e;
  3678. te[ 10 ] = bd * f + ac;
  3679. }
  3680. // bottom row
  3681. te[ 3 ] = 0;
  3682. te[ 7 ] = 0;
  3683. te[ 11 ] = 0;
  3684. // last column
  3685. te[ 12 ] = 0;
  3686. te[ 13 ] = 0;
  3687. te[ 14 ] = 0;
  3688. te[ 15 ] = 1;
  3689. return this;
  3690. }
  3691. makeRotationFromQuaternion( q ) {
  3692. return this.compose( _zero, q, _one );
  3693. }
  3694. lookAt( eye, target, up ) {
  3695. const te = this.elements;
  3696. _z.subVectors( eye, target );
  3697. if ( _z.lengthSq() === 0 ) {
  3698. // eye and target are in the same position
  3699. _z.z = 1;
  3700. }
  3701. _z.normalize();
  3702. _x.crossVectors( up, _z );
  3703. if ( _x.lengthSq() === 0 ) {
  3704. // up and z are parallel
  3705. if ( Math.abs( up.z ) === 1 ) {
  3706. _z.x += 0.0001;
  3707. } else {
  3708. _z.z += 0.0001;
  3709. }
  3710. _z.normalize();
  3711. _x.crossVectors( up, _z );
  3712. }
  3713. _x.normalize();
  3714. _y.crossVectors( _z, _x );
  3715. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3716. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3717. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3718. return this;
  3719. }
  3720. multiply( m ) {
  3721. return this.multiplyMatrices( this, m );
  3722. }
  3723. premultiply( m ) {
  3724. return this.multiplyMatrices( m, this );
  3725. }
  3726. multiplyMatrices( a, b ) {
  3727. const ae = a.elements;
  3728. const be = b.elements;
  3729. const te = this.elements;
  3730. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3731. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3732. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3733. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3734. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3735. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3736. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3737. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3738. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3739. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3740. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3741. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3742. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3743. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3744. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3745. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3746. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3747. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3748. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3749. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3750. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3751. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3752. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3753. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3754. return this;
  3755. }
  3756. multiplyScalar( s ) {
  3757. const te = this.elements;
  3758. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3759. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3760. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3761. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3762. return this;
  3763. }
  3764. determinant() {
  3765. const te = this.elements;
  3766. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3767. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3768. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3769. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3770. //TODO: make this more efficient
  3771. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3772. return (
  3773. n41 * (
  3774. + n14 * n23 * n32
  3775. - n13 * n24 * n32
  3776. - n14 * n22 * n33
  3777. + n12 * n24 * n33
  3778. + n13 * n22 * n34
  3779. - n12 * n23 * n34
  3780. ) +
  3781. n42 * (
  3782. + n11 * n23 * n34
  3783. - n11 * n24 * n33
  3784. + n14 * n21 * n33
  3785. - n13 * n21 * n34
  3786. + n13 * n24 * n31
  3787. - n14 * n23 * n31
  3788. ) +
  3789. n43 * (
  3790. + n11 * n24 * n32
  3791. - n11 * n22 * n34
  3792. - n14 * n21 * n32
  3793. + n12 * n21 * n34
  3794. + n14 * n22 * n31
  3795. - n12 * n24 * n31
  3796. ) +
  3797. n44 * (
  3798. - n13 * n22 * n31
  3799. - n11 * n23 * n32
  3800. + n11 * n22 * n33
  3801. + n13 * n21 * n32
  3802. - n12 * n21 * n33
  3803. + n12 * n23 * n31
  3804. )
  3805. );
  3806. }
  3807. transpose() {
  3808. const te = this.elements;
  3809. let tmp;
  3810. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3811. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3812. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3813. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3814. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3815. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3816. return this;
  3817. }
  3818. setPosition( x, y, z ) {
  3819. const te = this.elements;
  3820. if ( x.isVector3 ) {
  3821. te[ 12 ] = x.x;
  3822. te[ 13 ] = x.y;
  3823. te[ 14 ] = x.z;
  3824. } else {
  3825. te[ 12 ] = x;
  3826. te[ 13 ] = y;
  3827. te[ 14 ] = z;
  3828. }
  3829. return this;
  3830. }
  3831. invert() {
  3832. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3833. const te = this.elements,
  3834. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3835. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3836. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3837. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3838. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3839. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3840. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3841. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3842. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3843. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3844. const detInv = 1 / det;
  3845. te[ 0 ] = t11 * detInv;
  3846. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3847. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3848. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3849. te[ 4 ] = t12 * detInv;
  3850. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3851. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3852. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3853. te[ 8 ] = t13 * detInv;
  3854. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3855. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3856. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3857. te[ 12 ] = t14 * detInv;
  3858. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3859. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3860. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3861. return this;
  3862. }
  3863. scale( v ) {
  3864. const te = this.elements;
  3865. const x = v.x, y = v.y, z = v.z;
  3866. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3867. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3868. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3869. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3870. return this;
  3871. }
  3872. getMaxScaleOnAxis() {
  3873. const te = this.elements;
  3874. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3875. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3876. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3877. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3878. }
  3879. makeTranslation( x, y, z ) {
  3880. if ( x.isVector3 ) {
  3881. this.set(
  3882. 1, 0, 0, x.x,
  3883. 0, 1, 0, x.y,
  3884. 0, 0, 1, x.z,
  3885. 0, 0, 0, 1
  3886. );
  3887. } else {
  3888. this.set(
  3889. 1, 0, 0, x,
  3890. 0, 1, 0, y,
  3891. 0, 0, 1, z,
  3892. 0, 0, 0, 1
  3893. );
  3894. }
  3895. return this;
  3896. }
  3897. makeRotationX( theta ) {
  3898. const c = Math.cos( theta ), s = Math.sin( theta );
  3899. this.set(
  3900. 1, 0, 0, 0,
  3901. 0, c, - s, 0,
  3902. 0, s, c, 0,
  3903. 0, 0, 0, 1
  3904. );
  3905. return this;
  3906. }
  3907. makeRotationY( theta ) {
  3908. const c = Math.cos( theta ), s = Math.sin( theta );
  3909. this.set(
  3910. c, 0, s, 0,
  3911. 0, 1, 0, 0,
  3912. - s, 0, c, 0,
  3913. 0, 0, 0, 1
  3914. );
  3915. return this;
  3916. }
  3917. makeRotationZ( theta ) {
  3918. const c = Math.cos( theta ), s = Math.sin( theta );
  3919. this.set(
  3920. c, - s, 0, 0,
  3921. s, c, 0, 0,
  3922. 0, 0, 1, 0,
  3923. 0, 0, 0, 1
  3924. );
  3925. return this;
  3926. }
  3927. makeRotationAxis( axis, angle ) {
  3928. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3929. const c = Math.cos( angle );
  3930. const s = Math.sin( angle );
  3931. const t = 1 - c;
  3932. const x = axis.x, y = axis.y, z = axis.z;
  3933. const tx = t * x, ty = t * y;
  3934. this.set(
  3935. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3936. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3937. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3938. 0, 0, 0, 1
  3939. );
  3940. return this;
  3941. }
  3942. makeScale( x, y, z ) {
  3943. this.set(
  3944. x, 0, 0, 0,
  3945. 0, y, 0, 0,
  3946. 0, 0, z, 0,
  3947. 0, 0, 0, 1
  3948. );
  3949. return this;
  3950. }
  3951. makeShear( xy, xz, yx, yz, zx, zy ) {
  3952. this.set(
  3953. 1, yx, zx, 0,
  3954. xy, 1, zy, 0,
  3955. xz, yz, 1, 0,
  3956. 0, 0, 0, 1
  3957. );
  3958. return this;
  3959. }
  3960. compose( position, quaternion, scale ) {
  3961. const te = this.elements;
  3962. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3963. const x2 = x + x, y2 = y + y, z2 = z + z;
  3964. const xx = x * x2, xy = x * y2, xz = x * z2;
  3965. const yy = y * y2, yz = y * z2, zz = z * z2;
  3966. const wx = w * x2, wy = w * y2, wz = w * z2;
  3967. const sx = scale.x, sy = scale.y, sz = scale.z;
  3968. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3969. te[ 1 ] = ( xy + wz ) * sx;
  3970. te[ 2 ] = ( xz - wy ) * sx;
  3971. te[ 3 ] = 0;
  3972. te[ 4 ] = ( xy - wz ) * sy;
  3973. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3974. te[ 6 ] = ( yz + wx ) * sy;
  3975. te[ 7 ] = 0;
  3976. te[ 8 ] = ( xz + wy ) * sz;
  3977. te[ 9 ] = ( yz - wx ) * sz;
  3978. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3979. te[ 11 ] = 0;
  3980. te[ 12 ] = position.x;
  3981. te[ 13 ] = position.y;
  3982. te[ 14 ] = position.z;
  3983. te[ 15 ] = 1;
  3984. return this;
  3985. }
  3986. decompose( position, quaternion, scale ) {
  3987. const te = this.elements;
  3988. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3989. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3990. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3991. // if determine is negative, we need to invert one scale
  3992. const det = this.determinant();
  3993. if ( det < 0 ) sx = - sx;
  3994. position.x = te[ 12 ];
  3995. position.y = te[ 13 ];
  3996. position.z = te[ 14 ];
  3997. // scale the rotation part
  3998. _m1$2.copy( this );
  3999. const invSX = 1 / sx;
  4000. const invSY = 1 / sy;
  4001. const invSZ = 1 / sz;
  4002. _m1$2.elements[ 0 ] *= invSX;
  4003. _m1$2.elements[ 1 ] *= invSX;
  4004. _m1$2.elements[ 2 ] *= invSX;
  4005. _m1$2.elements[ 4 ] *= invSY;
  4006. _m1$2.elements[ 5 ] *= invSY;
  4007. _m1$2.elements[ 6 ] *= invSY;
  4008. _m1$2.elements[ 8 ] *= invSZ;
  4009. _m1$2.elements[ 9 ] *= invSZ;
  4010. _m1$2.elements[ 10 ] *= invSZ;
  4011. quaternion.setFromRotationMatrix( _m1$2 );
  4012. scale.x = sx;
  4013. scale.y = sy;
  4014. scale.z = sz;
  4015. return this;
  4016. }
  4017. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4018. const te = this.elements;
  4019. const x = 2 * near / ( right - left );
  4020. const y = 2 * near / ( top - bottom );
  4021. const a = ( right + left ) / ( right - left );
  4022. const b = ( top + bottom ) / ( top - bottom );
  4023. let c, d;
  4024. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4025. c = - ( far + near ) / ( far - near );
  4026. d = ( - 2 * far * near ) / ( far - near );
  4027. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4028. c = - far / ( far - near );
  4029. d = ( - far * near ) / ( far - near );
  4030. } else {
  4031. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4032. }
  4033. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4034. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4035. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4036. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4037. return this;
  4038. }
  4039. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4040. const te = this.elements;
  4041. const w = 1.0 / ( right - left );
  4042. const h = 1.0 / ( top - bottom );
  4043. const p = 1.0 / ( far - near );
  4044. const x = ( right + left ) * w;
  4045. const y = ( top + bottom ) * h;
  4046. let z, zInv;
  4047. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4048. z = ( far + near ) * p;
  4049. zInv = - 2 * p;
  4050. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4051. z = near * p;
  4052. zInv = - 1 * p;
  4053. } else {
  4054. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4055. }
  4056. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4057. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4058. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4059. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4060. return this;
  4061. }
  4062. equals( matrix ) {
  4063. const te = this.elements;
  4064. const me = matrix.elements;
  4065. for ( let i = 0; i < 16; i ++ ) {
  4066. if ( te[ i ] !== me[ i ] ) return false;
  4067. }
  4068. return true;
  4069. }
  4070. fromArray( array, offset = 0 ) {
  4071. for ( let i = 0; i < 16; i ++ ) {
  4072. this.elements[ i ] = array[ i + offset ];
  4073. }
  4074. return this;
  4075. }
  4076. toArray( array = [], offset = 0 ) {
  4077. const te = this.elements;
  4078. array[ offset ] = te[ 0 ];
  4079. array[ offset + 1 ] = te[ 1 ];
  4080. array[ offset + 2 ] = te[ 2 ];
  4081. array[ offset + 3 ] = te[ 3 ];
  4082. array[ offset + 4 ] = te[ 4 ];
  4083. array[ offset + 5 ] = te[ 5 ];
  4084. array[ offset + 6 ] = te[ 6 ];
  4085. array[ offset + 7 ] = te[ 7 ];
  4086. array[ offset + 8 ] = te[ 8 ];
  4087. array[ offset + 9 ] = te[ 9 ];
  4088. array[ offset + 10 ] = te[ 10 ];
  4089. array[ offset + 11 ] = te[ 11 ];
  4090. array[ offset + 12 ] = te[ 12 ];
  4091. array[ offset + 13 ] = te[ 13 ];
  4092. array[ offset + 14 ] = te[ 14 ];
  4093. array[ offset + 15 ] = te[ 15 ];
  4094. return array;
  4095. }
  4096. }
  4097. const _v1$5 = /*@__PURE__*/ new Vector3();
  4098. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4099. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4100. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4101. const _x = /*@__PURE__*/ new Vector3();
  4102. const _y = /*@__PURE__*/ new Vector3();
  4103. const _z = /*@__PURE__*/ new Vector3();
  4104. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4105. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4106. class Euler {
  4107. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4108. this.isEuler = true;
  4109. this._x = x;
  4110. this._y = y;
  4111. this._z = z;
  4112. this._order = order;
  4113. }
  4114. get x() {
  4115. return this._x;
  4116. }
  4117. set x( value ) {
  4118. this._x = value;
  4119. this._onChangeCallback();
  4120. }
  4121. get y() {
  4122. return this._y;
  4123. }
  4124. set y( value ) {
  4125. this._y = value;
  4126. this._onChangeCallback();
  4127. }
  4128. get z() {
  4129. return this._z;
  4130. }
  4131. set z( value ) {
  4132. this._z = value;
  4133. this._onChangeCallback();
  4134. }
  4135. get order() {
  4136. return this._order;
  4137. }
  4138. set order( value ) {
  4139. this._order = value;
  4140. this._onChangeCallback();
  4141. }
  4142. set( x, y, z, order = this._order ) {
  4143. this._x = x;
  4144. this._y = y;
  4145. this._z = z;
  4146. this._order = order;
  4147. this._onChangeCallback();
  4148. return this;
  4149. }
  4150. clone() {
  4151. return new this.constructor( this._x, this._y, this._z, this._order );
  4152. }
  4153. copy( euler ) {
  4154. this._x = euler._x;
  4155. this._y = euler._y;
  4156. this._z = euler._z;
  4157. this._order = euler._order;
  4158. this._onChangeCallback();
  4159. return this;
  4160. }
  4161. setFromRotationMatrix( m, order = this._order, update = true ) {
  4162. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4163. const te = m.elements;
  4164. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4165. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4166. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4167. switch ( order ) {
  4168. case 'XYZ':
  4169. this._y = Math.asin( clamp$1( m13, - 1, 1 ) );
  4170. if ( Math.abs( m13 ) < 0.9999999 ) {
  4171. this._x = Math.atan2( - m23, m33 );
  4172. this._z = Math.atan2( - m12, m11 );
  4173. } else {
  4174. this._x = Math.atan2( m32, m22 );
  4175. this._z = 0;
  4176. }
  4177. break;
  4178. case 'YXZ':
  4179. this._x = Math.asin( - clamp$1( m23, - 1, 1 ) );
  4180. if ( Math.abs( m23 ) < 0.9999999 ) {
  4181. this._y = Math.atan2( m13, m33 );
  4182. this._z = Math.atan2( m21, m22 );
  4183. } else {
  4184. this._y = Math.atan2( - m31, m11 );
  4185. this._z = 0;
  4186. }
  4187. break;
  4188. case 'ZXY':
  4189. this._x = Math.asin( clamp$1( m32, - 1, 1 ) );
  4190. if ( Math.abs( m32 ) < 0.9999999 ) {
  4191. this._y = Math.atan2( - m31, m33 );
  4192. this._z = Math.atan2( - m12, m22 );
  4193. } else {
  4194. this._y = 0;
  4195. this._z = Math.atan2( m21, m11 );
  4196. }
  4197. break;
  4198. case 'ZYX':
  4199. this._y = Math.asin( - clamp$1( m31, - 1, 1 ) );
  4200. if ( Math.abs( m31 ) < 0.9999999 ) {
  4201. this._x = Math.atan2( m32, m33 );
  4202. this._z = Math.atan2( m21, m11 );
  4203. } else {
  4204. this._x = 0;
  4205. this._z = Math.atan2( - m12, m22 );
  4206. }
  4207. break;
  4208. case 'YZX':
  4209. this._z = Math.asin( clamp$1( m21, - 1, 1 ) );
  4210. if ( Math.abs( m21 ) < 0.9999999 ) {
  4211. this._x = Math.atan2( - m23, m22 );
  4212. this._y = Math.atan2( - m31, m11 );
  4213. } else {
  4214. this._x = 0;
  4215. this._y = Math.atan2( m13, m33 );
  4216. }
  4217. break;
  4218. case 'XZY':
  4219. this._z = Math.asin( - clamp$1( m12, - 1, 1 ) );
  4220. if ( Math.abs( m12 ) < 0.9999999 ) {
  4221. this._x = Math.atan2( m32, m22 );
  4222. this._y = Math.atan2( m13, m11 );
  4223. } else {
  4224. this._x = Math.atan2( - m23, m33 );
  4225. this._y = 0;
  4226. }
  4227. break;
  4228. default:
  4229. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4230. }
  4231. this._order = order;
  4232. if ( update === true ) this._onChangeCallback();
  4233. return this;
  4234. }
  4235. setFromQuaternion( q, order, update ) {
  4236. _matrix$2.makeRotationFromQuaternion( q );
  4237. return this.setFromRotationMatrix( _matrix$2, order, update );
  4238. }
  4239. setFromVector3( v, order = this._order ) {
  4240. return this.set( v.x, v.y, v.z, order );
  4241. }
  4242. reorder( newOrder ) {
  4243. // WARNING: this discards revolution information -bhouston
  4244. _quaternion$3.setFromEuler( this );
  4245. return this.setFromQuaternion( _quaternion$3, newOrder );
  4246. }
  4247. equals( euler ) {
  4248. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4249. }
  4250. fromArray( array ) {
  4251. this._x = array[ 0 ];
  4252. this._y = array[ 1 ];
  4253. this._z = array[ 2 ];
  4254. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4255. this._onChangeCallback();
  4256. return this;
  4257. }
  4258. toArray( array = [], offset = 0 ) {
  4259. array[ offset ] = this._x;
  4260. array[ offset + 1 ] = this._y;
  4261. array[ offset + 2 ] = this._z;
  4262. array[ offset + 3 ] = this._order;
  4263. return array;
  4264. }
  4265. _onChange( callback ) {
  4266. this._onChangeCallback = callback;
  4267. return this;
  4268. }
  4269. _onChangeCallback() {}
  4270. *[ Symbol.iterator ]() {
  4271. yield this._x;
  4272. yield this._y;
  4273. yield this._z;
  4274. yield this._order;
  4275. }
  4276. }
  4277. Euler.DEFAULT_ORDER = 'XYZ';
  4278. class Layers {
  4279. constructor() {
  4280. this.mask = 1 | 0;
  4281. }
  4282. set( channel ) {
  4283. this.mask = ( 1 << channel | 0 ) >>> 0;
  4284. }
  4285. enable( channel ) {
  4286. this.mask |= 1 << channel | 0;
  4287. }
  4288. enableAll() {
  4289. this.mask = 0xffffffff | 0;
  4290. }
  4291. toggle( channel ) {
  4292. this.mask ^= 1 << channel | 0;
  4293. }
  4294. disable( channel ) {
  4295. this.mask &= ~ ( 1 << channel | 0 );
  4296. }
  4297. disableAll() {
  4298. this.mask = 0;
  4299. }
  4300. test( layers ) {
  4301. return ( this.mask & layers.mask ) !== 0;
  4302. }
  4303. isEnabled( channel ) {
  4304. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4305. }
  4306. }
  4307. let _object3DId = 0;
  4308. const _v1$4 = /*@__PURE__*/ new Vector3();
  4309. const _q1 = /*@__PURE__*/ new Quaternion();
  4310. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4311. const _target$1 = /*@__PURE__*/ new Vector3();
  4312. const _position$3 = /*@__PURE__*/ new Vector3();
  4313. const _scale$2 = /*@__PURE__*/ new Vector3();
  4314. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4315. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4316. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4317. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4318. const _addedEvent = { type: 'added' };
  4319. const _removedEvent = { type: 'removed' };
  4320. const _childaddedEvent = { type: 'childadded', child: null };
  4321. const _childremovedEvent = { type: 'childremoved', child: null };
  4322. class Object3D extends EventDispatcher {
  4323. constructor() {
  4324. super();
  4325. this.isObject3D = true;
  4326. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4327. this.uuid = generateUUID();
  4328. this.name = '';
  4329. this.type = 'Object3D';
  4330. this.parent = null;
  4331. this.children = [];
  4332. this.up = Object3D.DEFAULT_UP.clone();
  4333. const position = new Vector3();
  4334. const rotation = new Euler();
  4335. const quaternion = new Quaternion();
  4336. const scale = new Vector3( 1, 1, 1 );
  4337. function onRotationChange() {
  4338. quaternion.setFromEuler( rotation, false );
  4339. }
  4340. function onQuaternionChange() {
  4341. rotation.setFromQuaternion( quaternion, undefined, false );
  4342. }
  4343. rotation._onChange( onRotationChange );
  4344. quaternion._onChange( onQuaternionChange );
  4345. Object.defineProperties( this, {
  4346. position: {
  4347. configurable: true,
  4348. enumerable: true,
  4349. value: position
  4350. },
  4351. rotation: {
  4352. configurable: true,
  4353. enumerable: true,
  4354. value: rotation
  4355. },
  4356. quaternion: {
  4357. configurable: true,
  4358. enumerable: true,
  4359. value: quaternion
  4360. },
  4361. scale: {
  4362. configurable: true,
  4363. enumerable: true,
  4364. value: scale
  4365. },
  4366. modelViewMatrix: {
  4367. value: new Matrix4()
  4368. },
  4369. normalMatrix: {
  4370. value: new Matrix3()
  4371. }
  4372. } );
  4373. this.matrix = new Matrix4();
  4374. this.matrixWorld = new Matrix4();
  4375. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4376. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4377. this.matrixWorldNeedsUpdate = false;
  4378. this.layers = new Layers();
  4379. this.visible = true;
  4380. this.castShadow = false;
  4381. this.receiveShadow = false;
  4382. this.frustumCulled = true;
  4383. this.renderOrder = 0;
  4384. this.animations = [];
  4385. this.userData = {};
  4386. }
  4387. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4388. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4389. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4390. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4391. applyMatrix4( matrix ) {
  4392. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4393. this.matrix.premultiply( matrix );
  4394. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4395. }
  4396. applyQuaternion( q ) {
  4397. this.quaternion.premultiply( q );
  4398. return this;
  4399. }
  4400. setRotationFromAxisAngle( axis, angle ) {
  4401. // assumes axis is normalized
  4402. this.quaternion.setFromAxisAngle( axis, angle );
  4403. }
  4404. setRotationFromEuler( euler ) {
  4405. this.quaternion.setFromEuler( euler, true );
  4406. }
  4407. setRotationFromMatrix( m ) {
  4408. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4409. this.quaternion.setFromRotationMatrix( m );
  4410. }
  4411. setRotationFromQuaternion( q ) {
  4412. // assumes q is normalized
  4413. this.quaternion.copy( q );
  4414. }
  4415. rotateOnAxis( axis, angle ) {
  4416. // rotate object on axis in object space
  4417. // axis is assumed to be normalized
  4418. _q1.setFromAxisAngle( axis, angle );
  4419. this.quaternion.multiply( _q1 );
  4420. return this;
  4421. }
  4422. rotateOnWorldAxis( axis, angle ) {
  4423. // rotate object on axis in world space
  4424. // axis is assumed to be normalized
  4425. // method assumes no rotated parent
  4426. _q1.setFromAxisAngle( axis, angle );
  4427. this.quaternion.premultiply( _q1 );
  4428. return this;
  4429. }
  4430. rotateX( angle ) {
  4431. return this.rotateOnAxis( _xAxis, angle );
  4432. }
  4433. rotateY( angle ) {
  4434. return this.rotateOnAxis( _yAxis, angle );
  4435. }
  4436. rotateZ( angle ) {
  4437. return this.rotateOnAxis( _zAxis, angle );
  4438. }
  4439. translateOnAxis( axis, distance ) {
  4440. // translate object by distance along axis in object space
  4441. // axis is assumed to be normalized
  4442. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4443. this.position.add( _v1$4.multiplyScalar( distance ) );
  4444. return this;
  4445. }
  4446. translateX( distance ) {
  4447. return this.translateOnAxis( _xAxis, distance );
  4448. }
  4449. translateY( distance ) {
  4450. return this.translateOnAxis( _yAxis, distance );
  4451. }
  4452. translateZ( distance ) {
  4453. return this.translateOnAxis( _zAxis, distance );
  4454. }
  4455. localToWorld( vector ) {
  4456. this.updateWorldMatrix( true, false );
  4457. return vector.applyMatrix4( this.matrixWorld );
  4458. }
  4459. worldToLocal( vector ) {
  4460. this.updateWorldMatrix( true, false );
  4461. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4462. }
  4463. lookAt( x, y, z ) {
  4464. // This method does not support objects having non-uniformly-scaled parent(s)
  4465. if ( x.isVector3 ) {
  4466. _target$1.copy( x );
  4467. } else {
  4468. _target$1.set( x, y, z );
  4469. }
  4470. const parent = this.parent;
  4471. this.updateWorldMatrix( true, false );
  4472. _position$3.setFromMatrixPosition( this.matrixWorld );
  4473. if ( this.isCamera || this.isLight ) {
  4474. _m1$1.lookAt( _position$3, _target$1, this.up );
  4475. } else {
  4476. _m1$1.lookAt( _target$1, _position$3, this.up );
  4477. }
  4478. this.quaternion.setFromRotationMatrix( _m1$1 );
  4479. if ( parent ) {
  4480. _m1$1.extractRotation( parent.matrixWorld );
  4481. _q1.setFromRotationMatrix( _m1$1 );
  4482. this.quaternion.premultiply( _q1.invert() );
  4483. }
  4484. }
  4485. add( object ) {
  4486. if ( arguments.length > 1 ) {
  4487. for ( let i = 0; i < arguments.length; i ++ ) {
  4488. this.add( arguments[ i ] );
  4489. }
  4490. return this;
  4491. }
  4492. if ( object === this ) {
  4493. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4494. return this;
  4495. }
  4496. if ( object && object.isObject3D ) {
  4497. object.removeFromParent();
  4498. object.parent = this;
  4499. this.children.push( object );
  4500. object.dispatchEvent( _addedEvent );
  4501. _childaddedEvent.child = object;
  4502. this.dispatchEvent( _childaddedEvent );
  4503. _childaddedEvent.child = null;
  4504. } else {
  4505. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4506. }
  4507. return this;
  4508. }
  4509. remove( object ) {
  4510. if ( arguments.length > 1 ) {
  4511. for ( let i = 0; i < arguments.length; i ++ ) {
  4512. this.remove( arguments[ i ] );
  4513. }
  4514. return this;
  4515. }
  4516. const index = this.children.indexOf( object );
  4517. if ( index !== - 1 ) {
  4518. object.parent = null;
  4519. this.children.splice( index, 1 );
  4520. object.dispatchEvent( _removedEvent );
  4521. _childremovedEvent.child = object;
  4522. this.dispatchEvent( _childremovedEvent );
  4523. _childremovedEvent.child = null;
  4524. }
  4525. return this;
  4526. }
  4527. removeFromParent() {
  4528. const parent = this.parent;
  4529. if ( parent !== null ) {
  4530. parent.remove( this );
  4531. }
  4532. return this;
  4533. }
  4534. clear() {
  4535. return this.remove( ... this.children );
  4536. }
  4537. attach( object ) {
  4538. // adds object as a child of this, while maintaining the object's world transform
  4539. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4540. this.updateWorldMatrix( true, false );
  4541. _m1$1.copy( this.matrixWorld ).invert();
  4542. if ( object.parent !== null ) {
  4543. object.parent.updateWorldMatrix( true, false );
  4544. _m1$1.multiply( object.parent.matrixWorld );
  4545. }
  4546. object.applyMatrix4( _m1$1 );
  4547. object.removeFromParent();
  4548. object.parent = this;
  4549. this.children.push( object );
  4550. object.updateWorldMatrix( false, true );
  4551. object.dispatchEvent( _addedEvent );
  4552. _childaddedEvent.child = object;
  4553. this.dispatchEvent( _childaddedEvent );
  4554. _childaddedEvent.child = null;
  4555. return this;
  4556. }
  4557. getObjectById( id ) {
  4558. return this.getObjectByProperty( 'id', id );
  4559. }
  4560. getObjectByName( name ) {
  4561. return this.getObjectByProperty( 'name', name );
  4562. }
  4563. getObjectByProperty( name, value ) {
  4564. if ( this[ name ] === value ) return this;
  4565. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4566. const child = this.children[ i ];
  4567. const object = child.getObjectByProperty( name, value );
  4568. if ( object !== undefined ) {
  4569. return object;
  4570. }
  4571. }
  4572. return undefined;
  4573. }
  4574. getObjectsByProperty( name, value, result = [] ) {
  4575. if ( this[ name ] === value ) result.push( this );
  4576. const children = this.children;
  4577. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4578. children[ i ].getObjectsByProperty( name, value, result );
  4579. }
  4580. return result;
  4581. }
  4582. getWorldPosition( target ) {
  4583. this.updateWorldMatrix( true, false );
  4584. return target.setFromMatrixPosition( this.matrixWorld );
  4585. }
  4586. getWorldQuaternion( target ) {
  4587. this.updateWorldMatrix( true, false );
  4588. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4589. return target;
  4590. }
  4591. getWorldScale( target ) {
  4592. this.updateWorldMatrix( true, false );
  4593. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4594. return target;
  4595. }
  4596. getWorldDirection( target ) {
  4597. this.updateWorldMatrix( true, false );
  4598. const e = this.matrixWorld.elements;
  4599. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4600. }
  4601. raycast( /* raycaster, intersects */ ) {}
  4602. traverse( callback ) {
  4603. callback( this );
  4604. const children = this.children;
  4605. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4606. children[ i ].traverse( callback );
  4607. }
  4608. }
  4609. traverseVisible( callback ) {
  4610. if ( this.visible === false ) return;
  4611. callback( this );
  4612. const children = this.children;
  4613. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4614. children[ i ].traverseVisible( callback );
  4615. }
  4616. }
  4617. traverseAncestors( callback ) {
  4618. const parent = this.parent;
  4619. if ( parent !== null ) {
  4620. callback( parent );
  4621. parent.traverseAncestors( callback );
  4622. }
  4623. }
  4624. updateMatrix() {
  4625. this.matrix.compose( this.position, this.quaternion, this.scale );
  4626. this.matrixWorldNeedsUpdate = true;
  4627. }
  4628. updateMatrixWorld( force ) {
  4629. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4630. if ( this.matrixWorldNeedsUpdate || force ) {
  4631. if ( this.matrixWorldAutoUpdate === true ) {
  4632. if ( this.parent === null ) {
  4633. this.matrixWorld.copy( this.matrix );
  4634. } else {
  4635. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4636. }
  4637. }
  4638. this.matrixWorldNeedsUpdate = false;
  4639. force = true;
  4640. }
  4641. // make sure descendants are updated if required
  4642. const children = this.children;
  4643. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4644. const child = children[ i ];
  4645. child.updateMatrixWorld( force );
  4646. }
  4647. }
  4648. updateWorldMatrix( updateParents, updateChildren ) {
  4649. const parent = this.parent;
  4650. if ( updateParents === true && parent !== null ) {
  4651. parent.updateWorldMatrix( true, false );
  4652. }
  4653. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4654. if ( this.matrixWorldAutoUpdate === true ) {
  4655. if ( this.parent === null ) {
  4656. this.matrixWorld.copy( this.matrix );
  4657. } else {
  4658. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4659. }
  4660. }
  4661. // make sure descendants are updated
  4662. if ( updateChildren === true ) {
  4663. const children = this.children;
  4664. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4665. const child = children[ i ];
  4666. child.updateWorldMatrix( false, true );
  4667. }
  4668. }
  4669. }
  4670. toJSON( meta ) {
  4671. // meta is a string when called from JSON.stringify
  4672. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4673. const output = {};
  4674. // meta is a hash used to collect geometries, materials.
  4675. // not providing it implies that this is the root object
  4676. // being serialized.
  4677. if ( isRootObject ) {
  4678. // initialize meta obj
  4679. meta = {
  4680. geometries: {},
  4681. materials: {},
  4682. textures: {},
  4683. images: {},
  4684. shapes: {},
  4685. skeletons: {},
  4686. animations: {},
  4687. nodes: {}
  4688. };
  4689. output.metadata = {
  4690. version: 4.6,
  4691. type: 'Object',
  4692. generator: 'Object3D.toJSON'
  4693. };
  4694. }
  4695. // standard Object3D serialization
  4696. const object = {};
  4697. object.uuid = this.uuid;
  4698. object.type = this.type;
  4699. if ( this.name !== '' ) object.name = this.name;
  4700. if ( this.castShadow === true ) object.castShadow = true;
  4701. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4702. if ( this.visible === false ) object.visible = false;
  4703. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4704. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4705. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4706. object.layers = this.layers.mask;
  4707. object.matrix = this.matrix.toArray();
  4708. object.up = this.up.toArray();
  4709. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4710. // object specific properties
  4711. if ( this.isInstancedMesh ) {
  4712. object.type = 'InstancedMesh';
  4713. object.count = this.count;
  4714. object.instanceMatrix = this.instanceMatrix.toJSON();
  4715. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4716. }
  4717. if ( this.isBatchedMesh ) {
  4718. object.type = 'BatchedMesh';
  4719. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4720. object.sortObjects = this.sortObjects;
  4721. object.drawRanges = this._drawRanges;
  4722. object.reservedRanges = this._reservedRanges;
  4723. object.visibility = this._visibility;
  4724. object.active = this._active;
  4725. object.bounds = this._bounds.map( bound => ( {
  4726. boxInitialized: bound.boxInitialized,
  4727. boxMin: bound.box.min.toArray(),
  4728. boxMax: bound.box.max.toArray(),
  4729. sphereInitialized: bound.sphereInitialized,
  4730. sphereRadius: bound.sphere.radius,
  4731. sphereCenter: bound.sphere.center.toArray()
  4732. } ) );
  4733. object.maxInstanceCount = this._maxInstanceCount;
  4734. object.maxVertexCount = this._maxVertexCount;
  4735. object.maxIndexCount = this._maxIndexCount;
  4736. object.geometryInitialized = this._geometryInitialized;
  4737. object.geometryCount = this._geometryCount;
  4738. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4739. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4740. if ( this.boundingSphere !== null ) {
  4741. object.boundingSphere = {
  4742. center: object.boundingSphere.center.toArray(),
  4743. radius: object.boundingSphere.radius
  4744. };
  4745. }
  4746. if ( this.boundingBox !== null ) {
  4747. object.boundingBox = {
  4748. min: object.boundingBox.min.toArray(),
  4749. max: object.boundingBox.max.toArray()
  4750. };
  4751. }
  4752. }
  4753. //
  4754. function serialize( library, element ) {
  4755. if ( library[ element.uuid ] === undefined ) {
  4756. library[ element.uuid ] = element.toJSON( meta );
  4757. }
  4758. return element.uuid;
  4759. }
  4760. if ( this.isScene ) {
  4761. if ( this.background ) {
  4762. if ( this.background.isColor ) {
  4763. object.background = this.background.toJSON();
  4764. } else if ( this.background.isTexture ) {
  4765. object.background = this.background.toJSON( meta ).uuid;
  4766. }
  4767. }
  4768. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4769. object.environment = this.environment.toJSON( meta ).uuid;
  4770. }
  4771. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4772. object.geometry = serialize( meta.geometries, this.geometry );
  4773. const parameters = this.geometry.parameters;
  4774. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4775. const shapes = parameters.shapes;
  4776. if ( Array.isArray( shapes ) ) {
  4777. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4778. const shape = shapes[ i ];
  4779. serialize( meta.shapes, shape );
  4780. }
  4781. } else {
  4782. serialize( meta.shapes, shapes );
  4783. }
  4784. }
  4785. }
  4786. if ( this.isSkinnedMesh ) {
  4787. object.bindMode = this.bindMode;
  4788. object.bindMatrix = this.bindMatrix.toArray();
  4789. if ( this.skeleton !== undefined ) {
  4790. serialize( meta.skeletons, this.skeleton );
  4791. object.skeleton = this.skeleton.uuid;
  4792. }
  4793. }
  4794. if ( this.material !== undefined ) {
  4795. if ( Array.isArray( this.material ) ) {
  4796. const uuids = [];
  4797. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4798. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4799. }
  4800. object.material = uuids;
  4801. } else {
  4802. object.material = serialize( meta.materials, this.material );
  4803. }
  4804. }
  4805. //
  4806. if ( this.children.length > 0 ) {
  4807. object.children = [];
  4808. for ( let i = 0; i < this.children.length; i ++ ) {
  4809. object.children.push( this.children[ i ].toJSON( meta ).object );
  4810. }
  4811. }
  4812. //
  4813. if ( this.animations.length > 0 ) {
  4814. object.animations = [];
  4815. for ( let i = 0; i < this.animations.length; i ++ ) {
  4816. const animation = this.animations[ i ];
  4817. object.animations.push( serialize( meta.animations, animation ) );
  4818. }
  4819. }
  4820. if ( isRootObject ) {
  4821. const geometries = extractFromCache( meta.geometries );
  4822. const materials = extractFromCache( meta.materials );
  4823. const textures = extractFromCache( meta.textures );
  4824. const images = extractFromCache( meta.images );
  4825. const shapes = extractFromCache( meta.shapes );
  4826. const skeletons = extractFromCache( meta.skeletons );
  4827. const animations = extractFromCache( meta.animations );
  4828. const nodes = extractFromCache( meta.nodes );
  4829. if ( geometries.length > 0 ) output.geometries = geometries;
  4830. if ( materials.length > 0 ) output.materials = materials;
  4831. if ( textures.length > 0 ) output.textures = textures;
  4832. if ( images.length > 0 ) output.images = images;
  4833. if ( shapes.length > 0 ) output.shapes = shapes;
  4834. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4835. if ( animations.length > 0 ) output.animations = animations;
  4836. if ( nodes.length > 0 ) output.nodes = nodes;
  4837. }
  4838. output.object = object;
  4839. return output;
  4840. // extract data from the cache hash
  4841. // remove metadata on each item
  4842. // and return as array
  4843. function extractFromCache( cache ) {
  4844. const values = [];
  4845. for ( const key in cache ) {
  4846. const data = cache[ key ];
  4847. delete data.metadata;
  4848. values.push( data );
  4849. }
  4850. return values;
  4851. }
  4852. }
  4853. clone( recursive ) {
  4854. return new this.constructor().copy( this, recursive );
  4855. }
  4856. copy( source, recursive = true ) {
  4857. this.name = source.name;
  4858. this.up.copy( source.up );
  4859. this.position.copy( source.position );
  4860. this.rotation.order = source.rotation.order;
  4861. this.quaternion.copy( source.quaternion );
  4862. this.scale.copy( source.scale );
  4863. this.matrix.copy( source.matrix );
  4864. this.matrixWorld.copy( source.matrixWorld );
  4865. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4866. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4867. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4868. this.layers.mask = source.layers.mask;
  4869. this.visible = source.visible;
  4870. this.castShadow = source.castShadow;
  4871. this.receiveShadow = source.receiveShadow;
  4872. this.frustumCulled = source.frustumCulled;
  4873. this.renderOrder = source.renderOrder;
  4874. this.animations = source.animations.slice();
  4875. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4876. if ( recursive === true ) {
  4877. for ( let i = 0; i < source.children.length; i ++ ) {
  4878. const child = source.children[ i ];
  4879. this.add( child.clone() );
  4880. }
  4881. }
  4882. return this;
  4883. }
  4884. }
  4885. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4886. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4887. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4888. const _v0$1 = /*@__PURE__*/ new Vector3();
  4889. const _v1$3 = /*@__PURE__*/ new Vector3();
  4890. const _v2$2 = /*@__PURE__*/ new Vector3();
  4891. const _v3$2 = /*@__PURE__*/ new Vector3();
  4892. const _vab = /*@__PURE__*/ new Vector3();
  4893. const _vac = /*@__PURE__*/ new Vector3();
  4894. const _vbc = /*@__PURE__*/ new Vector3();
  4895. const _vap = /*@__PURE__*/ new Vector3();
  4896. const _vbp = /*@__PURE__*/ new Vector3();
  4897. const _vcp = /*@__PURE__*/ new Vector3();
  4898. const _v40 = /*@__PURE__*/ new Vector4();
  4899. const _v41 = /*@__PURE__*/ new Vector4();
  4900. const _v42 = /*@__PURE__*/ new Vector4();
  4901. class Triangle {
  4902. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4903. this.a = a;
  4904. this.b = b;
  4905. this.c = c;
  4906. }
  4907. static getNormal( a, b, c, target ) {
  4908. target.subVectors( c, b );
  4909. _v0$1.subVectors( a, b );
  4910. target.cross( _v0$1 );
  4911. const targetLengthSq = target.lengthSq();
  4912. if ( targetLengthSq > 0 ) {
  4913. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4914. }
  4915. return target.set( 0, 0, 0 );
  4916. }
  4917. // static/instance method to calculate barycentric coordinates
  4918. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4919. static getBarycoord( point, a, b, c, target ) {
  4920. _v0$1.subVectors( c, a );
  4921. _v1$3.subVectors( b, a );
  4922. _v2$2.subVectors( point, a );
  4923. const dot00 = _v0$1.dot( _v0$1 );
  4924. const dot01 = _v0$1.dot( _v1$3 );
  4925. const dot02 = _v0$1.dot( _v2$2 );
  4926. const dot11 = _v1$3.dot( _v1$3 );
  4927. const dot12 = _v1$3.dot( _v2$2 );
  4928. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4929. // collinear or singular triangle
  4930. if ( denom === 0 ) {
  4931. target.set( 0, 0, 0 );
  4932. return null;
  4933. }
  4934. const invDenom = 1 / denom;
  4935. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4936. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4937. // barycentric coordinates must always sum to 1
  4938. return target.set( 1 - u - v, v, u );
  4939. }
  4940. static containsPoint( point, a, b, c ) {
  4941. // if the triangle is degenerate then we can't contain a point
  4942. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4943. return false;
  4944. }
  4945. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4946. }
  4947. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4948. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4949. target.x = 0;
  4950. target.y = 0;
  4951. if ( 'z' in target ) target.z = 0;
  4952. if ( 'w' in target ) target.w = 0;
  4953. return null;
  4954. }
  4955. target.setScalar( 0 );
  4956. target.addScaledVector( v1, _v3$2.x );
  4957. target.addScaledVector( v2, _v3$2.y );
  4958. target.addScaledVector( v3, _v3$2.z );
  4959. return target;
  4960. }
  4961. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  4962. _v40.setScalar( 0 );
  4963. _v41.setScalar( 0 );
  4964. _v42.setScalar( 0 );
  4965. _v40.fromBufferAttribute( attr, i1 );
  4966. _v41.fromBufferAttribute( attr, i2 );
  4967. _v42.fromBufferAttribute( attr, i3 );
  4968. target.setScalar( 0 );
  4969. target.addScaledVector( _v40, barycoord.x );
  4970. target.addScaledVector( _v41, barycoord.y );
  4971. target.addScaledVector( _v42, barycoord.z );
  4972. return target;
  4973. }
  4974. static isFrontFacing( a, b, c, direction ) {
  4975. _v0$1.subVectors( c, b );
  4976. _v1$3.subVectors( a, b );
  4977. // strictly front facing
  4978. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4979. }
  4980. set( a, b, c ) {
  4981. this.a.copy( a );
  4982. this.b.copy( b );
  4983. this.c.copy( c );
  4984. return this;
  4985. }
  4986. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4987. this.a.copy( points[ i0 ] );
  4988. this.b.copy( points[ i1 ] );
  4989. this.c.copy( points[ i2 ] );
  4990. return this;
  4991. }
  4992. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4993. this.a.fromBufferAttribute( attribute, i0 );
  4994. this.b.fromBufferAttribute( attribute, i1 );
  4995. this.c.fromBufferAttribute( attribute, i2 );
  4996. return this;
  4997. }
  4998. clone() {
  4999. return new this.constructor().copy( this );
  5000. }
  5001. copy( triangle ) {
  5002. this.a.copy( triangle.a );
  5003. this.b.copy( triangle.b );
  5004. this.c.copy( triangle.c );
  5005. return this;
  5006. }
  5007. getArea() {
  5008. _v0$1.subVectors( this.c, this.b );
  5009. _v1$3.subVectors( this.a, this.b );
  5010. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5011. }
  5012. getMidpoint( target ) {
  5013. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5014. }
  5015. getNormal( target ) {
  5016. return Triangle.getNormal( this.a, this.b, this.c, target );
  5017. }
  5018. getPlane( target ) {
  5019. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5020. }
  5021. getBarycoord( point, target ) {
  5022. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5023. }
  5024. getInterpolation( point, v1, v2, v3, target ) {
  5025. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5026. }
  5027. containsPoint( point ) {
  5028. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5029. }
  5030. isFrontFacing( direction ) {
  5031. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5032. }
  5033. intersectsBox( box ) {
  5034. return box.intersectsTriangle( this );
  5035. }
  5036. closestPointToPoint( p, target ) {
  5037. const a = this.a, b = this.b, c = this.c;
  5038. let v, w;
  5039. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5040. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5041. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5042. // basically, we're distinguishing which of the voronoi regions of the triangle
  5043. // the point lies in with the minimum amount of redundant computation.
  5044. _vab.subVectors( b, a );
  5045. _vac.subVectors( c, a );
  5046. _vap.subVectors( p, a );
  5047. const d1 = _vab.dot( _vap );
  5048. const d2 = _vac.dot( _vap );
  5049. if ( d1 <= 0 && d2 <= 0 ) {
  5050. // vertex region of A; barycentric coords (1, 0, 0)
  5051. return target.copy( a );
  5052. }
  5053. _vbp.subVectors( p, b );
  5054. const d3 = _vab.dot( _vbp );
  5055. const d4 = _vac.dot( _vbp );
  5056. if ( d3 >= 0 && d4 <= d3 ) {
  5057. // vertex region of B; barycentric coords (0, 1, 0)
  5058. return target.copy( b );
  5059. }
  5060. const vc = d1 * d4 - d3 * d2;
  5061. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5062. v = d1 / ( d1 - d3 );
  5063. // edge region of AB; barycentric coords (1-v, v, 0)
  5064. return target.copy( a ).addScaledVector( _vab, v );
  5065. }
  5066. _vcp.subVectors( p, c );
  5067. const d5 = _vab.dot( _vcp );
  5068. const d6 = _vac.dot( _vcp );
  5069. if ( d6 >= 0 && d5 <= d6 ) {
  5070. // vertex region of C; barycentric coords (0, 0, 1)
  5071. return target.copy( c );
  5072. }
  5073. const vb = d5 * d2 - d1 * d6;
  5074. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5075. w = d2 / ( d2 - d6 );
  5076. // edge region of AC; barycentric coords (1-w, 0, w)
  5077. return target.copy( a ).addScaledVector( _vac, w );
  5078. }
  5079. const va = d3 * d6 - d5 * d4;
  5080. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5081. _vbc.subVectors( c, b );
  5082. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5083. // edge region of BC; barycentric coords (0, 1-w, w)
  5084. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5085. }
  5086. // face region
  5087. const denom = 1 / ( va + vb + vc );
  5088. // u = va * denom
  5089. v = vb * denom;
  5090. w = vc * denom;
  5091. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5092. }
  5093. equals( triangle ) {
  5094. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5095. }
  5096. }
  5097. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5098. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5099. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5100. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5101. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5102. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5103. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5104. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5105. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5106. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5107. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5108. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5109. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5110. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5111. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5112. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5113. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5114. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5115. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5116. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5117. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5118. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5119. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5120. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5121. const _hslA = { h: 0, s: 0, l: 0 };
  5122. const _hslB = { h: 0, s: 0, l: 0 };
  5123. function hue2rgb( p, q, t ) {
  5124. if ( t < 0 ) t += 1;
  5125. if ( t > 1 ) t -= 1;
  5126. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5127. if ( t < 1 / 2 ) return q;
  5128. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5129. return p;
  5130. }
  5131. class Color {
  5132. constructor( r, g, b ) {
  5133. this.isColor = true;
  5134. this.r = 1;
  5135. this.g = 1;
  5136. this.b = 1;
  5137. return this.set( r, g, b );
  5138. }
  5139. set( r, g, b ) {
  5140. if ( g === undefined && b === undefined ) {
  5141. // r is THREE.Color, hex or string
  5142. const value = r;
  5143. if ( value && value.isColor ) {
  5144. this.copy( value );
  5145. } else if ( typeof value === 'number' ) {
  5146. this.setHex( value );
  5147. } else if ( typeof value === 'string' ) {
  5148. this.setStyle( value );
  5149. }
  5150. } else {
  5151. this.setRGB( r, g, b );
  5152. }
  5153. return this;
  5154. }
  5155. setScalar( scalar ) {
  5156. this.r = scalar;
  5157. this.g = scalar;
  5158. this.b = scalar;
  5159. return this;
  5160. }
  5161. setHex( hex, colorSpace = SRGBColorSpace ) {
  5162. hex = Math.floor( hex );
  5163. this.r = ( hex >> 16 & 255 ) / 255;
  5164. this.g = ( hex >> 8 & 255 ) / 255;
  5165. this.b = ( hex & 255 ) / 255;
  5166. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5167. return this;
  5168. }
  5169. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5170. this.r = r;
  5171. this.g = g;
  5172. this.b = b;
  5173. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5174. return this;
  5175. }
  5176. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5177. // h,s,l ranges are in 0.0 - 1.0
  5178. h = euclideanModulo( h, 1 );
  5179. s = clamp$1( s, 0, 1 );
  5180. l = clamp$1( l, 0, 1 );
  5181. if ( s === 0 ) {
  5182. this.r = this.g = this.b = l;
  5183. } else {
  5184. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5185. const q = ( 2 * l ) - p;
  5186. this.r = hue2rgb( q, p, h + 1 / 3 );
  5187. this.g = hue2rgb( q, p, h );
  5188. this.b = hue2rgb( q, p, h - 1 / 3 );
  5189. }
  5190. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5191. return this;
  5192. }
  5193. setStyle( style, colorSpace = SRGBColorSpace ) {
  5194. function handleAlpha( string ) {
  5195. if ( string === undefined ) return;
  5196. if ( parseFloat( string ) < 1 ) {
  5197. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5198. }
  5199. }
  5200. let m;
  5201. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5202. // rgb / hsl
  5203. let color;
  5204. const name = m[ 1 ];
  5205. const components = m[ 2 ];
  5206. switch ( name ) {
  5207. case 'rgb':
  5208. case 'rgba':
  5209. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5210. // rgb(255,0,0) rgba(255,0,0,0.5)
  5211. handleAlpha( color[ 4 ] );
  5212. return this.setRGB(
  5213. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5214. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5215. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5216. colorSpace
  5217. );
  5218. }
  5219. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5220. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5221. handleAlpha( color[ 4 ] );
  5222. return this.setRGB(
  5223. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5224. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5225. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5226. colorSpace
  5227. );
  5228. }
  5229. break;
  5230. case 'hsl':
  5231. case 'hsla':
  5232. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5233. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5234. handleAlpha( color[ 4 ] );
  5235. return this.setHSL(
  5236. parseFloat( color[ 1 ] ) / 360,
  5237. parseFloat( color[ 2 ] ) / 100,
  5238. parseFloat( color[ 3 ] ) / 100,
  5239. colorSpace
  5240. );
  5241. }
  5242. break;
  5243. default:
  5244. console.warn( 'THREE.Color: Unknown color model ' + style );
  5245. }
  5246. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5247. // hex color
  5248. const hex = m[ 1 ];
  5249. const size = hex.length;
  5250. if ( size === 3 ) {
  5251. // #ff0
  5252. return this.setRGB(
  5253. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5254. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5255. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5256. colorSpace
  5257. );
  5258. } else if ( size === 6 ) {
  5259. // #ff0000
  5260. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5261. } else {
  5262. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5263. }
  5264. } else if ( style && style.length > 0 ) {
  5265. return this.setColorName( style, colorSpace );
  5266. }
  5267. return this;
  5268. }
  5269. setColorName( style, colorSpace = SRGBColorSpace ) {
  5270. // color keywords
  5271. const hex = _colorKeywords[ style.toLowerCase() ];
  5272. if ( hex !== undefined ) {
  5273. // red
  5274. this.setHex( hex, colorSpace );
  5275. } else {
  5276. // unknown color
  5277. console.warn( 'THREE.Color: Unknown color ' + style );
  5278. }
  5279. return this;
  5280. }
  5281. clone() {
  5282. return new this.constructor( this.r, this.g, this.b );
  5283. }
  5284. copy( color ) {
  5285. this.r = color.r;
  5286. this.g = color.g;
  5287. this.b = color.b;
  5288. return this;
  5289. }
  5290. copySRGBToLinear( color ) {
  5291. this.r = SRGBToLinear( color.r );
  5292. this.g = SRGBToLinear( color.g );
  5293. this.b = SRGBToLinear( color.b );
  5294. return this;
  5295. }
  5296. copyLinearToSRGB( color ) {
  5297. this.r = LinearToSRGB( color.r );
  5298. this.g = LinearToSRGB( color.g );
  5299. this.b = LinearToSRGB( color.b );
  5300. return this;
  5301. }
  5302. convertSRGBToLinear() {
  5303. this.copySRGBToLinear( this );
  5304. return this;
  5305. }
  5306. convertLinearToSRGB() {
  5307. this.copyLinearToSRGB( this );
  5308. return this;
  5309. }
  5310. getHex( colorSpace = SRGBColorSpace ) {
  5311. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5312. return Math.round( clamp$1( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp$1( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp$1( _color.b * 255, 0, 255 ) );
  5313. }
  5314. getHexString( colorSpace = SRGBColorSpace ) {
  5315. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5316. }
  5317. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5318. // h,s,l ranges are in 0.0 - 1.0
  5319. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5320. const r = _color.r, g = _color.g, b = _color.b;
  5321. const max = Math.max( r, g, b );
  5322. const min = Math.min( r, g, b );
  5323. let hue, saturation;
  5324. const lightness = ( min + max ) / 2.0;
  5325. if ( min === max ) {
  5326. hue = 0;
  5327. saturation = 0;
  5328. } else {
  5329. const delta = max - min;
  5330. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5331. switch ( max ) {
  5332. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5333. case g: hue = ( b - r ) / delta + 2; break;
  5334. case b: hue = ( r - g ) / delta + 4; break;
  5335. }
  5336. hue /= 6;
  5337. }
  5338. target.h = hue;
  5339. target.s = saturation;
  5340. target.l = lightness;
  5341. return target;
  5342. }
  5343. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5344. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5345. target.r = _color.r;
  5346. target.g = _color.g;
  5347. target.b = _color.b;
  5348. return target;
  5349. }
  5350. getStyle( colorSpace = SRGBColorSpace ) {
  5351. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5352. const r = _color.r, g = _color.g, b = _color.b;
  5353. if ( colorSpace !== SRGBColorSpace ) {
  5354. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5355. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5356. }
  5357. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5358. }
  5359. offsetHSL( h, s, l ) {
  5360. this.getHSL( _hslA );
  5361. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5362. }
  5363. add( color ) {
  5364. this.r += color.r;
  5365. this.g += color.g;
  5366. this.b += color.b;
  5367. return this;
  5368. }
  5369. addColors( color1, color2 ) {
  5370. this.r = color1.r + color2.r;
  5371. this.g = color1.g + color2.g;
  5372. this.b = color1.b + color2.b;
  5373. return this;
  5374. }
  5375. addScalar( s ) {
  5376. this.r += s;
  5377. this.g += s;
  5378. this.b += s;
  5379. return this;
  5380. }
  5381. sub( color ) {
  5382. this.r = Math.max( 0, this.r - color.r );
  5383. this.g = Math.max( 0, this.g - color.g );
  5384. this.b = Math.max( 0, this.b - color.b );
  5385. return this;
  5386. }
  5387. multiply( color ) {
  5388. this.r *= color.r;
  5389. this.g *= color.g;
  5390. this.b *= color.b;
  5391. return this;
  5392. }
  5393. multiplyScalar( s ) {
  5394. this.r *= s;
  5395. this.g *= s;
  5396. this.b *= s;
  5397. return this;
  5398. }
  5399. lerp( color, alpha ) {
  5400. this.r += ( color.r - this.r ) * alpha;
  5401. this.g += ( color.g - this.g ) * alpha;
  5402. this.b += ( color.b - this.b ) * alpha;
  5403. return this;
  5404. }
  5405. lerpColors( color1, color2, alpha ) {
  5406. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5407. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5408. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5409. return this;
  5410. }
  5411. lerpHSL( color, alpha ) {
  5412. this.getHSL( _hslA );
  5413. color.getHSL( _hslB );
  5414. const h = lerp( _hslA.h, _hslB.h, alpha );
  5415. const s = lerp( _hslA.s, _hslB.s, alpha );
  5416. const l = lerp( _hslA.l, _hslB.l, alpha );
  5417. this.setHSL( h, s, l );
  5418. return this;
  5419. }
  5420. setFromVector3( v ) {
  5421. this.r = v.x;
  5422. this.g = v.y;
  5423. this.b = v.z;
  5424. return this;
  5425. }
  5426. applyMatrix3( m ) {
  5427. const r = this.r, g = this.g, b = this.b;
  5428. const e = m.elements;
  5429. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5430. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5431. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5432. return this;
  5433. }
  5434. equals( c ) {
  5435. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5436. }
  5437. fromArray( array, offset = 0 ) {
  5438. this.r = array[ offset ];
  5439. this.g = array[ offset + 1 ];
  5440. this.b = array[ offset + 2 ];
  5441. return this;
  5442. }
  5443. toArray( array = [], offset = 0 ) {
  5444. array[ offset ] = this.r;
  5445. array[ offset + 1 ] = this.g;
  5446. array[ offset + 2 ] = this.b;
  5447. return array;
  5448. }
  5449. fromBufferAttribute( attribute, index ) {
  5450. this.r = attribute.getX( index );
  5451. this.g = attribute.getY( index );
  5452. this.b = attribute.getZ( index );
  5453. return this;
  5454. }
  5455. toJSON() {
  5456. return this.getHex();
  5457. }
  5458. *[ Symbol.iterator ]() {
  5459. yield this.r;
  5460. yield this.g;
  5461. yield this.b;
  5462. }
  5463. }
  5464. const _color = /*@__PURE__*/ new Color();
  5465. Color.NAMES = _colorKeywords;
  5466. let _materialId = 0;
  5467. class Material extends EventDispatcher {
  5468. constructor() {
  5469. super();
  5470. this.isMaterial = true;
  5471. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5472. this.uuid = generateUUID();
  5473. this.name = '';
  5474. this.type = 'Material';
  5475. this.blending = NormalBlending;
  5476. this.side = FrontSide;
  5477. this.vertexColors = false;
  5478. this.opacity = 1;
  5479. this.transparent = false;
  5480. this.alphaHash = false;
  5481. this.blendSrc = SrcAlphaFactor;
  5482. this.blendDst = OneMinusSrcAlphaFactor;
  5483. this.blendEquation = AddEquation;
  5484. this.blendSrcAlpha = null;
  5485. this.blendDstAlpha = null;
  5486. this.blendEquationAlpha = null;
  5487. this.blendColor = new Color( 0, 0, 0 );
  5488. this.blendAlpha = 0;
  5489. this.depthFunc = LessEqualDepth;
  5490. this.depthTest = true;
  5491. this.depthWrite = true;
  5492. this.stencilWriteMask = 0xff;
  5493. this.stencilFunc = AlwaysStencilFunc;
  5494. this.stencilRef = 0;
  5495. this.stencilFuncMask = 0xff;
  5496. this.stencilFail = KeepStencilOp;
  5497. this.stencilZFail = KeepStencilOp;
  5498. this.stencilZPass = KeepStencilOp;
  5499. this.stencilWrite = false;
  5500. this.clippingPlanes = null;
  5501. this.clipIntersection = false;
  5502. this.clipShadows = false;
  5503. this.shadowSide = null;
  5504. this.colorWrite = true;
  5505. this.precision = null; // override the renderer's default precision for this material
  5506. this.polygonOffset = false;
  5507. this.polygonOffsetFactor = 0;
  5508. this.polygonOffsetUnits = 0;
  5509. this.dithering = false;
  5510. this.alphaToCoverage = false;
  5511. this.premultipliedAlpha = false;
  5512. this.forceSinglePass = false;
  5513. this.visible = true;
  5514. this.toneMapped = true;
  5515. this.userData = {};
  5516. this.version = 0;
  5517. this._alphaTest = 0;
  5518. }
  5519. get alphaTest() {
  5520. return this._alphaTest;
  5521. }
  5522. set alphaTest( value ) {
  5523. if ( this._alphaTest > 0 !== value > 0 ) {
  5524. this.version ++;
  5525. }
  5526. this._alphaTest = value;
  5527. }
  5528. // onBeforeRender and onBeforeCompile only supported in WebGLRenderer
  5529. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5530. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5531. customProgramCacheKey() {
  5532. return this.onBeforeCompile.toString();
  5533. }
  5534. setValues( values ) {
  5535. if ( values === undefined ) return;
  5536. for ( const key in values ) {
  5537. const newValue = values[ key ];
  5538. if ( newValue === undefined ) {
  5539. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5540. continue;
  5541. }
  5542. const currentValue = this[ key ];
  5543. if ( currentValue === undefined ) {
  5544. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5545. continue;
  5546. }
  5547. if ( currentValue && currentValue.isColor ) {
  5548. currentValue.set( newValue );
  5549. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5550. currentValue.copy( newValue );
  5551. } else {
  5552. this[ key ] = newValue;
  5553. }
  5554. }
  5555. }
  5556. toJSON( meta ) {
  5557. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5558. if ( isRootObject ) {
  5559. meta = {
  5560. textures: {},
  5561. images: {}
  5562. };
  5563. }
  5564. const data = {
  5565. metadata: {
  5566. version: 4.6,
  5567. type: 'Material',
  5568. generator: 'Material.toJSON'
  5569. }
  5570. };
  5571. // standard Material serialization
  5572. data.uuid = this.uuid;
  5573. data.type = this.type;
  5574. if ( this.name !== '' ) data.name = this.name;
  5575. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5576. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5577. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5578. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5579. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5580. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5581. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5582. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5583. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5584. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5585. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5586. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5587. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5588. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5589. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5590. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5591. }
  5592. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5593. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5594. }
  5595. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5596. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5597. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5598. }
  5599. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5600. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5601. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5602. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5603. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5604. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5605. }
  5606. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5607. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5608. }
  5609. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5610. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5611. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5612. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5613. }
  5614. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5615. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5616. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5617. if ( this.lightMap && this.lightMap.isTexture ) {
  5618. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5619. data.lightMapIntensity = this.lightMapIntensity;
  5620. }
  5621. if ( this.aoMap && this.aoMap.isTexture ) {
  5622. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5623. data.aoMapIntensity = this.aoMapIntensity;
  5624. }
  5625. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5626. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5627. data.bumpScale = this.bumpScale;
  5628. }
  5629. if ( this.normalMap && this.normalMap.isTexture ) {
  5630. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5631. data.normalMapType = this.normalMapType;
  5632. data.normalScale = this.normalScale.toArray();
  5633. }
  5634. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5635. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5636. data.displacementScale = this.displacementScale;
  5637. data.displacementBias = this.displacementBias;
  5638. }
  5639. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5640. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5641. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5642. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5643. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5644. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5645. if ( this.envMap && this.envMap.isTexture ) {
  5646. data.envMap = this.envMap.toJSON( meta ).uuid;
  5647. if ( this.combine !== undefined ) data.combine = this.combine;
  5648. }
  5649. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5650. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5651. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5652. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5653. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5654. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5655. }
  5656. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5657. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5658. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5659. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5660. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5661. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5662. if ( this.size !== undefined ) data.size = this.size;
  5663. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5664. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5665. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5666. if ( this.side !== FrontSide ) data.side = this.side;
  5667. if ( this.vertexColors === true ) data.vertexColors = true;
  5668. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5669. if ( this.transparent === true ) data.transparent = true;
  5670. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5671. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5672. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5673. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5674. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5675. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5676. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5677. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5678. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5679. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5680. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5681. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5682. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5683. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5684. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5685. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5686. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5687. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5688. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5689. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5690. // rotation (SpriteMaterial)
  5691. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5692. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5693. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5694. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5695. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5696. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5697. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5698. if ( this.scale !== undefined ) data.scale = this.scale;
  5699. if ( this.dithering === true ) data.dithering = true;
  5700. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5701. if ( this.alphaHash === true ) data.alphaHash = true;
  5702. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5703. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5704. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5705. if ( this.wireframe === true ) data.wireframe = true;
  5706. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5707. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5708. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5709. if ( this.flatShading === true ) data.flatShading = true;
  5710. if ( this.visible === false ) data.visible = false;
  5711. if ( this.toneMapped === false ) data.toneMapped = false;
  5712. if ( this.fog === false ) data.fog = false;
  5713. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5714. // TODO: Copied from Object3D.toJSON
  5715. function extractFromCache( cache ) {
  5716. const values = [];
  5717. for ( const key in cache ) {
  5718. const data = cache[ key ];
  5719. delete data.metadata;
  5720. values.push( data );
  5721. }
  5722. return values;
  5723. }
  5724. if ( isRootObject ) {
  5725. const textures = extractFromCache( meta.textures );
  5726. const images = extractFromCache( meta.images );
  5727. if ( textures.length > 0 ) data.textures = textures;
  5728. if ( images.length > 0 ) data.images = images;
  5729. }
  5730. return data;
  5731. }
  5732. clone() {
  5733. return new this.constructor().copy( this );
  5734. }
  5735. copy( source ) {
  5736. this.name = source.name;
  5737. this.blending = source.blending;
  5738. this.side = source.side;
  5739. this.vertexColors = source.vertexColors;
  5740. this.opacity = source.opacity;
  5741. this.transparent = source.transparent;
  5742. this.blendSrc = source.blendSrc;
  5743. this.blendDst = source.blendDst;
  5744. this.blendEquation = source.blendEquation;
  5745. this.blendSrcAlpha = source.blendSrcAlpha;
  5746. this.blendDstAlpha = source.blendDstAlpha;
  5747. this.blendEquationAlpha = source.blendEquationAlpha;
  5748. this.blendColor.copy( source.blendColor );
  5749. this.blendAlpha = source.blendAlpha;
  5750. this.depthFunc = source.depthFunc;
  5751. this.depthTest = source.depthTest;
  5752. this.depthWrite = source.depthWrite;
  5753. this.stencilWriteMask = source.stencilWriteMask;
  5754. this.stencilFunc = source.stencilFunc;
  5755. this.stencilRef = source.stencilRef;
  5756. this.stencilFuncMask = source.stencilFuncMask;
  5757. this.stencilFail = source.stencilFail;
  5758. this.stencilZFail = source.stencilZFail;
  5759. this.stencilZPass = source.stencilZPass;
  5760. this.stencilWrite = source.stencilWrite;
  5761. const srcPlanes = source.clippingPlanes;
  5762. let dstPlanes = null;
  5763. if ( srcPlanes !== null ) {
  5764. const n = srcPlanes.length;
  5765. dstPlanes = new Array( n );
  5766. for ( let i = 0; i !== n; ++ i ) {
  5767. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5768. }
  5769. }
  5770. this.clippingPlanes = dstPlanes;
  5771. this.clipIntersection = source.clipIntersection;
  5772. this.clipShadows = source.clipShadows;
  5773. this.shadowSide = source.shadowSide;
  5774. this.colorWrite = source.colorWrite;
  5775. this.precision = source.precision;
  5776. this.polygonOffset = source.polygonOffset;
  5777. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5778. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5779. this.dithering = source.dithering;
  5780. this.alphaTest = source.alphaTest;
  5781. this.alphaHash = source.alphaHash;
  5782. this.alphaToCoverage = source.alphaToCoverage;
  5783. this.premultipliedAlpha = source.premultipliedAlpha;
  5784. this.forceSinglePass = source.forceSinglePass;
  5785. this.visible = source.visible;
  5786. this.toneMapped = source.toneMapped;
  5787. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5788. return this;
  5789. }
  5790. dispose() {
  5791. this.dispatchEvent( { type: 'dispose' } );
  5792. }
  5793. set needsUpdate( value ) {
  5794. if ( value === true ) this.version ++;
  5795. }
  5796. onBuild( /* shaderobject, renderer */ ) {
  5797. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5798. }
  5799. }
  5800. class MeshBasicMaterial extends Material {
  5801. constructor( parameters ) {
  5802. super();
  5803. this.isMeshBasicMaterial = true;
  5804. this.type = 'MeshBasicMaterial';
  5805. this.color = new Color( 0xffffff ); // emissive
  5806. this.map = null;
  5807. this.lightMap = null;
  5808. this.lightMapIntensity = 1.0;
  5809. this.aoMap = null;
  5810. this.aoMapIntensity = 1.0;
  5811. this.specularMap = null;
  5812. this.alphaMap = null;
  5813. this.envMap = null;
  5814. this.envMapRotation = new Euler();
  5815. this.combine = MultiplyOperation;
  5816. this.reflectivity = 1;
  5817. this.refractionRatio = 0.98;
  5818. this.wireframe = false;
  5819. this.wireframeLinewidth = 1;
  5820. this.wireframeLinecap = 'round';
  5821. this.wireframeLinejoin = 'round';
  5822. this.fog = true;
  5823. this.setValues( parameters );
  5824. }
  5825. copy( source ) {
  5826. super.copy( source );
  5827. this.color.copy( source.color );
  5828. this.map = source.map;
  5829. this.lightMap = source.lightMap;
  5830. this.lightMapIntensity = source.lightMapIntensity;
  5831. this.aoMap = source.aoMap;
  5832. this.aoMapIntensity = source.aoMapIntensity;
  5833. this.specularMap = source.specularMap;
  5834. this.alphaMap = source.alphaMap;
  5835. this.envMap = source.envMap;
  5836. this.envMapRotation.copy( source.envMapRotation );
  5837. this.combine = source.combine;
  5838. this.reflectivity = source.reflectivity;
  5839. this.refractionRatio = source.refractionRatio;
  5840. this.wireframe = source.wireframe;
  5841. this.wireframeLinewidth = source.wireframeLinewidth;
  5842. this.wireframeLinecap = source.wireframeLinecap;
  5843. this.wireframeLinejoin = source.wireframeLinejoin;
  5844. this.fog = source.fog;
  5845. return this;
  5846. }
  5847. }
  5848. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5849. const _tables = /*@__PURE__*/ _generateTables();
  5850. function _generateTables() {
  5851. // float32 to float16 helpers
  5852. const buffer = new ArrayBuffer( 4 );
  5853. const floatView = new Float32Array( buffer );
  5854. const uint32View = new Uint32Array( buffer );
  5855. const baseTable = new Uint32Array( 512 );
  5856. const shiftTable = new Uint32Array( 512 );
  5857. for ( let i = 0; i < 256; ++ i ) {
  5858. const e = i - 127;
  5859. // very small number (0, -0)
  5860. if ( e < - 27 ) {
  5861. baseTable[ i ] = 0x0000;
  5862. baseTable[ i | 0x100 ] = 0x8000;
  5863. shiftTable[ i ] = 24;
  5864. shiftTable[ i | 0x100 ] = 24;
  5865. // small number (denorm)
  5866. } else if ( e < - 14 ) {
  5867. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5868. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5869. shiftTable[ i ] = - e - 1;
  5870. shiftTable[ i | 0x100 ] = - e - 1;
  5871. // normal number
  5872. } else if ( e <= 15 ) {
  5873. baseTable[ i ] = ( e + 15 ) << 10;
  5874. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5875. shiftTable[ i ] = 13;
  5876. shiftTable[ i | 0x100 ] = 13;
  5877. // large number (Infinity, -Infinity)
  5878. } else if ( e < 128 ) {
  5879. baseTable[ i ] = 0x7c00;
  5880. baseTable[ i | 0x100 ] = 0xfc00;
  5881. shiftTable[ i ] = 24;
  5882. shiftTable[ i | 0x100 ] = 24;
  5883. // stay (NaN, Infinity, -Infinity)
  5884. } else {
  5885. baseTable[ i ] = 0x7c00;
  5886. baseTable[ i | 0x100 ] = 0xfc00;
  5887. shiftTable[ i ] = 13;
  5888. shiftTable[ i | 0x100 ] = 13;
  5889. }
  5890. }
  5891. // float16 to float32 helpers
  5892. const mantissaTable = new Uint32Array( 2048 );
  5893. const exponentTable = new Uint32Array( 64 );
  5894. const offsetTable = new Uint32Array( 64 );
  5895. for ( let i = 1; i < 1024; ++ i ) {
  5896. let m = i << 13; // zero pad mantissa bits
  5897. let e = 0; // zero exponent
  5898. // normalized
  5899. while ( ( m & 0x00800000 ) === 0 ) {
  5900. m <<= 1;
  5901. e -= 0x00800000; // decrement exponent
  5902. }
  5903. m &= ~ 0x00800000; // clear leading 1 bit
  5904. e += 0x38800000; // adjust bias
  5905. mantissaTable[ i ] = m | e;
  5906. }
  5907. for ( let i = 1024; i < 2048; ++ i ) {
  5908. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5909. }
  5910. for ( let i = 1; i < 31; ++ i ) {
  5911. exponentTable[ i ] = i << 23;
  5912. }
  5913. exponentTable[ 31 ] = 0x47800000;
  5914. exponentTable[ 32 ] = 0x80000000;
  5915. for ( let i = 33; i < 63; ++ i ) {
  5916. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5917. }
  5918. exponentTable[ 63 ] = 0xc7800000;
  5919. for ( let i = 1; i < 64; ++ i ) {
  5920. if ( i !== 32 ) {
  5921. offsetTable[ i ] = 1024;
  5922. }
  5923. }
  5924. return {
  5925. floatView: floatView,
  5926. uint32View: uint32View,
  5927. baseTable: baseTable,
  5928. shiftTable: shiftTable,
  5929. mantissaTable: mantissaTable,
  5930. exponentTable: exponentTable,
  5931. offsetTable: offsetTable
  5932. };
  5933. }
  5934. // float32 to float16
  5935. function toHalfFloat( val ) {
  5936. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5937. val = clamp$1( val, - 65504, 65504 );
  5938. _tables.floatView[ 0 ] = val;
  5939. const f = _tables.uint32View[ 0 ];
  5940. const e = ( f >> 23 ) & 0x1ff;
  5941. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5942. }
  5943. // float16 to float32
  5944. function fromHalfFloat( val ) {
  5945. const m = val >> 10;
  5946. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5947. return _tables.floatView[ 0 ];
  5948. }
  5949. const DataUtils = {
  5950. toHalfFloat: toHalfFloat,
  5951. fromHalfFloat: fromHalfFloat,
  5952. };
  5953. const _vector$9 = /*@__PURE__*/ new Vector3();
  5954. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5955. class BufferAttribute {
  5956. constructor( array, itemSize, normalized = false ) {
  5957. if ( Array.isArray( array ) ) {
  5958. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5959. }
  5960. this.isBufferAttribute = true;
  5961. this.name = '';
  5962. this.array = array;
  5963. this.itemSize = itemSize;
  5964. this.count = array !== undefined ? array.length / itemSize : 0;
  5965. this.normalized = normalized;
  5966. this.usage = StaticDrawUsage;
  5967. this.updateRanges = [];
  5968. this.gpuType = FloatType;
  5969. this.version = 0;
  5970. }
  5971. onUploadCallback() {}
  5972. set needsUpdate( value ) {
  5973. if ( value === true ) this.version ++;
  5974. }
  5975. setUsage( value ) {
  5976. this.usage = value;
  5977. return this;
  5978. }
  5979. addUpdateRange( start, count ) {
  5980. this.updateRanges.push( { start, count } );
  5981. }
  5982. clearUpdateRanges() {
  5983. this.updateRanges.length = 0;
  5984. }
  5985. copy( source ) {
  5986. this.name = source.name;
  5987. this.array = new source.array.constructor( source.array );
  5988. this.itemSize = source.itemSize;
  5989. this.count = source.count;
  5990. this.normalized = source.normalized;
  5991. this.usage = source.usage;
  5992. this.gpuType = source.gpuType;
  5993. return this;
  5994. }
  5995. copyAt( index1, attribute, index2 ) {
  5996. index1 *= this.itemSize;
  5997. index2 *= attribute.itemSize;
  5998. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5999. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6000. }
  6001. return this;
  6002. }
  6003. copyArray( array ) {
  6004. this.array.set( array );
  6005. return this;
  6006. }
  6007. applyMatrix3( m ) {
  6008. if ( this.itemSize === 2 ) {
  6009. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6010. _vector2$1.fromBufferAttribute( this, i );
  6011. _vector2$1.applyMatrix3( m );
  6012. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6013. }
  6014. } else if ( this.itemSize === 3 ) {
  6015. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6016. _vector$9.fromBufferAttribute( this, i );
  6017. _vector$9.applyMatrix3( m );
  6018. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6019. }
  6020. }
  6021. return this;
  6022. }
  6023. applyMatrix4( m ) {
  6024. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6025. _vector$9.fromBufferAttribute( this, i );
  6026. _vector$9.applyMatrix4( m );
  6027. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6028. }
  6029. return this;
  6030. }
  6031. applyNormalMatrix( m ) {
  6032. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6033. _vector$9.fromBufferAttribute( this, i );
  6034. _vector$9.applyNormalMatrix( m );
  6035. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6036. }
  6037. return this;
  6038. }
  6039. transformDirection( m ) {
  6040. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6041. _vector$9.fromBufferAttribute( this, i );
  6042. _vector$9.transformDirection( m );
  6043. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6044. }
  6045. return this;
  6046. }
  6047. set( value, offset = 0 ) {
  6048. // Matching BufferAttribute constructor, do not normalize the array.
  6049. this.array.set( value, offset );
  6050. return this;
  6051. }
  6052. getComponent( index, component ) {
  6053. let value = this.array[ index * this.itemSize + component ];
  6054. if ( this.normalized ) value = denormalize( value, this.array );
  6055. return value;
  6056. }
  6057. setComponent( index, component, value ) {
  6058. if ( this.normalized ) value = normalize$1( value, this.array );
  6059. this.array[ index * this.itemSize + component ] = value;
  6060. return this;
  6061. }
  6062. getX( index ) {
  6063. let x = this.array[ index * this.itemSize ];
  6064. if ( this.normalized ) x = denormalize( x, this.array );
  6065. return x;
  6066. }
  6067. setX( index, x ) {
  6068. if ( this.normalized ) x = normalize$1( x, this.array );
  6069. this.array[ index * this.itemSize ] = x;
  6070. return this;
  6071. }
  6072. getY( index ) {
  6073. let y = this.array[ index * this.itemSize + 1 ];
  6074. if ( this.normalized ) y = denormalize( y, this.array );
  6075. return y;
  6076. }
  6077. setY( index, y ) {
  6078. if ( this.normalized ) y = normalize$1( y, this.array );
  6079. this.array[ index * this.itemSize + 1 ] = y;
  6080. return this;
  6081. }
  6082. getZ( index ) {
  6083. let z = this.array[ index * this.itemSize + 2 ];
  6084. if ( this.normalized ) z = denormalize( z, this.array );
  6085. return z;
  6086. }
  6087. setZ( index, z ) {
  6088. if ( this.normalized ) z = normalize$1( z, this.array );
  6089. this.array[ index * this.itemSize + 2 ] = z;
  6090. return this;
  6091. }
  6092. getW( index ) {
  6093. let w = this.array[ index * this.itemSize + 3 ];
  6094. if ( this.normalized ) w = denormalize( w, this.array );
  6095. return w;
  6096. }
  6097. setW( index, w ) {
  6098. if ( this.normalized ) w = normalize$1( w, this.array );
  6099. this.array[ index * this.itemSize + 3 ] = w;
  6100. return this;
  6101. }
  6102. setXY( index, x, y ) {
  6103. index *= this.itemSize;
  6104. if ( this.normalized ) {
  6105. x = normalize$1( x, this.array );
  6106. y = normalize$1( y, this.array );
  6107. }
  6108. this.array[ index + 0 ] = x;
  6109. this.array[ index + 1 ] = y;
  6110. return this;
  6111. }
  6112. setXYZ( index, x, y, z ) {
  6113. index *= this.itemSize;
  6114. if ( this.normalized ) {
  6115. x = normalize$1( x, this.array );
  6116. y = normalize$1( y, this.array );
  6117. z = normalize$1( z, this.array );
  6118. }
  6119. this.array[ index + 0 ] = x;
  6120. this.array[ index + 1 ] = y;
  6121. this.array[ index + 2 ] = z;
  6122. return this;
  6123. }
  6124. setXYZW( index, x, y, z, w ) {
  6125. index *= this.itemSize;
  6126. if ( this.normalized ) {
  6127. x = normalize$1( x, this.array );
  6128. y = normalize$1( y, this.array );
  6129. z = normalize$1( z, this.array );
  6130. w = normalize$1( w, this.array );
  6131. }
  6132. this.array[ index + 0 ] = x;
  6133. this.array[ index + 1 ] = y;
  6134. this.array[ index + 2 ] = z;
  6135. this.array[ index + 3 ] = w;
  6136. return this;
  6137. }
  6138. onUpload( callback ) {
  6139. this.onUploadCallback = callback;
  6140. return this;
  6141. }
  6142. clone() {
  6143. return new this.constructor( this.array, this.itemSize ).copy( this );
  6144. }
  6145. toJSON() {
  6146. const data = {
  6147. itemSize: this.itemSize,
  6148. type: this.array.constructor.name,
  6149. array: Array.from( this.array ),
  6150. normalized: this.normalized
  6151. };
  6152. if ( this.name !== '' ) data.name = this.name;
  6153. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6154. return data;
  6155. }
  6156. }
  6157. //
  6158. class Int8BufferAttribute extends BufferAttribute {
  6159. constructor( array, itemSize, normalized ) {
  6160. super( new Int8Array( array ), itemSize, normalized );
  6161. }
  6162. }
  6163. class Uint8BufferAttribute extends BufferAttribute {
  6164. constructor( array, itemSize, normalized ) {
  6165. super( new Uint8Array( array ), itemSize, normalized );
  6166. }
  6167. }
  6168. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6169. constructor( array, itemSize, normalized ) {
  6170. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6171. }
  6172. }
  6173. class Int16BufferAttribute extends BufferAttribute {
  6174. constructor( array, itemSize, normalized ) {
  6175. super( new Int16Array( array ), itemSize, normalized );
  6176. }
  6177. }
  6178. class Uint16BufferAttribute extends BufferAttribute {
  6179. constructor( array, itemSize, normalized ) {
  6180. super( new Uint16Array( array ), itemSize, normalized );
  6181. }
  6182. }
  6183. class Int32BufferAttribute extends BufferAttribute {
  6184. constructor( array, itemSize, normalized ) {
  6185. super( new Int32Array( array ), itemSize, normalized );
  6186. }
  6187. }
  6188. class Uint32BufferAttribute extends BufferAttribute {
  6189. constructor( array, itemSize, normalized ) {
  6190. super( new Uint32Array( array ), itemSize, normalized );
  6191. }
  6192. }
  6193. class Float16BufferAttribute extends BufferAttribute {
  6194. constructor( array, itemSize, normalized ) {
  6195. super( new Uint16Array( array ), itemSize, normalized );
  6196. this.isFloat16BufferAttribute = true;
  6197. }
  6198. getX( index ) {
  6199. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6200. if ( this.normalized ) x = denormalize( x, this.array );
  6201. return x;
  6202. }
  6203. setX( index, x ) {
  6204. if ( this.normalized ) x = normalize$1( x, this.array );
  6205. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6206. return this;
  6207. }
  6208. getY( index ) {
  6209. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6210. if ( this.normalized ) y = denormalize( y, this.array );
  6211. return y;
  6212. }
  6213. setY( index, y ) {
  6214. if ( this.normalized ) y = normalize$1( y, this.array );
  6215. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6216. return this;
  6217. }
  6218. getZ( index ) {
  6219. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6220. if ( this.normalized ) z = denormalize( z, this.array );
  6221. return z;
  6222. }
  6223. setZ( index, z ) {
  6224. if ( this.normalized ) z = normalize$1( z, this.array );
  6225. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6226. return this;
  6227. }
  6228. getW( index ) {
  6229. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6230. if ( this.normalized ) w = denormalize( w, this.array );
  6231. return w;
  6232. }
  6233. setW( index, w ) {
  6234. if ( this.normalized ) w = normalize$1( w, this.array );
  6235. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6236. return this;
  6237. }
  6238. setXY( index, x, y ) {
  6239. index *= this.itemSize;
  6240. if ( this.normalized ) {
  6241. x = normalize$1( x, this.array );
  6242. y = normalize$1( y, this.array );
  6243. }
  6244. this.array[ index + 0 ] = toHalfFloat( x );
  6245. this.array[ index + 1 ] = toHalfFloat( y );
  6246. return this;
  6247. }
  6248. setXYZ( index, x, y, z ) {
  6249. index *= this.itemSize;
  6250. if ( this.normalized ) {
  6251. x = normalize$1( x, this.array );
  6252. y = normalize$1( y, this.array );
  6253. z = normalize$1( z, this.array );
  6254. }
  6255. this.array[ index + 0 ] = toHalfFloat( x );
  6256. this.array[ index + 1 ] = toHalfFloat( y );
  6257. this.array[ index + 2 ] = toHalfFloat( z );
  6258. return this;
  6259. }
  6260. setXYZW( index, x, y, z, w ) {
  6261. index *= this.itemSize;
  6262. if ( this.normalized ) {
  6263. x = normalize$1( x, this.array );
  6264. y = normalize$1( y, this.array );
  6265. z = normalize$1( z, this.array );
  6266. w = normalize$1( w, this.array );
  6267. }
  6268. this.array[ index + 0 ] = toHalfFloat( x );
  6269. this.array[ index + 1 ] = toHalfFloat( y );
  6270. this.array[ index + 2 ] = toHalfFloat( z );
  6271. this.array[ index + 3 ] = toHalfFloat( w );
  6272. return this;
  6273. }
  6274. }
  6275. class Float32BufferAttribute extends BufferAttribute {
  6276. constructor( array, itemSize, normalized ) {
  6277. super( new Float32Array( array ), itemSize, normalized );
  6278. }
  6279. }
  6280. let _id$9 = 0;
  6281. const _m1 = /*@__PURE__*/ new Matrix4();
  6282. const _obj = /*@__PURE__*/ new Object3D();
  6283. const _offset = /*@__PURE__*/ new Vector3();
  6284. const _box$2 = /*@__PURE__*/ new Box3();
  6285. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6286. const _vector$8 = /*@__PURE__*/ new Vector3();
  6287. class BufferGeometry extends EventDispatcher {
  6288. constructor() {
  6289. super();
  6290. this.isBufferGeometry = true;
  6291. Object.defineProperty( this, 'id', { value: _id$9 ++ } );
  6292. this.uuid = generateUUID();
  6293. this.name = '';
  6294. this.type = 'BufferGeometry';
  6295. this.index = null;
  6296. this.attributes = {};
  6297. this.morphAttributes = {};
  6298. this.morphTargetsRelative = false;
  6299. this.groups = [];
  6300. this.boundingBox = null;
  6301. this.boundingSphere = null;
  6302. this.drawRange = { start: 0, count: Infinity };
  6303. this.userData = {};
  6304. }
  6305. getIndex() {
  6306. return this.index;
  6307. }
  6308. setIndex( index ) {
  6309. if ( Array.isArray( index ) ) {
  6310. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6311. } else {
  6312. this.index = index;
  6313. }
  6314. return this;
  6315. }
  6316. getAttribute( name ) {
  6317. return this.attributes[ name ];
  6318. }
  6319. setAttribute( name, attribute ) {
  6320. this.attributes[ name ] = attribute;
  6321. return this;
  6322. }
  6323. deleteAttribute( name ) {
  6324. delete this.attributes[ name ];
  6325. return this;
  6326. }
  6327. hasAttribute( name ) {
  6328. return this.attributes[ name ] !== undefined;
  6329. }
  6330. addGroup( start, count, materialIndex = 0 ) {
  6331. this.groups.push( {
  6332. start: start,
  6333. count: count,
  6334. materialIndex: materialIndex
  6335. } );
  6336. }
  6337. clearGroups() {
  6338. this.groups = [];
  6339. }
  6340. setDrawRange( start, count ) {
  6341. this.drawRange.start = start;
  6342. this.drawRange.count = count;
  6343. }
  6344. applyMatrix4( matrix ) {
  6345. const position = this.attributes.position;
  6346. if ( position !== undefined ) {
  6347. position.applyMatrix4( matrix );
  6348. position.needsUpdate = true;
  6349. }
  6350. const normal = this.attributes.normal;
  6351. if ( normal !== undefined ) {
  6352. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6353. normal.applyNormalMatrix( normalMatrix );
  6354. normal.needsUpdate = true;
  6355. }
  6356. const tangent = this.attributes.tangent;
  6357. if ( tangent !== undefined ) {
  6358. tangent.transformDirection( matrix );
  6359. tangent.needsUpdate = true;
  6360. }
  6361. if ( this.boundingBox !== null ) {
  6362. this.computeBoundingBox();
  6363. }
  6364. if ( this.boundingSphere !== null ) {
  6365. this.computeBoundingSphere();
  6366. }
  6367. return this;
  6368. }
  6369. applyQuaternion( q ) {
  6370. _m1.makeRotationFromQuaternion( q );
  6371. this.applyMatrix4( _m1 );
  6372. return this;
  6373. }
  6374. rotateX( angle ) {
  6375. // rotate geometry around world x-axis
  6376. _m1.makeRotationX( angle );
  6377. this.applyMatrix4( _m1 );
  6378. return this;
  6379. }
  6380. rotateY( angle ) {
  6381. // rotate geometry around world y-axis
  6382. _m1.makeRotationY( angle );
  6383. this.applyMatrix4( _m1 );
  6384. return this;
  6385. }
  6386. rotateZ( angle ) {
  6387. // rotate geometry around world z-axis
  6388. _m1.makeRotationZ( angle );
  6389. this.applyMatrix4( _m1 );
  6390. return this;
  6391. }
  6392. translate( x, y, z ) {
  6393. // translate geometry
  6394. _m1.makeTranslation( x, y, z );
  6395. this.applyMatrix4( _m1 );
  6396. return this;
  6397. }
  6398. scale( x, y, z ) {
  6399. // scale geometry
  6400. _m1.makeScale( x, y, z );
  6401. this.applyMatrix4( _m1 );
  6402. return this;
  6403. }
  6404. lookAt( vector ) {
  6405. _obj.lookAt( vector );
  6406. _obj.updateMatrix();
  6407. this.applyMatrix4( _obj.matrix );
  6408. return this;
  6409. }
  6410. center() {
  6411. this.computeBoundingBox();
  6412. this.boundingBox.getCenter( _offset ).negate();
  6413. this.translate( _offset.x, _offset.y, _offset.z );
  6414. return this;
  6415. }
  6416. setFromPoints( points ) {
  6417. const position = [];
  6418. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6419. const point = points[ i ];
  6420. position.push( point.x, point.y, point.z || 0 );
  6421. }
  6422. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6423. return this;
  6424. }
  6425. computeBoundingBox() {
  6426. if ( this.boundingBox === null ) {
  6427. this.boundingBox = new Box3();
  6428. }
  6429. const position = this.attributes.position;
  6430. const morphAttributesPosition = this.morphAttributes.position;
  6431. if ( position && position.isGLBufferAttribute ) {
  6432. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6433. this.boundingBox.set(
  6434. new Vector3( - Infinity, - Infinity, - Infinity ),
  6435. new Vector3( + Infinity, + Infinity, + Infinity )
  6436. );
  6437. return;
  6438. }
  6439. if ( position !== undefined ) {
  6440. this.boundingBox.setFromBufferAttribute( position );
  6441. // process morph attributes if present
  6442. if ( morphAttributesPosition ) {
  6443. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6444. const morphAttribute = morphAttributesPosition[ i ];
  6445. _box$2.setFromBufferAttribute( morphAttribute );
  6446. if ( this.morphTargetsRelative ) {
  6447. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6448. this.boundingBox.expandByPoint( _vector$8 );
  6449. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6450. this.boundingBox.expandByPoint( _vector$8 );
  6451. } else {
  6452. this.boundingBox.expandByPoint( _box$2.min );
  6453. this.boundingBox.expandByPoint( _box$2.max );
  6454. }
  6455. }
  6456. }
  6457. } else {
  6458. this.boundingBox.makeEmpty();
  6459. }
  6460. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6461. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6462. }
  6463. }
  6464. computeBoundingSphere() {
  6465. if ( this.boundingSphere === null ) {
  6466. this.boundingSphere = new Sphere();
  6467. }
  6468. const position = this.attributes.position;
  6469. const morphAttributesPosition = this.morphAttributes.position;
  6470. if ( position && position.isGLBufferAttribute ) {
  6471. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6472. this.boundingSphere.set( new Vector3(), Infinity );
  6473. return;
  6474. }
  6475. if ( position ) {
  6476. // first, find the center of the bounding sphere
  6477. const center = this.boundingSphere.center;
  6478. _box$2.setFromBufferAttribute( position );
  6479. // process morph attributes if present
  6480. if ( morphAttributesPosition ) {
  6481. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6482. const morphAttribute = morphAttributesPosition[ i ];
  6483. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6484. if ( this.morphTargetsRelative ) {
  6485. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6486. _box$2.expandByPoint( _vector$8 );
  6487. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6488. _box$2.expandByPoint( _vector$8 );
  6489. } else {
  6490. _box$2.expandByPoint( _boxMorphTargets.min );
  6491. _box$2.expandByPoint( _boxMorphTargets.max );
  6492. }
  6493. }
  6494. }
  6495. _box$2.getCenter( center );
  6496. // second, try to find a boundingSphere with a radius smaller than the
  6497. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6498. let maxRadiusSq = 0;
  6499. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6500. _vector$8.fromBufferAttribute( position, i );
  6501. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6502. }
  6503. // process morph attributes if present
  6504. if ( morphAttributesPosition ) {
  6505. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6506. const morphAttribute = morphAttributesPosition[ i ];
  6507. const morphTargetsRelative = this.morphTargetsRelative;
  6508. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6509. _vector$8.fromBufferAttribute( morphAttribute, j );
  6510. if ( morphTargetsRelative ) {
  6511. _offset.fromBufferAttribute( position, j );
  6512. _vector$8.add( _offset );
  6513. }
  6514. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6515. }
  6516. }
  6517. }
  6518. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6519. if ( isNaN( this.boundingSphere.radius ) ) {
  6520. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6521. }
  6522. }
  6523. }
  6524. computeTangents() {
  6525. const index = this.index;
  6526. const attributes = this.attributes;
  6527. // based on http://www.terathon.com/code/tangent.html
  6528. // (per vertex tangents)
  6529. if ( index === null ||
  6530. attributes.position === undefined ||
  6531. attributes.normal === undefined ||
  6532. attributes.uv === undefined ) {
  6533. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6534. return;
  6535. }
  6536. const positionAttribute = attributes.position;
  6537. const normalAttribute = attributes.normal;
  6538. const uvAttribute = attributes.uv;
  6539. if ( this.hasAttribute( 'tangent' ) === false ) {
  6540. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6541. }
  6542. const tangentAttribute = this.getAttribute( 'tangent' );
  6543. const tan1 = [], tan2 = [];
  6544. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6545. tan1[ i ] = new Vector3();
  6546. tan2[ i ] = new Vector3();
  6547. }
  6548. const vA = new Vector3(),
  6549. vB = new Vector3(),
  6550. vC = new Vector3(),
  6551. uvA = new Vector2(),
  6552. uvB = new Vector2(),
  6553. uvC = new Vector2(),
  6554. sdir = new Vector3(),
  6555. tdir = new Vector3();
  6556. function handleTriangle( a, b, c ) {
  6557. vA.fromBufferAttribute( positionAttribute, a );
  6558. vB.fromBufferAttribute( positionAttribute, b );
  6559. vC.fromBufferAttribute( positionAttribute, c );
  6560. uvA.fromBufferAttribute( uvAttribute, a );
  6561. uvB.fromBufferAttribute( uvAttribute, b );
  6562. uvC.fromBufferAttribute( uvAttribute, c );
  6563. vB.sub( vA );
  6564. vC.sub( vA );
  6565. uvB.sub( uvA );
  6566. uvC.sub( uvA );
  6567. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6568. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6569. if ( ! isFinite( r ) ) return;
  6570. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6571. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6572. tan1[ a ].add( sdir );
  6573. tan1[ b ].add( sdir );
  6574. tan1[ c ].add( sdir );
  6575. tan2[ a ].add( tdir );
  6576. tan2[ b ].add( tdir );
  6577. tan2[ c ].add( tdir );
  6578. }
  6579. let groups = this.groups;
  6580. if ( groups.length === 0 ) {
  6581. groups = [ {
  6582. start: 0,
  6583. count: index.count
  6584. } ];
  6585. }
  6586. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6587. const group = groups[ i ];
  6588. const start = group.start;
  6589. const count = group.count;
  6590. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6591. handleTriangle(
  6592. index.getX( j + 0 ),
  6593. index.getX( j + 1 ),
  6594. index.getX( j + 2 )
  6595. );
  6596. }
  6597. }
  6598. const tmp = new Vector3(), tmp2 = new Vector3();
  6599. const n = new Vector3(), n2 = new Vector3();
  6600. function handleVertex( v ) {
  6601. n.fromBufferAttribute( normalAttribute, v );
  6602. n2.copy( n );
  6603. const t = tan1[ v ];
  6604. // Gram-Schmidt orthogonalize
  6605. tmp.copy( t );
  6606. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6607. // Calculate handedness
  6608. tmp2.crossVectors( n2, t );
  6609. const test = tmp2.dot( tan2[ v ] );
  6610. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6611. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6612. }
  6613. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6614. const group = groups[ i ];
  6615. const start = group.start;
  6616. const count = group.count;
  6617. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6618. handleVertex( index.getX( j + 0 ) );
  6619. handleVertex( index.getX( j + 1 ) );
  6620. handleVertex( index.getX( j + 2 ) );
  6621. }
  6622. }
  6623. }
  6624. computeVertexNormals() {
  6625. const index = this.index;
  6626. const positionAttribute = this.getAttribute( 'position' );
  6627. if ( positionAttribute !== undefined ) {
  6628. let normalAttribute = this.getAttribute( 'normal' );
  6629. if ( normalAttribute === undefined ) {
  6630. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6631. this.setAttribute( 'normal', normalAttribute );
  6632. } else {
  6633. // reset existing normals to zero
  6634. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6635. normalAttribute.setXYZ( i, 0, 0, 0 );
  6636. }
  6637. }
  6638. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6639. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6640. const cb = new Vector3(), ab = new Vector3();
  6641. // indexed elements
  6642. if ( index ) {
  6643. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6644. const vA = index.getX( i + 0 );
  6645. const vB = index.getX( i + 1 );
  6646. const vC = index.getX( i + 2 );
  6647. pA.fromBufferAttribute( positionAttribute, vA );
  6648. pB.fromBufferAttribute( positionAttribute, vB );
  6649. pC.fromBufferAttribute( positionAttribute, vC );
  6650. cb.subVectors( pC, pB );
  6651. ab.subVectors( pA, pB );
  6652. cb.cross( ab );
  6653. nA.fromBufferAttribute( normalAttribute, vA );
  6654. nB.fromBufferAttribute( normalAttribute, vB );
  6655. nC.fromBufferAttribute( normalAttribute, vC );
  6656. nA.add( cb );
  6657. nB.add( cb );
  6658. nC.add( cb );
  6659. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6660. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6661. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6662. }
  6663. } else {
  6664. // non-indexed elements (unconnected triangle soup)
  6665. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6666. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6667. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6668. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6669. cb.subVectors( pC, pB );
  6670. ab.subVectors( pA, pB );
  6671. cb.cross( ab );
  6672. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6673. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6674. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6675. }
  6676. }
  6677. this.normalizeNormals();
  6678. normalAttribute.needsUpdate = true;
  6679. }
  6680. }
  6681. normalizeNormals() {
  6682. const normals = this.attributes.normal;
  6683. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6684. _vector$8.fromBufferAttribute( normals, i );
  6685. _vector$8.normalize();
  6686. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6687. }
  6688. }
  6689. toNonIndexed() {
  6690. function convertBufferAttribute( attribute, indices ) {
  6691. const array = attribute.array;
  6692. const itemSize = attribute.itemSize;
  6693. const normalized = attribute.normalized;
  6694. const array2 = new array.constructor( indices.length * itemSize );
  6695. let index = 0, index2 = 0;
  6696. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6697. if ( attribute.isInterleavedBufferAttribute ) {
  6698. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6699. } else {
  6700. index = indices[ i ] * itemSize;
  6701. }
  6702. for ( let j = 0; j < itemSize; j ++ ) {
  6703. array2[ index2 ++ ] = array[ index ++ ];
  6704. }
  6705. }
  6706. return new BufferAttribute( array2, itemSize, normalized );
  6707. }
  6708. //
  6709. if ( this.index === null ) {
  6710. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6711. return this;
  6712. }
  6713. const geometry2 = new BufferGeometry();
  6714. const indices = this.index.array;
  6715. const attributes = this.attributes;
  6716. // attributes
  6717. for ( const name in attributes ) {
  6718. const attribute = attributes[ name ];
  6719. const newAttribute = convertBufferAttribute( attribute, indices );
  6720. geometry2.setAttribute( name, newAttribute );
  6721. }
  6722. // morph attributes
  6723. const morphAttributes = this.morphAttributes;
  6724. for ( const name in morphAttributes ) {
  6725. const morphArray = [];
  6726. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6727. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6728. const attribute = morphAttribute[ i ];
  6729. const newAttribute = convertBufferAttribute( attribute, indices );
  6730. morphArray.push( newAttribute );
  6731. }
  6732. geometry2.morphAttributes[ name ] = morphArray;
  6733. }
  6734. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6735. // groups
  6736. const groups = this.groups;
  6737. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6738. const group = groups[ i ];
  6739. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6740. }
  6741. return geometry2;
  6742. }
  6743. toJSON() {
  6744. const data = {
  6745. metadata: {
  6746. version: 4.6,
  6747. type: 'BufferGeometry',
  6748. generator: 'BufferGeometry.toJSON'
  6749. }
  6750. };
  6751. // standard BufferGeometry serialization
  6752. data.uuid = this.uuid;
  6753. data.type = this.type;
  6754. if ( this.name !== '' ) data.name = this.name;
  6755. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6756. if ( this.parameters !== undefined ) {
  6757. const parameters = this.parameters;
  6758. for ( const key in parameters ) {
  6759. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6760. }
  6761. return data;
  6762. }
  6763. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6764. data.data = { attributes: {} };
  6765. const index = this.index;
  6766. if ( index !== null ) {
  6767. data.data.index = {
  6768. type: index.array.constructor.name,
  6769. array: Array.prototype.slice.call( index.array )
  6770. };
  6771. }
  6772. const attributes = this.attributes;
  6773. for ( const key in attributes ) {
  6774. const attribute = attributes[ key ];
  6775. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6776. }
  6777. const morphAttributes = {};
  6778. let hasMorphAttributes = false;
  6779. for ( const key in this.morphAttributes ) {
  6780. const attributeArray = this.morphAttributes[ key ];
  6781. const array = [];
  6782. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6783. const attribute = attributeArray[ i ];
  6784. array.push( attribute.toJSON( data.data ) );
  6785. }
  6786. if ( array.length > 0 ) {
  6787. morphAttributes[ key ] = array;
  6788. hasMorphAttributes = true;
  6789. }
  6790. }
  6791. if ( hasMorphAttributes ) {
  6792. data.data.morphAttributes = morphAttributes;
  6793. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6794. }
  6795. const groups = this.groups;
  6796. if ( groups.length > 0 ) {
  6797. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6798. }
  6799. const boundingSphere = this.boundingSphere;
  6800. if ( boundingSphere !== null ) {
  6801. data.data.boundingSphere = {
  6802. center: boundingSphere.center.toArray(),
  6803. radius: boundingSphere.radius
  6804. };
  6805. }
  6806. return data;
  6807. }
  6808. clone() {
  6809. return new this.constructor().copy( this );
  6810. }
  6811. copy( source ) {
  6812. // reset
  6813. this.index = null;
  6814. this.attributes = {};
  6815. this.morphAttributes = {};
  6816. this.groups = [];
  6817. this.boundingBox = null;
  6818. this.boundingSphere = null;
  6819. // used for storing cloned, shared data
  6820. const data = {};
  6821. // name
  6822. this.name = source.name;
  6823. // index
  6824. const index = source.index;
  6825. if ( index !== null ) {
  6826. this.setIndex( index.clone( data ) );
  6827. }
  6828. // attributes
  6829. const attributes = source.attributes;
  6830. for ( const name in attributes ) {
  6831. const attribute = attributes[ name ];
  6832. this.setAttribute( name, attribute.clone( data ) );
  6833. }
  6834. // morph attributes
  6835. const morphAttributes = source.morphAttributes;
  6836. for ( const name in morphAttributes ) {
  6837. const array = [];
  6838. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6839. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6840. array.push( morphAttribute[ i ].clone( data ) );
  6841. }
  6842. this.morphAttributes[ name ] = array;
  6843. }
  6844. this.morphTargetsRelative = source.morphTargetsRelative;
  6845. // groups
  6846. const groups = source.groups;
  6847. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6848. const group = groups[ i ];
  6849. this.addGroup( group.start, group.count, group.materialIndex );
  6850. }
  6851. // bounding box
  6852. const boundingBox = source.boundingBox;
  6853. if ( boundingBox !== null ) {
  6854. this.boundingBox = boundingBox.clone();
  6855. }
  6856. // bounding sphere
  6857. const boundingSphere = source.boundingSphere;
  6858. if ( boundingSphere !== null ) {
  6859. this.boundingSphere = boundingSphere.clone();
  6860. }
  6861. // draw range
  6862. this.drawRange.start = source.drawRange.start;
  6863. this.drawRange.count = source.drawRange.count;
  6864. // user data
  6865. this.userData = source.userData;
  6866. return this;
  6867. }
  6868. dispose() {
  6869. this.dispatchEvent( { type: 'dispose' } );
  6870. }
  6871. }
  6872. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6873. const _ray$3 = /*@__PURE__*/ new Ray();
  6874. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6875. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6876. const _vA$1 = /*@__PURE__*/ new Vector3();
  6877. const _vB$1 = /*@__PURE__*/ new Vector3();
  6878. const _vC$1 = /*@__PURE__*/ new Vector3();
  6879. const _tempA = /*@__PURE__*/ new Vector3();
  6880. const _morphA = /*@__PURE__*/ new Vector3();
  6881. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6882. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6883. class Mesh extends Object3D {
  6884. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6885. super();
  6886. this.isMesh = true;
  6887. this.type = 'Mesh';
  6888. this.geometry = geometry;
  6889. this.material = material;
  6890. this.updateMorphTargets();
  6891. }
  6892. copy( source, recursive ) {
  6893. super.copy( source, recursive );
  6894. if ( source.morphTargetInfluences !== undefined ) {
  6895. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6896. }
  6897. if ( source.morphTargetDictionary !== undefined ) {
  6898. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6899. }
  6900. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6901. this.geometry = source.geometry;
  6902. return this;
  6903. }
  6904. updateMorphTargets() {
  6905. const geometry = this.geometry;
  6906. const morphAttributes = geometry.morphAttributes;
  6907. const keys = Object.keys( morphAttributes );
  6908. if ( keys.length > 0 ) {
  6909. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6910. if ( morphAttribute !== undefined ) {
  6911. this.morphTargetInfluences = [];
  6912. this.morphTargetDictionary = {};
  6913. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6914. const name = morphAttribute[ m ].name || String( m );
  6915. this.morphTargetInfluences.push( 0 );
  6916. this.morphTargetDictionary[ name ] = m;
  6917. }
  6918. }
  6919. }
  6920. }
  6921. getVertexPosition( index, target ) {
  6922. const geometry = this.geometry;
  6923. const position = geometry.attributes.position;
  6924. const morphPosition = geometry.morphAttributes.position;
  6925. const morphTargetsRelative = geometry.morphTargetsRelative;
  6926. target.fromBufferAttribute( position, index );
  6927. const morphInfluences = this.morphTargetInfluences;
  6928. if ( morphPosition && morphInfluences ) {
  6929. _morphA.set( 0, 0, 0 );
  6930. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6931. const influence = morphInfluences[ i ];
  6932. const morphAttribute = morphPosition[ i ];
  6933. if ( influence === 0 ) continue;
  6934. _tempA.fromBufferAttribute( morphAttribute, index );
  6935. if ( morphTargetsRelative ) {
  6936. _morphA.addScaledVector( _tempA, influence );
  6937. } else {
  6938. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6939. }
  6940. }
  6941. target.add( _morphA );
  6942. }
  6943. return target;
  6944. }
  6945. raycast( raycaster, intersects ) {
  6946. const geometry = this.geometry;
  6947. const material = this.material;
  6948. const matrixWorld = this.matrixWorld;
  6949. if ( material === undefined ) return;
  6950. // test with bounding sphere in world space
  6951. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6952. _sphere$6.copy( geometry.boundingSphere );
  6953. _sphere$6.applyMatrix4( matrixWorld );
  6954. // check distance from ray origin to bounding sphere
  6955. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6956. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6957. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6958. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6959. }
  6960. // convert ray to local space of mesh
  6961. _inverseMatrix$3.copy( matrixWorld ).invert();
  6962. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6963. // test with bounding box in local space
  6964. if ( geometry.boundingBox !== null ) {
  6965. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6966. }
  6967. // test for intersections with geometry
  6968. this._computeIntersections( raycaster, intersects, _ray$3 );
  6969. }
  6970. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6971. let intersection;
  6972. const geometry = this.geometry;
  6973. const material = this.material;
  6974. const index = geometry.index;
  6975. const position = geometry.attributes.position;
  6976. const uv = geometry.attributes.uv;
  6977. const uv1 = geometry.attributes.uv1;
  6978. const normal = geometry.attributes.normal;
  6979. const groups = geometry.groups;
  6980. const drawRange = geometry.drawRange;
  6981. if ( index !== null ) {
  6982. // indexed buffer geometry
  6983. if ( Array.isArray( material ) ) {
  6984. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6985. const group = groups[ i ];
  6986. const groupMaterial = material[ group.materialIndex ];
  6987. const start = Math.max( group.start, drawRange.start );
  6988. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6989. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6990. const a = index.getX( j );
  6991. const b = index.getX( j + 1 );
  6992. const c = index.getX( j + 2 );
  6993. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6994. if ( intersection ) {
  6995. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6996. intersection.face.materialIndex = group.materialIndex;
  6997. intersects.push( intersection );
  6998. }
  6999. }
  7000. }
  7001. } else {
  7002. const start = Math.max( 0, drawRange.start );
  7003. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7004. for ( let i = start, il = end; i < il; i += 3 ) {
  7005. const a = index.getX( i );
  7006. const b = index.getX( i + 1 );
  7007. const c = index.getX( i + 2 );
  7008. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7009. if ( intersection ) {
  7010. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7011. intersects.push( intersection );
  7012. }
  7013. }
  7014. }
  7015. } else if ( position !== undefined ) {
  7016. // non-indexed buffer geometry
  7017. if ( Array.isArray( material ) ) {
  7018. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7019. const group = groups[ i ];
  7020. const groupMaterial = material[ group.materialIndex ];
  7021. const start = Math.max( group.start, drawRange.start );
  7022. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7023. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7024. const a = j;
  7025. const b = j + 1;
  7026. const c = j + 2;
  7027. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7028. if ( intersection ) {
  7029. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7030. intersection.face.materialIndex = group.materialIndex;
  7031. intersects.push( intersection );
  7032. }
  7033. }
  7034. }
  7035. } else {
  7036. const start = Math.max( 0, drawRange.start );
  7037. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7038. for ( let i = start, il = end; i < il; i += 3 ) {
  7039. const a = i;
  7040. const b = i + 1;
  7041. const c = i + 2;
  7042. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7043. if ( intersection ) {
  7044. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7045. intersects.push( intersection );
  7046. }
  7047. }
  7048. }
  7049. }
  7050. }
  7051. }
  7052. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7053. let intersect;
  7054. if ( material.side === BackSide ) {
  7055. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7056. } else {
  7057. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7058. }
  7059. if ( intersect === null ) return null;
  7060. _intersectionPointWorld.copy( point );
  7061. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7062. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7063. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7064. return {
  7065. distance: distance,
  7066. point: _intersectionPointWorld.clone(),
  7067. object: object
  7068. };
  7069. }
  7070. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7071. object.getVertexPosition( a, _vA$1 );
  7072. object.getVertexPosition( b, _vB$1 );
  7073. object.getVertexPosition( c, _vC$1 );
  7074. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7075. if ( intersection ) {
  7076. const barycoord = new Vector3();
  7077. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  7078. if ( uv ) {
  7079. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  7080. }
  7081. if ( uv1 ) {
  7082. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  7083. }
  7084. if ( normal ) {
  7085. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  7086. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7087. intersection.normal.multiplyScalar( - 1 );
  7088. }
  7089. }
  7090. const face = {
  7091. a: a,
  7092. b: b,
  7093. c: c,
  7094. normal: new Vector3(),
  7095. materialIndex: 0
  7096. };
  7097. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7098. intersection.face = face;
  7099. intersection.barycoord = barycoord;
  7100. }
  7101. return intersection;
  7102. }
  7103. class BoxGeometry extends BufferGeometry {
  7104. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7105. super();
  7106. this.type = 'BoxGeometry';
  7107. this.parameters = {
  7108. width: width,
  7109. height: height,
  7110. depth: depth,
  7111. widthSegments: widthSegments,
  7112. heightSegments: heightSegments,
  7113. depthSegments: depthSegments
  7114. };
  7115. const scope = this;
  7116. // segments
  7117. widthSegments = Math.floor( widthSegments );
  7118. heightSegments = Math.floor( heightSegments );
  7119. depthSegments = Math.floor( depthSegments );
  7120. // buffers
  7121. const indices = [];
  7122. const vertices = [];
  7123. const normals = [];
  7124. const uvs = [];
  7125. // helper variables
  7126. let numberOfVertices = 0;
  7127. let groupStart = 0;
  7128. // build each side of the box geometry
  7129. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7130. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7131. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7132. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7133. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7134. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7135. // build geometry
  7136. this.setIndex( indices );
  7137. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7138. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7139. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7140. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7141. const segmentWidth = width / gridX;
  7142. const segmentHeight = height / gridY;
  7143. const widthHalf = width / 2;
  7144. const heightHalf = height / 2;
  7145. const depthHalf = depth / 2;
  7146. const gridX1 = gridX + 1;
  7147. const gridY1 = gridY + 1;
  7148. let vertexCounter = 0;
  7149. let groupCount = 0;
  7150. const vector = new Vector3();
  7151. // generate vertices, normals and uvs
  7152. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7153. const y = iy * segmentHeight - heightHalf;
  7154. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7155. const x = ix * segmentWidth - widthHalf;
  7156. // set values to correct vector component
  7157. vector[ u ] = x * udir;
  7158. vector[ v ] = y * vdir;
  7159. vector[ w ] = depthHalf;
  7160. // now apply vector to vertex buffer
  7161. vertices.push( vector.x, vector.y, vector.z );
  7162. // set values to correct vector component
  7163. vector[ u ] = 0;
  7164. vector[ v ] = 0;
  7165. vector[ w ] = depth > 0 ? 1 : - 1;
  7166. // now apply vector to normal buffer
  7167. normals.push( vector.x, vector.y, vector.z );
  7168. // uvs
  7169. uvs.push( ix / gridX );
  7170. uvs.push( 1 - ( iy / gridY ) );
  7171. // counters
  7172. vertexCounter += 1;
  7173. }
  7174. }
  7175. // indices
  7176. // 1. you need three indices to draw a single face
  7177. // 2. a single segment consists of two faces
  7178. // 3. so we need to generate six (2*3) indices per segment
  7179. for ( let iy = 0; iy < gridY; iy ++ ) {
  7180. for ( let ix = 0; ix < gridX; ix ++ ) {
  7181. const a = numberOfVertices + ix + gridX1 * iy;
  7182. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7183. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7184. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7185. // faces
  7186. indices.push( a, b, d );
  7187. indices.push( b, c, d );
  7188. // increase counter
  7189. groupCount += 6;
  7190. }
  7191. }
  7192. // add a group to the geometry. this will ensure multi material support
  7193. scope.addGroup( groupStart, groupCount, materialIndex );
  7194. // calculate new start value for groups
  7195. groupStart += groupCount;
  7196. // update total number of vertices
  7197. numberOfVertices += vertexCounter;
  7198. }
  7199. }
  7200. copy( source ) {
  7201. super.copy( source );
  7202. this.parameters = Object.assign( {}, source.parameters );
  7203. return this;
  7204. }
  7205. static fromJSON( data ) {
  7206. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7207. }
  7208. }
  7209. /**
  7210. * Uniform Utilities
  7211. */
  7212. function cloneUniforms( src ) {
  7213. const dst = {};
  7214. for ( const u in src ) {
  7215. dst[ u ] = {};
  7216. for ( const p in src[ u ] ) {
  7217. const property = src[ u ][ p ];
  7218. if ( property && ( property.isColor ||
  7219. property.isMatrix3 || property.isMatrix4 ||
  7220. property.isVector2 || property.isVector3 || property.isVector4 ||
  7221. property.isTexture || property.isQuaternion ) ) {
  7222. if ( property.isRenderTargetTexture ) {
  7223. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7224. dst[ u ][ p ] = null;
  7225. } else {
  7226. dst[ u ][ p ] = property.clone();
  7227. }
  7228. } else if ( Array.isArray( property ) ) {
  7229. dst[ u ][ p ] = property.slice();
  7230. } else {
  7231. dst[ u ][ p ] = property;
  7232. }
  7233. }
  7234. }
  7235. return dst;
  7236. }
  7237. function cloneUniformsGroups( src ) {
  7238. const dst = [];
  7239. for ( let u = 0; u < src.length; u ++ ) {
  7240. dst.push( src[ u ].clone() );
  7241. }
  7242. return dst;
  7243. }
  7244. var default_vertex = /* glsl */`
  7245. void main() {
  7246. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7247. }
  7248. `;
  7249. var default_fragment = /* glsl */`
  7250. void main() {
  7251. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7252. }
  7253. `;
  7254. class ShaderMaterial extends Material {
  7255. constructor( parameters ) {
  7256. super();
  7257. this.isShaderMaterial = true;
  7258. this.type = 'ShaderMaterial';
  7259. this.defines = {};
  7260. this.uniforms = {};
  7261. this.uniformsGroups = [];
  7262. this.vertexShader = default_vertex;
  7263. this.fragmentShader = default_fragment;
  7264. this.linewidth = 1;
  7265. this.wireframe = false;
  7266. this.wireframeLinewidth = 1;
  7267. this.fog = false; // set to use scene fog
  7268. this.lights = false; // set to use scene lights
  7269. this.clipping = false; // set to use user-defined clipping planes
  7270. this.forceSinglePass = true;
  7271. this.extensions = {
  7272. clipCullDistance: false, // set to use vertex shader clipping
  7273. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7274. };
  7275. // When rendered geometry doesn't include these attributes but the material does,
  7276. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7277. this.defaultAttributeValues = {
  7278. 'color': [ 1, 1, 1 ],
  7279. 'uv': [ 0, 0 ],
  7280. 'uv1': [ 0, 0 ]
  7281. };
  7282. this.index0AttributeName = undefined;
  7283. this.uniformsNeedUpdate = false;
  7284. this.glslVersion = null;
  7285. if ( parameters !== undefined ) {
  7286. this.setValues( parameters );
  7287. }
  7288. }
  7289. copy( source ) {
  7290. super.copy( source );
  7291. this.fragmentShader = source.fragmentShader;
  7292. this.vertexShader = source.vertexShader;
  7293. this.uniforms = cloneUniforms( source.uniforms );
  7294. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7295. this.defines = Object.assign( {}, source.defines );
  7296. this.wireframe = source.wireframe;
  7297. this.wireframeLinewidth = source.wireframeLinewidth;
  7298. this.fog = source.fog;
  7299. this.lights = source.lights;
  7300. this.clipping = source.clipping;
  7301. this.extensions = Object.assign( {}, source.extensions );
  7302. this.glslVersion = source.glslVersion;
  7303. return this;
  7304. }
  7305. toJSON( meta ) {
  7306. const data = super.toJSON( meta );
  7307. data.glslVersion = this.glslVersion;
  7308. data.uniforms = {};
  7309. for ( const name in this.uniforms ) {
  7310. const uniform = this.uniforms[ name ];
  7311. const value = uniform.value;
  7312. if ( value && value.isTexture ) {
  7313. data.uniforms[ name ] = {
  7314. type: 't',
  7315. value: value.toJSON( meta ).uuid
  7316. };
  7317. } else if ( value && value.isColor ) {
  7318. data.uniforms[ name ] = {
  7319. type: 'c',
  7320. value: value.getHex()
  7321. };
  7322. } else if ( value && value.isVector2 ) {
  7323. data.uniforms[ name ] = {
  7324. type: 'v2',
  7325. value: value.toArray()
  7326. };
  7327. } else if ( value && value.isVector3 ) {
  7328. data.uniforms[ name ] = {
  7329. type: 'v3',
  7330. value: value.toArray()
  7331. };
  7332. } else if ( value && value.isVector4 ) {
  7333. data.uniforms[ name ] = {
  7334. type: 'v4',
  7335. value: value.toArray()
  7336. };
  7337. } else if ( value && value.isMatrix3 ) {
  7338. data.uniforms[ name ] = {
  7339. type: 'm3',
  7340. value: value.toArray()
  7341. };
  7342. } else if ( value && value.isMatrix4 ) {
  7343. data.uniforms[ name ] = {
  7344. type: 'm4',
  7345. value: value.toArray()
  7346. };
  7347. } else {
  7348. data.uniforms[ name ] = {
  7349. value: value
  7350. };
  7351. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7352. }
  7353. }
  7354. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7355. data.vertexShader = this.vertexShader;
  7356. data.fragmentShader = this.fragmentShader;
  7357. data.lights = this.lights;
  7358. data.clipping = this.clipping;
  7359. const extensions = {};
  7360. for ( const key in this.extensions ) {
  7361. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7362. }
  7363. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7364. return data;
  7365. }
  7366. }
  7367. class Camera extends Object3D {
  7368. constructor() {
  7369. super();
  7370. this.isCamera = true;
  7371. this.type = 'Camera';
  7372. this.matrixWorldInverse = new Matrix4();
  7373. this.projectionMatrix = new Matrix4();
  7374. this.projectionMatrixInverse = new Matrix4();
  7375. this.coordinateSystem = WebGLCoordinateSystem;
  7376. }
  7377. copy( source, recursive ) {
  7378. super.copy( source, recursive );
  7379. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7380. this.projectionMatrix.copy( source.projectionMatrix );
  7381. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7382. this.coordinateSystem = source.coordinateSystem;
  7383. return this;
  7384. }
  7385. getWorldDirection( target ) {
  7386. return super.getWorldDirection( target ).negate();
  7387. }
  7388. updateMatrixWorld( force ) {
  7389. super.updateMatrixWorld( force );
  7390. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7391. }
  7392. updateWorldMatrix( updateParents, updateChildren ) {
  7393. super.updateWorldMatrix( updateParents, updateChildren );
  7394. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7395. }
  7396. clone() {
  7397. return new this.constructor().copy( this );
  7398. }
  7399. }
  7400. const _v3$1 = /*@__PURE__*/ new Vector3();
  7401. const _minTarget = /*@__PURE__*/ new Vector2();
  7402. const _maxTarget = /*@__PURE__*/ new Vector2();
  7403. class PerspectiveCamera extends Camera {
  7404. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7405. super();
  7406. this.isPerspectiveCamera = true;
  7407. this.type = 'PerspectiveCamera';
  7408. this.fov = fov;
  7409. this.zoom = 1;
  7410. this.near = near;
  7411. this.far = far;
  7412. this.focus = 10;
  7413. this.aspect = aspect;
  7414. this.view = null;
  7415. this.filmGauge = 35; // width of the film (default in millimeters)
  7416. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7417. this.updateProjectionMatrix();
  7418. }
  7419. copy( source, recursive ) {
  7420. super.copy( source, recursive );
  7421. this.fov = source.fov;
  7422. this.zoom = source.zoom;
  7423. this.near = source.near;
  7424. this.far = source.far;
  7425. this.focus = source.focus;
  7426. this.aspect = source.aspect;
  7427. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7428. this.filmGauge = source.filmGauge;
  7429. this.filmOffset = source.filmOffset;
  7430. return this;
  7431. }
  7432. /**
  7433. * Sets the FOV by focal length in respect to the current .filmGauge.
  7434. *
  7435. * The default film gauge is 35, so that the focal length can be specified for
  7436. * a 35mm (full frame) camera.
  7437. *
  7438. * Values for focal length and film gauge must have the same unit.
  7439. */
  7440. setFocalLength( focalLength ) {
  7441. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7442. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7443. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7444. this.updateProjectionMatrix();
  7445. }
  7446. /**
  7447. * Calculates the focal length from the current .fov and .filmGauge.
  7448. */
  7449. getFocalLength() {
  7450. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7451. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7452. }
  7453. getEffectiveFOV() {
  7454. return RAD2DEG * 2 * Math.atan(
  7455. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7456. }
  7457. getFilmWidth() {
  7458. // film not completely covered in portrait format (aspect < 1)
  7459. return this.filmGauge * Math.min( this.aspect, 1 );
  7460. }
  7461. getFilmHeight() {
  7462. // film not completely covered in landscape format (aspect > 1)
  7463. return this.filmGauge / Math.max( this.aspect, 1 );
  7464. }
  7465. /**
  7466. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7467. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7468. */
  7469. getViewBounds( distance, minTarget, maxTarget ) {
  7470. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7471. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7472. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7473. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7474. }
  7475. /**
  7476. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7477. * Copies the result into the target Vector2, where x is width and y is height.
  7478. */
  7479. getViewSize( distance, target ) {
  7480. this.getViewBounds( distance, _minTarget, _maxTarget );
  7481. return target.subVectors( _maxTarget, _minTarget );
  7482. }
  7483. /**
  7484. * Sets an offset in a larger frustum. This is useful for multi-window or
  7485. * multi-monitor/multi-machine setups.
  7486. *
  7487. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7488. * the monitors are in grid like this
  7489. *
  7490. * +---+---+---+
  7491. * | A | B | C |
  7492. * +---+---+---+
  7493. * | D | E | F |
  7494. * +---+---+---+
  7495. *
  7496. * then for each monitor you would call it like this
  7497. *
  7498. * const w = 1920;
  7499. * const h = 1080;
  7500. * const fullWidth = w * 3;
  7501. * const fullHeight = h * 2;
  7502. *
  7503. * --A--
  7504. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7505. * --B--
  7506. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7507. * --C--
  7508. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7509. * --D--
  7510. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7511. * --E--
  7512. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7513. * --F--
  7514. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7515. *
  7516. * Note there is no reason monitors have to be the same size or in a grid.
  7517. */
  7518. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7519. this.aspect = fullWidth / fullHeight;
  7520. if ( this.view === null ) {
  7521. this.view = {
  7522. enabled: true,
  7523. fullWidth: 1,
  7524. fullHeight: 1,
  7525. offsetX: 0,
  7526. offsetY: 0,
  7527. width: 1,
  7528. height: 1
  7529. };
  7530. }
  7531. this.view.enabled = true;
  7532. this.view.fullWidth = fullWidth;
  7533. this.view.fullHeight = fullHeight;
  7534. this.view.offsetX = x;
  7535. this.view.offsetY = y;
  7536. this.view.width = width;
  7537. this.view.height = height;
  7538. this.updateProjectionMatrix();
  7539. }
  7540. clearViewOffset() {
  7541. if ( this.view !== null ) {
  7542. this.view.enabled = false;
  7543. }
  7544. this.updateProjectionMatrix();
  7545. }
  7546. updateProjectionMatrix() {
  7547. const near = this.near;
  7548. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7549. let height = 2 * top;
  7550. let width = this.aspect * height;
  7551. let left = - 0.5 * width;
  7552. const view = this.view;
  7553. if ( this.view !== null && this.view.enabled ) {
  7554. const fullWidth = view.fullWidth,
  7555. fullHeight = view.fullHeight;
  7556. left += view.offsetX * width / fullWidth;
  7557. top -= view.offsetY * height / fullHeight;
  7558. width *= view.width / fullWidth;
  7559. height *= view.height / fullHeight;
  7560. }
  7561. const skew = this.filmOffset;
  7562. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7563. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7564. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7565. }
  7566. toJSON( meta ) {
  7567. const data = super.toJSON( meta );
  7568. data.object.fov = this.fov;
  7569. data.object.zoom = this.zoom;
  7570. data.object.near = this.near;
  7571. data.object.far = this.far;
  7572. data.object.focus = this.focus;
  7573. data.object.aspect = this.aspect;
  7574. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7575. data.object.filmGauge = this.filmGauge;
  7576. data.object.filmOffset = this.filmOffset;
  7577. return data;
  7578. }
  7579. }
  7580. const fov = - 90; // negative fov is not an error
  7581. const aspect = 1;
  7582. class CubeCamera extends Object3D {
  7583. constructor( near, far, renderTarget ) {
  7584. super();
  7585. this.type = 'CubeCamera';
  7586. this.renderTarget = renderTarget;
  7587. this.coordinateSystem = null;
  7588. this.activeMipmapLevel = 0;
  7589. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7590. cameraPX.layers = this.layers;
  7591. this.add( cameraPX );
  7592. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7593. cameraNX.layers = this.layers;
  7594. this.add( cameraNX );
  7595. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7596. cameraPY.layers = this.layers;
  7597. this.add( cameraPY );
  7598. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7599. cameraNY.layers = this.layers;
  7600. this.add( cameraNY );
  7601. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7602. cameraPZ.layers = this.layers;
  7603. this.add( cameraPZ );
  7604. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7605. cameraNZ.layers = this.layers;
  7606. this.add( cameraNZ );
  7607. }
  7608. updateCoordinateSystem() {
  7609. const coordinateSystem = this.coordinateSystem;
  7610. const cameras = this.children.concat();
  7611. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7612. for ( const camera of cameras ) this.remove( camera );
  7613. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7614. cameraPX.up.set( 0, 1, 0 );
  7615. cameraPX.lookAt( 1, 0, 0 );
  7616. cameraNX.up.set( 0, 1, 0 );
  7617. cameraNX.lookAt( - 1, 0, 0 );
  7618. cameraPY.up.set( 0, 0, - 1 );
  7619. cameraPY.lookAt( 0, 1, 0 );
  7620. cameraNY.up.set( 0, 0, 1 );
  7621. cameraNY.lookAt( 0, - 1, 0 );
  7622. cameraPZ.up.set( 0, 1, 0 );
  7623. cameraPZ.lookAt( 0, 0, 1 );
  7624. cameraNZ.up.set( 0, 1, 0 );
  7625. cameraNZ.lookAt( 0, 0, - 1 );
  7626. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7627. cameraPX.up.set( 0, - 1, 0 );
  7628. cameraPX.lookAt( - 1, 0, 0 );
  7629. cameraNX.up.set( 0, - 1, 0 );
  7630. cameraNX.lookAt( 1, 0, 0 );
  7631. cameraPY.up.set( 0, 0, 1 );
  7632. cameraPY.lookAt( 0, 1, 0 );
  7633. cameraNY.up.set( 0, 0, - 1 );
  7634. cameraNY.lookAt( 0, - 1, 0 );
  7635. cameraPZ.up.set( 0, - 1, 0 );
  7636. cameraPZ.lookAt( 0, 0, 1 );
  7637. cameraNZ.up.set( 0, - 1, 0 );
  7638. cameraNZ.lookAt( 0, 0, - 1 );
  7639. } else {
  7640. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7641. }
  7642. for ( const camera of cameras ) {
  7643. this.add( camera );
  7644. camera.updateMatrixWorld();
  7645. }
  7646. }
  7647. update( renderer, scene ) {
  7648. if ( this.parent === null ) this.updateMatrixWorld();
  7649. const { renderTarget, activeMipmapLevel } = this;
  7650. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7651. this.coordinateSystem = renderer.coordinateSystem;
  7652. this.updateCoordinateSystem();
  7653. }
  7654. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7655. const currentRenderTarget = renderer.getRenderTarget();
  7656. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7657. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7658. const currentXrEnabled = renderer.xr.enabled;
  7659. renderer.xr.enabled = false;
  7660. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7661. renderTarget.texture.generateMipmaps = false;
  7662. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7663. renderer.render( scene, cameraPX );
  7664. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7665. renderer.render( scene, cameraNX );
  7666. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7667. renderer.render( scene, cameraPY );
  7668. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7669. renderer.render( scene, cameraNY );
  7670. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7671. renderer.render( scene, cameraPZ );
  7672. // mipmaps are generated during the last call of render()
  7673. // at this point, all sides of the cube render target are defined
  7674. renderTarget.texture.generateMipmaps = generateMipmaps;
  7675. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7676. renderer.render( scene, cameraNZ );
  7677. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7678. renderer.xr.enabled = currentXrEnabled;
  7679. renderTarget.texture.needsPMREMUpdate = true;
  7680. }
  7681. }
  7682. class CubeTexture extends Texture {
  7683. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7684. images = images !== undefined ? images : [];
  7685. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7686. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7687. this.isCubeTexture = true;
  7688. this.flipY = false;
  7689. }
  7690. get images() {
  7691. return this.image;
  7692. }
  7693. set images( value ) {
  7694. this.image = value;
  7695. }
  7696. }
  7697. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7698. constructor( size = 1, options = {} ) {
  7699. super( size, size, options );
  7700. this.isWebGLCubeRenderTarget = true;
  7701. const image = { width: size, height: size, depth: 1 };
  7702. const images = [ image, image, image, image, image, image ];
  7703. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7704. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7705. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7706. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7707. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7708. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7709. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7710. this.texture.isRenderTargetTexture = true;
  7711. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7712. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7713. }
  7714. fromEquirectangularTexture( renderer, texture ) {
  7715. this.texture.type = texture.type;
  7716. this.texture.colorSpace = texture.colorSpace;
  7717. this.texture.generateMipmaps = texture.generateMipmaps;
  7718. this.texture.minFilter = texture.minFilter;
  7719. this.texture.magFilter = texture.magFilter;
  7720. const shader = {
  7721. uniforms: {
  7722. tEquirect: { value: null },
  7723. },
  7724. vertexShader: /* glsl */`
  7725. varying vec3 vWorldDirection;
  7726. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7727. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7728. }
  7729. void main() {
  7730. vWorldDirection = transformDirection( position, modelMatrix );
  7731. #include <begin_vertex>
  7732. #include <project_vertex>
  7733. }
  7734. `,
  7735. fragmentShader: /* glsl */`
  7736. uniform sampler2D tEquirect;
  7737. varying vec3 vWorldDirection;
  7738. #include <common>
  7739. void main() {
  7740. vec3 direction = normalize( vWorldDirection );
  7741. vec2 sampleUV = equirectUv( direction );
  7742. gl_FragColor = texture2D( tEquirect, sampleUV );
  7743. }
  7744. `
  7745. };
  7746. const geometry = new BoxGeometry( 5, 5, 5 );
  7747. const material = new ShaderMaterial( {
  7748. name: 'CubemapFromEquirect',
  7749. uniforms: cloneUniforms( shader.uniforms ),
  7750. vertexShader: shader.vertexShader,
  7751. fragmentShader: shader.fragmentShader,
  7752. side: BackSide,
  7753. blending: NoBlending
  7754. } );
  7755. material.uniforms.tEquirect.value = texture;
  7756. const mesh = new Mesh( geometry, material );
  7757. const currentMinFilter = texture.minFilter;
  7758. // Avoid blurred poles
  7759. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7760. const camera = new CubeCamera( 1, 10, this );
  7761. camera.update( renderer, mesh );
  7762. texture.minFilter = currentMinFilter;
  7763. mesh.geometry.dispose();
  7764. mesh.material.dispose();
  7765. return this;
  7766. }
  7767. clear( renderer, color, depth, stencil ) {
  7768. const currentRenderTarget = renderer.getRenderTarget();
  7769. for ( let i = 0; i < 6; i ++ ) {
  7770. renderer.setRenderTarget( this, i );
  7771. renderer.clear( color, depth, stencil );
  7772. }
  7773. renderer.setRenderTarget( currentRenderTarget );
  7774. }
  7775. }
  7776. class FogExp2 {
  7777. constructor( color, density = 0.00025 ) {
  7778. this.isFogExp2 = true;
  7779. this.name = '';
  7780. this.color = new Color( color );
  7781. this.density = density;
  7782. }
  7783. clone() {
  7784. return new FogExp2( this.color, this.density );
  7785. }
  7786. toJSON( /* meta */ ) {
  7787. return {
  7788. type: 'FogExp2',
  7789. name: this.name,
  7790. color: this.color.getHex(),
  7791. density: this.density
  7792. };
  7793. }
  7794. }
  7795. class Fog {
  7796. constructor( color, near = 1, far = 1000 ) {
  7797. this.isFog = true;
  7798. this.name = '';
  7799. this.color = new Color( color );
  7800. this.near = near;
  7801. this.far = far;
  7802. }
  7803. clone() {
  7804. return new Fog( this.color, this.near, this.far );
  7805. }
  7806. toJSON( /* meta */ ) {
  7807. return {
  7808. type: 'Fog',
  7809. name: this.name,
  7810. color: this.color.getHex(),
  7811. near: this.near,
  7812. far: this.far
  7813. };
  7814. }
  7815. }
  7816. class Scene extends Object3D {
  7817. constructor() {
  7818. super();
  7819. this.isScene = true;
  7820. this.type = 'Scene';
  7821. this.background = null;
  7822. this.environment = null;
  7823. this.fog = null;
  7824. this.backgroundBlurriness = 0;
  7825. this.backgroundIntensity = 1;
  7826. this.backgroundRotation = new Euler();
  7827. this.environmentIntensity = 1;
  7828. this.environmentRotation = new Euler();
  7829. this.overrideMaterial = null;
  7830. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7831. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7832. }
  7833. }
  7834. copy( source, recursive ) {
  7835. super.copy( source, recursive );
  7836. if ( source.background !== null ) this.background = source.background.clone();
  7837. if ( source.environment !== null ) this.environment = source.environment.clone();
  7838. if ( source.fog !== null ) this.fog = source.fog.clone();
  7839. this.backgroundBlurriness = source.backgroundBlurriness;
  7840. this.backgroundIntensity = source.backgroundIntensity;
  7841. this.backgroundRotation.copy( source.backgroundRotation );
  7842. this.environmentIntensity = source.environmentIntensity;
  7843. this.environmentRotation.copy( source.environmentRotation );
  7844. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7845. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7846. return this;
  7847. }
  7848. toJSON( meta ) {
  7849. const data = super.toJSON( meta );
  7850. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7851. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7852. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7853. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7854. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7855. data.object.environmentRotation = this.environmentRotation.toArray();
  7856. return data;
  7857. }
  7858. }
  7859. class InterleavedBuffer {
  7860. constructor( array, stride ) {
  7861. this.isInterleavedBuffer = true;
  7862. this.array = array;
  7863. this.stride = stride;
  7864. this.count = array !== undefined ? array.length / stride : 0;
  7865. this.usage = StaticDrawUsage;
  7866. this.updateRanges = [];
  7867. this.version = 0;
  7868. this.uuid = generateUUID();
  7869. }
  7870. onUploadCallback() {}
  7871. set needsUpdate( value ) {
  7872. if ( value === true ) this.version ++;
  7873. }
  7874. setUsage( value ) {
  7875. this.usage = value;
  7876. return this;
  7877. }
  7878. addUpdateRange( start, count ) {
  7879. this.updateRanges.push( { start, count } );
  7880. }
  7881. clearUpdateRanges() {
  7882. this.updateRanges.length = 0;
  7883. }
  7884. copy( source ) {
  7885. this.array = new source.array.constructor( source.array );
  7886. this.count = source.count;
  7887. this.stride = source.stride;
  7888. this.usage = source.usage;
  7889. return this;
  7890. }
  7891. copyAt( index1, attribute, index2 ) {
  7892. index1 *= this.stride;
  7893. index2 *= attribute.stride;
  7894. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7895. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7896. }
  7897. return this;
  7898. }
  7899. set( value, offset = 0 ) {
  7900. this.array.set( value, offset );
  7901. return this;
  7902. }
  7903. clone( data ) {
  7904. if ( data.arrayBuffers === undefined ) {
  7905. data.arrayBuffers = {};
  7906. }
  7907. if ( this.array.buffer._uuid === undefined ) {
  7908. this.array.buffer._uuid = generateUUID();
  7909. }
  7910. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7911. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7912. }
  7913. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7914. const ib = new this.constructor( array, this.stride );
  7915. ib.setUsage( this.usage );
  7916. return ib;
  7917. }
  7918. onUpload( callback ) {
  7919. this.onUploadCallback = callback;
  7920. return this;
  7921. }
  7922. toJSON( data ) {
  7923. if ( data.arrayBuffers === undefined ) {
  7924. data.arrayBuffers = {};
  7925. }
  7926. // generate UUID for array buffer if necessary
  7927. if ( this.array.buffer._uuid === undefined ) {
  7928. this.array.buffer._uuid = generateUUID();
  7929. }
  7930. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7931. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7932. }
  7933. //
  7934. return {
  7935. uuid: this.uuid,
  7936. buffer: this.array.buffer._uuid,
  7937. type: this.array.constructor.name,
  7938. stride: this.stride
  7939. };
  7940. }
  7941. }
  7942. const _vector$7 = /*@__PURE__*/ new Vector3();
  7943. class InterleavedBufferAttribute {
  7944. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7945. this.isInterleavedBufferAttribute = true;
  7946. this.name = '';
  7947. this.data = interleavedBuffer;
  7948. this.itemSize = itemSize;
  7949. this.offset = offset;
  7950. this.normalized = normalized;
  7951. }
  7952. get count() {
  7953. return this.data.count;
  7954. }
  7955. get array() {
  7956. return this.data.array;
  7957. }
  7958. set needsUpdate( value ) {
  7959. this.data.needsUpdate = value;
  7960. }
  7961. applyMatrix4( m ) {
  7962. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  7963. _vector$7.fromBufferAttribute( this, i );
  7964. _vector$7.applyMatrix4( m );
  7965. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7966. }
  7967. return this;
  7968. }
  7969. applyNormalMatrix( m ) {
  7970. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7971. _vector$7.fromBufferAttribute( this, i );
  7972. _vector$7.applyNormalMatrix( m );
  7973. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7974. }
  7975. return this;
  7976. }
  7977. transformDirection( m ) {
  7978. for ( let i = 0, l = this.count; i < l; i ++ ) {
  7979. _vector$7.fromBufferAttribute( this, i );
  7980. _vector$7.transformDirection( m );
  7981. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7982. }
  7983. return this;
  7984. }
  7985. getComponent( index, component ) {
  7986. let value = this.array[ index * this.data.stride + this.offset + component ];
  7987. if ( this.normalized ) value = denormalize( value, this.array );
  7988. return value;
  7989. }
  7990. setComponent( index, component, value ) {
  7991. if ( this.normalized ) value = normalize$1( value, this.array );
  7992. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  7993. return this;
  7994. }
  7995. setX( index, x ) {
  7996. if ( this.normalized ) x = normalize$1( x, this.array );
  7997. this.data.array[ index * this.data.stride + this.offset ] = x;
  7998. return this;
  7999. }
  8000. setY( index, y ) {
  8001. if ( this.normalized ) y = normalize$1( y, this.array );
  8002. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8003. return this;
  8004. }
  8005. setZ( index, z ) {
  8006. if ( this.normalized ) z = normalize$1( z, this.array );
  8007. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8008. return this;
  8009. }
  8010. setW( index, w ) {
  8011. if ( this.normalized ) w = normalize$1( w, this.array );
  8012. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8013. return this;
  8014. }
  8015. getX( index ) {
  8016. let x = this.data.array[ index * this.data.stride + this.offset ];
  8017. if ( this.normalized ) x = denormalize( x, this.array );
  8018. return x;
  8019. }
  8020. getY( index ) {
  8021. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8022. if ( this.normalized ) y = denormalize( y, this.array );
  8023. return y;
  8024. }
  8025. getZ( index ) {
  8026. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8027. if ( this.normalized ) z = denormalize( z, this.array );
  8028. return z;
  8029. }
  8030. getW( index ) {
  8031. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8032. if ( this.normalized ) w = denormalize( w, this.array );
  8033. return w;
  8034. }
  8035. setXY( index, x, y ) {
  8036. index = index * this.data.stride + this.offset;
  8037. if ( this.normalized ) {
  8038. x = normalize$1( x, this.array );
  8039. y = normalize$1( y, this.array );
  8040. }
  8041. this.data.array[ index + 0 ] = x;
  8042. this.data.array[ index + 1 ] = y;
  8043. return this;
  8044. }
  8045. setXYZ( index, x, y, z ) {
  8046. index = index * this.data.stride + this.offset;
  8047. if ( this.normalized ) {
  8048. x = normalize$1( x, this.array );
  8049. y = normalize$1( y, this.array );
  8050. z = normalize$1( z, this.array );
  8051. }
  8052. this.data.array[ index + 0 ] = x;
  8053. this.data.array[ index + 1 ] = y;
  8054. this.data.array[ index + 2 ] = z;
  8055. return this;
  8056. }
  8057. setXYZW( index, x, y, z, w ) {
  8058. index = index * this.data.stride + this.offset;
  8059. if ( this.normalized ) {
  8060. x = normalize$1( x, this.array );
  8061. y = normalize$1( y, this.array );
  8062. z = normalize$1( z, this.array );
  8063. w = normalize$1( w, this.array );
  8064. }
  8065. this.data.array[ index + 0 ] = x;
  8066. this.data.array[ index + 1 ] = y;
  8067. this.data.array[ index + 2 ] = z;
  8068. this.data.array[ index + 3 ] = w;
  8069. return this;
  8070. }
  8071. clone( data ) {
  8072. if ( data === undefined ) {
  8073. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8074. const array = [];
  8075. for ( let i = 0; i < this.count; i ++ ) {
  8076. const index = i * this.data.stride + this.offset;
  8077. for ( let j = 0; j < this.itemSize; j ++ ) {
  8078. array.push( this.data.array[ index + j ] );
  8079. }
  8080. }
  8081. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8082. } else {
  8083. if ( data.interleavedBuffers === undefined ) {
  8084. data.interleavedBuffers = {};
  8085. }
  8086. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8087. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8088. }
  8089. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8090. }
  8091. }
  8092. toJSON( data ) {
  8093. if ( data === undefined ) {
  8094. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8095. const array = [];
  8096. for ( let i = 0; i < this.count; i ++ ) {
  8097. const index = i * this.data.stride + this.offset;
  8098. for ( let j = 0; j < this.itemSize; j ++ ) {
  8099. array.push( this.data.array[ index + j ] );
  8100. }
  8101. }
  8102. // de-interleave data and save it as an ordinary buffer attribute for now
  8103. return {
  8104. itemSize: this.itemSize,
  8105. type: this.array.constructor.name,
  8106. array: array,
  8107. normalized: this.normalized
  8108. };
  8109. } else {
  8110. // save as true interleaved attribute
  8111. if ( data.interleavedBuffers === undefined ) {
  8112. data.interleavedBuffers = {};
  8113. }
  8114. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8115. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8116. }
  8117. return {
  8118. isInterleavedBufferAttribute: true,
  8119. itemSize: this.itemSize,
  8120. data: this.data.uuid,
  8121. offset: this.offset,
  8122. normalized: this.normalized
  8123. };
  8124. }
  8125. }
  8126. }
  8127. class SpriteMaterial extends Material {
  8128. constructor( parameters ) {
  8129. super();
  8130. this.isSpriteMaterial = true;
  8131. this.type = 'SpriteMaterial';
  8132. this.color = new Color( 0xffffff );
  8133. this.map = null;
  8134. this.alphaMap = null;
  8135. this.rotation = 0;
  8136. this.sizeAttenuation = true;
  8137. this.transparent = true;
  8138. this.fog = true;
  8139. this.setValues( parameters );
  8140. }
  8141. copy( source ) {
  8142. super.copy( source );
  8143. this.color.copy( source.color );
  8144. this.map = source.map;
  8145. this.alphaMap = source.alphaMap;
  8146. this.rotation = source.rotation;
  8147. this.sizeAttenuation = source.sizeAttenuation;
  8148. this.fog = source.fog;
  8149. return this;
  8150. }
  8151. }
  8152. let _geometry$1;
  8153. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8154. const _worldScale = /*@__PURE__*/ new Vector3();
  8155. const _mvPosition = /*@__PURE__*/ new Vector3();
  8156. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8157. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8158. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8159. const _vA = /*@__PURE__*/ new Vector3();
  8160. const _vB = /*@__PURE__*/ new Vector3();
  8161. const _vC = /*@__PURE__*/ new Vector3();
  8162. const _uvA = /*@__PURE__*/ new Vector2();
  8163. const _uvB = /*@__PURE__*/ new Vector2();
  8164. const _uvC = /*@__PURE__*/ new Vector2();
  8165. class Sprite extends Object3D {
  8166. constructor( material = new SpriteMaterial() ) {
  8167. super();
  8168. this.isSprite = true;
  8169. this.type = 'Sprite';
  8170. if ( _geometry$1 === undefined ) {
  8171. _geometry$1 = new BufferGeometry();
  8172. const float32Array = new Float32Array( [
  8173. - 0.5, - 0.5, 0, 0, 0,
  8174. 0.5, - 0.5, 0, 1, 0,
  8175. 0.5, 0.5, 0, 1, 1,
  8176. - 0.5, 0.5, 0, 0, 1
  8177. ] );
  8178. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8179. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8180. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8181. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8182. }
  8183. this.geometry = _geometry$1;
  8184. this.material = material;
  8185. this.center = new Vector2( 0.5, 0.5 );
  8186. }
  8187. raycast( raycaster, intersects ) {
  8188. if ( raycaster.camera === null ) {
  8189. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8190. }
  8191. _worldScale.setFromMatrixScale( this.matrixWorld );
  8192. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8193. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8194. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8195. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8196. _worldScale.multiplyScalar( - _mvPosition.z );
  8197. }
  8198. const rotation = this.material.rotation;
  8199. let sin, cos;
  8200. if ( rotation !== 0 ) {
  8201. cos = Math.cos( rotation );
  8202. sin = Math.sin( rotation );
  8203. }
  8204. const center = this.center;
  8205. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8206. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8207. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8208. _uvA.set( 0, 0 );
  8209. _uvB.set( 1, 0 );
  8210. _uvC.set( 1, 1 );
  8211. // check first triangle
  8212. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8213. if ( intersect === null ) {
  8214. // check second triangle
  8215. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8216. _uvB.set( 0, 1 );
  8217. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8218. if ( intersect === null ) {
  8219. return;
  8220. }
  8221. }
  8222. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8223. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8224. intersects.push( {
  8225. distance: distance,
  8226. point: _intersectPoint.clone(),
  8227. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8228. face: null,
  8229. object: this
  8230. } );
  8231. }
  8232. copy( source, recursive ) {
  8233. super.copy( source, recursive );
  8234. if ( source.center !== undefined ) this.center.copy( source.center );
  8235. this.material = source.material;
  8236. return this;
  8237. }
  8238. }
  8239. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8240. // compute position in camera space
  8241. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8242. // to check if rotation is not zero
  8243. if ( sin !== undefined ) {
  8244. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8245. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8246. } else {
  8247. _rotatedPosition.copy( _alignedPosition );
  8248. }
  8249. vertexPosition.copy( mvPosition );
  8250. vertexPosition.x += _rotatedPosition.x;
  8251. vertexPosition.y += _rotatedPosition.y;
  8252. // transform to world space
  8253. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8254. }
  8255. const _v1$2 = /*@__PURE__*/ new Vector3();
  8256. const _v2$1 = /*@__PURE__*/ new Vector3();
  8257. class LOD extends Object3D {
  8258. constructor() {
  8259. super();
  8260. this._currentLevel = 0;
  8261. this.type = 'LOD';
  8262. Object.defineProperties( this, {
  8263. levels: {
  8264. enumerable: true,
  8265. value: []
  8266. },
  8267. isLOD: {
  8268. value: true,
  8269. }
  8270. } );
  8271. this.autoUpdate = true;
  8272. }
  8273. copy( source ) {
  8274. super.copy( source, false );
  8275. const levels = source.levels;
  8276. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8277. const level = levels[ i ];
  8278. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8279. }
  8280. this.autoUpdate = source.autoUpdate;
  8281. return this;
  8282. }
  8283. addLevel( object, distance = 0, hysteresis = 0 ) {
  8284. distance = Math.abs( distance );
  8285. const levels = this.levels;
  8286. let l;
  8287. for ( l = 0; l < levels.length; l ++ ) {
  8288. if ( distance < levels[ l ].distance ) {
  8289. break;
  8290. }
  8291. }
  8292. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8293. this.add( object );
  8294. return this;
  8295. }
  8296. removeLevel( distance ) {
  8297. const levels = this.levels;
  8298. for ( let i = 0; i < levels.length; i ++ ) {
  8299. if ( levels[ i ].distance === distance ) {
  8300. const removedElements = levels.splice( i, 1 );
  8301. this.remove( removedElements[ 0 ].object );
  8302. return true;
  8303. }
  8304. }
  8305. return false;
  8306. }
  8307. getCurrentLevel() {
  8308. return this._currentLevel;
  8309. }
  8310. getObjectForDistance( distance ) {
  8311. const levels = this.levels;
  8312. if ( levels.length > 0 ) {
  8313. let i, l;
  8314. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8315. let levelDistance = levels[ i ].distance;
  8316. if ( levels[ i ].object.visible ) {
  8317. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8318. }
  8319. if ( distance < levelDistance ) {
  8320. break;
  8321. }
  8322. }
  8323. return levels[ i - 1 ].object;
  8324. }
  8325. return null;
  8326. }
  8327. raycast( raycaster, intersects ) {
  8328. const levels = this.levels;
  8329. if ( levels.length > 0 ) {
  8330. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8331. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8332. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8333. }
  8334. }
  8335. update( camera ) {
  8336. const levels = this.levels;
  8337. if ( levels.length > 1 ) {
  8338. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8339. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8340. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8341. levels[ 0 ].object.visible = true;
  8342. let i, l;
  8343. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8344. let levelDistance = levels[ i ].distance;
  8345. if ( levels[ i ].object.visible ) {
  8346. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8347. }
  8348. if ( distance >= levelDistance ) {
  8349. levels[ i - 1 ].object.visible = false;
  8350. levels[ i ].object.visible = true;
  8351. } else {
  8352. break;
  8353. }
  8354. }
  8355. this._currentLevel = i - 1;
  8356. for ( ; i < l; i ++ ) {
  8357. levels[ i ].object.visible = false;
  8358. }
  8359. }
  8360. }
  8361. toJSON( meta ) {
  8362. const data = super.toJSON( meta );
  8363. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8364. data.object.levels = [];
  8365. const levels = this.levels;
  8366. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8367. const level = levels[ i ];
  8368. data.object.levels.push( {
  8369. object: level.object.uuid,
  8370. distance: level.distance,
  8371. hysteresis: level.hysteresis
  8372. } );
  8373. }
  8374. return data;
  8375. }
  8376. }
  8377. const _basePosition = /*@__PURE__*/ new Vector3();
  8378. const _skinIndex = /*@__PURE__*/ new Vector4();
  8379. const _skinWeight = /*@__PURE__*/ new Vector4();
  8380. const _vector3 = /*@__PURE__*/ new Vector3();
  8381. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8382. const _vertex = /*@__PURE__*/ new Vector3();
  8383. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8384. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8385. const _ray$2 = /*@__PURE__*/ new Ray();
  8386. class SkinnedMesh extends Mesh {
  8387. constructor( geometry, material ) {
  8388. super( geometry, material );
  8389. this.isSkinnedMesh = true;
  8390. this.type = 'SkinnedMesh';
  8391. this.bindMode = AttachedBindMode;
  8392. this.bindMatrix = new Matrix4();
  8393. this.bindMatrixInverse = new Matrix4();
  8394. this.boundingBox = null;
  8395. this.boundingSphere = null;
  8396. }
  8397. computeBoundingBox() {
  8398. const geometry = this.geometry;
  8399. if ( this.boundingBox === null ) {
  8400. this.boundingBox = new Box3();
  8401. }
  8402. this.boundingBox.makeEmpty();
  8403. const positionAttribute = geometry.getAttribute( 'position' );
  8404. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8405. this.getVertexPosition( i, _vertex );
  8406. this.boundingBox.expandByPoint( _vertex );
  8407. }
  8408. }
  8409. computeBoundingSphere() {
  8410. const geometry = this.geometry;
  8411. if ( this.boundingSphere === null ) {
  8412. this.boundingSphere = new Sphere();
  8413. }
  8414. this.boundingSphere.makeEmpty();
  8415. const positionAttribute = geometry.getAttribute( 'position' );
  8416. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8417. this.getVertexPosition( i, _vertex );
  8418. this.boundingSphere.expandByPoint( _vertex );
  8419. }
  8420. }
  8421. copy( source, recursive ) {
  8422. super.copy( source, recursive );
  8423. this.bindMode = source.bindMode;
  8424. this.bindMatrix.copy( source.bindMatrix );
  8425. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8426. this.skeleton = source.skeleton;
  8427. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8428. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8429. return this;
  8430. }
  8431. raycast( raycaster, intersects ) {
  8432. const material = this.material;
  8433. const matrixWorld = this.matrixWorld;
  8434. if ( material === undefined ) return;
  8435. // test with bounding sphere in world space
  8436. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8437. _sphere$5.copy( this.boundingSphere );
  8438. _sphere$5.applyMatrix4( matrixWorld );
  8439. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8440. // convert ray to local space of skinned mesh
  8441. _inverseMatrix$2.copy( matrixWorld ).invert();
  8442. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8443. // test with bounding box in local space
  8444. if ( this.boundingBox !== null ) {
  8445. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8446. }
  8447. // test for intersections with geometry
  8448. this._computeIntersections( raycaster, intersects, _ray$2 );
  8449. }
  8450. getVertexPosition( index, target ) {
  8451. super.getVertexPosition( index, target );
  8452. this.applyBoneTransform( index, target );
  8453. return target;
  8454. }
  8455. bind( skeleton, bindMatrix ) {
  8456. this.skeleton = skeleton;
  8457. if ( bindMatrix === undefined ) {
  8458. this.updateMatrixWorld( true );
  8459. this.skeleton.calculateInverses();
  8460. bindMatrix = this.matrixWorld;
  8461. }
  8462. this.bindMatrix.copy( bindMatrix );
  8463. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8464. }
  8465. pose() {
  8466. this.skeleton.pose();
  8467. }
  8468. normalizeSkinWeights() {
  8469. const vector = new Vector4();
  8470. const skinWeight = this.geometry.attributes.skinWeight;
  8471. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8472. vector.fromBufferAttribute( skinWeight, i );
  8473. const scale = 1.0 / vector.manhattanLength();
  8474. if ( scale !== Infinity ) {
  8475. vector.multiplyScalar( scale );
  8476. } else {
  8477. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8478. }
  8479. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8480. }
  8481. }
  8482. updateMatrixWorld( force ) {
  8483. super.updateMatrixWorld( force );
  8484. if ( this.bindMode === AttachedBindMode ) {
  8485. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8486. } else if ( this.bindMode === DetachedBindMode ) {
  8487. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8488. } else {
  8489. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8490. }
  8491. }
  8492. applyBoneTransform( index, vector ) {
  8493. const skeleton = this.skeleton;
  8494. const geometry = this.geometry;
  8495. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8496. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8497. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8498. vector.set( 0, 0, 0 );
  8499. for ( let i = 0; i < 4; i ++ ) {
  8500. const weight = _skinWeight.getComponent( i );
  8501. if ( weight !== 0 ) {
  8502. const boneIndex = _skinIndex.getComponent( i );
  8503. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8504. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8505. }
  8506. }
  8507. return vector.applyMatrix4( this.bindMatrixInverse );
  8508. }
  8509. }
  8510. class Bone extends Object3D {
  8511. constructor() {
  8512. super();
  8513. this.isBone = true;
  8514. this.type = 'Bone';
  8515. }
  8516. }
  8517. class DataTexture extends Texture {
  8518. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8519. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8520. this.isDataTexture = true;
  8521. this.image = { data: data, width: width, height: height };
  8522. this.generateMipmaps = false;
  8523. this.flipY = false;
  8524. this.unpackAlignment = 1;
  8525. }
  8526. }
  8527. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8528. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  8529. class Skeleton {
  8530. constructor( bones = [], boneInverses = [] ) {
  8531. this.uuid = generateUUID();
  8532. this.bones = bones.slice( 0 );
  8533. this.boneInverses = boneInverses;
  8534. this.boneMatrices = null;
  8535. this.boneTexture = null;
  8536. this.init();
  8537. }
  8538. init() {
  8539. const bones = this.bones;
  8540. const boneInverses = this.boneInverses;
  8541. this.boneMatrices = new Float32Array( bones.length * 16 );
  8542. // calculate inverse bone matrices if necessary
  8543. if ( boneInverses.length === 0 ) {
  8544. this.calculateInverses();
  8545. } else {
  8546. // handle special case
  8547. if ( bones.length !== boneInverses.length ) {
  8548. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8549. this.boneInverses = [];
  8550. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8551. this.boneInverses.push( new Matrix4() );
  8552. }
  8553. }
  8554. }
  8555. }
  8556. calculateInverses() {
  8557. this.boneInverses.length = 0;
  8558. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8559. const inverse = new Matrix4();
  8560. if ( this.bones[ i ] ) {
  8561. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8562. }
  8563. this.boneInverses.push( inverse );
  8564. }
  8565. }
  8566. pose() {
  8567. // recover the bind-time world matrices
  8568. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8569. const bone = this.bones[ i ];
  8570. if ( bone ) {
  8571. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8572. }
  8573. }
  8574. // compute the local matrices, positions, rotations and scales
  8575. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8576. const bone = this.bones[ i ];
  8577. if ( bone ) {
  8578. if ( bone.parent && bone.parent.isBone ) {
  8579. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8580. bone.matrix.multiply( bone.matrixWorld );
  8581. } else {
  8582. bone.matrix.copy( bone.matrixWorld );
  8583. }
  8584. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8585. }
  8586. }
  8587. }
  8588. update() {
  8589. const bones = this.bones;
  8590. const boneInverses = this.boneInverses;
  8591. const boneMatrices = this.boneMatrices;
  8592. const boneTexture = this.boneTexture;
  8593. // flatten bone matrices to array
  8594. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8595. // compute the offset between the current and the original transform
  8596. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  8597. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8598. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8599. }
  8600. if ( boneTexture !== null ) {
  8601. boneTexture.needsUpdate = true;
  8602. }
  8603. }
  8604. clone() {
  8605. return new Skeleton( this.bones, this.boneInverses );
  8606. }
  8607. computeBoneTexture() {
  8608. // layout (1 matrix = 4 pixels)
  8609. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8610. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8611. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8612. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8613. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8614. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8615. size = Math.ceil( size / 4 ) * 4;
  8616. size = Math.max( size, 4 );
  8617. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8618. boneMatrices.set( this.boneMatrices ); // copy current values
  8619. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8620. boneTexture.needsUpdate = true;
  8621. this.boneMatrices = boneMatrices;
  8622. this.boneTexture = boneTexture;
  8623. return this;
  8624. }
  8625. getBoneByName( name ) {
  8626. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8627. const bone = this.bones[ i ];
  8628. if ( bone.name === name ) {
  8629. return bone;
  8630. }
  8631. }
  8632. return undefined;
  8633. }
  8634. dispose( ) {
  8635. if ( this.boneTexture !== null ) {
  8636. this.boneTexture.dispose();
  8637. this.boneTexture = null;
  8638. }
  8639. }
  8640. fromJSON( json, bones ) {
  8641. this.uuid = json.uuid;
  8642. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8643. const uuid = json.bones[ i ];
  8644. let bone = bones[ uuid ];
  8645. if ( bone === undefined ) {
  8646. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8647. bone = new Bone();
  8648. }
  8649. this.bones.push( bone );
  8650. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8651. }
  8652. this.init();
  8653. return this;
  8654. }
  8655. toJSON() {
  8656. const data = {
  8657. metadata: {
  8658. version: 4.6,
  8659. type: 'Skeleton',
  8660. generator: 'Skeleton.toJSON'
  8661. },
  8662. bones: [],
  8663. boneInverses: []
  8664. };
  8665. data.uuid = this.uuid;
  8666. const bones = this.bones;
  8667. const boneInverses = this.boneInverses;
  8668. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8669. const bone = bones[ i ];
  8670. data.bones.push( bone.uuid );
  8671. const boneInverse = boneInverses[ i ];
  8672. data.boneInverses.push( boneInverse.toArray() );
  8673. }
  8674. return data;
  8675. }
  8676. }
  8677. class InstancedBufferAttribute extends BufferAttribute {
  8678. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8679. super( array, itemSize, normalized );
  8680. this.isInstancedBufferAttribute = true;
  8681. this.meshPerAttribute = meshPerAttribute;
  8682. }
  8683. copy( source ) {
  8684. super.copy( source );
  8685. this.meshPerAttribute = source.meshPerAttribute;
  8686. return this;
  8687. }
  8688. toJSON() {
  8689. const data = super.toJSON();
  8690. data.meshPerAttribute = this.meshPerAttribute;
  8691. data.isInstancedBufferAttribute = true;
  8692. return data;
  8693. }
  8694. }
  8695. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8696. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8697. const _instanceIntersects = [];
  8698. const _box3 = /*@__PURE__*/ new Box3();
  8699. const _identity = /*@__PURE__*/ new Matrix4();
  8700. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8701. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8702. class InstancedMesh extends Mesh {
  8703. constructor( geometry, material, count ) {
  8704. super( geometry, material );
  8705. this.isInstancedMesh = true;
  8706. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8707. this.instanceColor = null;
  8708. this.morphTexture = null;
  8709. this.count = count;
  8710. this.boundingBox = null;
  8711. this.boundingSphere = null;
  8712. for ( let i = 0; i < count; i ++ ) {
  8713. this.setMatrixAt( i, _identity );
  8714. }
  8715. }
  8716. computeBoundingBox() {
  8717. const geometry = this.geometry;
  8718. const count = this.count;
  8719. if ( this.boundingBox === null ) {
  8720. this.boundingBox = new Box3();
  8721. }
  8722. if ( geometry.boundingBox === null ) {
  8723. geometry.computeBoundingBox();
  8724. }
  8725. this.boundingBox.makeEmpty();
  8726. for ( let i = 0; i < count; i ++ ) {
  8727. this.getMatrixAt( i, _instanceLocalMatrix );
  8728. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8729. this.boundingBox.union( _box3 );
  8730. }
  8731. }
  8732. computeBoundingSphere() {
  8733. const geometry = this.geometry;
  8734. const count = this.count;
  8735. if ( this.boundingSphere === null ) {
  8736. this.boundingSphere = new Sphere();
  8737. }
  8738. if ( geometry.boundingSphere === null ) {
  8739. geometry.computeBoundingSphere();
  8740. }
  8741. this.boundingSphere.makeEmpty();
  8742. for ( let i = 0; i < count; i ++ ) {
  8743. this.getMatrixAt( i, _instanceLocalMatrix );
  8744. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8745. this.boundingSphere.union( _sphere$4 );
  8746. }
  8747. }
  8748. copy( source, recursive ) {
  8749. super.copy( source, recursive );
  8750. this.instanceMatrix.copy( source.instanceMatrix );
  8751. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8752. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8753. this.count = source.count;
  8754. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8755. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8756. return this;
  8757. }
  8758. getColorAt( index, color ) {
  8759. color.fromArray( this.instanceColor.array, index * 3 );
  8760. }
  8761. getMatrixAt( index, matrix ) {
  8762. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8763. }
  8764. getMorphAt( index, object ) {
  8765. const objectInfluences = object.morphTargetInfluences;
  8766. const array = this.morphTexture.source.data.data;
  8767. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8768. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8769. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8770. objectInfluences[ i ] = array[ dataIndex + i ];
  8771. }
  8772. }
  8773. raycast( raycaster, intersects ) {
  8774. const matrixWorld = this.matrixWorld;
  8775. const raycastTimes = this.count;
  8776. _mesh$1.geometry = this.geometry;
  8777. _mesh$1.material = this.material;
  8778. if ( _mesh$1.material === undefined ) return;
  8779. // test with bounding sphere first
  8780. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8781. _sphere$4.copy( this.boundingSphere );
  8782. _sphere$4.applyMatrix4( matrixWorld );
  8783. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8784. // now test each instance
  8785. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8786. // calculate the world matrix for each instance
  8787. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8788. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8789. // the mesh represents this single instance
  8790. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8791. _mesh$1.raycast( raycaster, _instanceIntersects );
  8792. // process the result of raycast
  8793. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8794. const intersect = _instanceIntersects[ i ];
  8795. intersect.instanceId = instanceId;
  8796. intersect.object = this;
  8797. intersects.push( intersect );
  8798. }
  8799. _instanceIntersects.length = 0;
  8800. }
  8801. }
  8802. setColorAt( index, color ) {
  8803. if ( this.instanceColor === null ) {
  8804. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  8805. }
  8806. color.toArray( this.instanceColor.array, index * 3 );
  8807. }
  8808. setMatrixAt( index, matrix ) {
  8809. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8810. }
  8811. setMorphAt( index, object ) {
  8812. const objectInfluences = object.morphTargetInfluences;
  8813. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8814. if ( this.morphTexture === null ) {
  8815. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8816. }
  8817. const array = this.morphTexture.source.data.data;
  8818. let morphInfluencesSum = 0;
  8819. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8820. morphInfluencesSum += objectInfluences[ i ];
  8821. }
  8822. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8823. const dataIndex = len * index;
  8824. array[ dataIndex ] = morphBaseInfluence;
  8825. array.set( objectInfluences, dataIndex + 1 );
  8826. }
  8827. updateMorphTargets() {
  8828. }
  8829. dispose() {
  8830. this.dispatchEvent( { type: 'dispose' } );
  8831. if ( this.morphTexture !== null ) {
  8832. this.morphTexture.dispose();
  8833. this.morphTexture = null;
  8834. }
  8835. return this;
  8836. }
  8837. }
  8838. const _vector1 = /*@__PURE__*/ new Vector3();
  8839. const _vector2 = /*@__PURE__*/ new Vector3();
  8840. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8841. class Plane {
  8842. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8843. this.isPlane = true;
  8844. // normal is assumed to be normalized
  8845. this.normal = normal;
  8846. this.constant = constant;
  8847. }
  8848. set( normal, constant ) {
  8849. this.normal.copy( normal );
  8850. this.constant = constant;
  8851. return this;
  8852. }
  8853. setComponents( x, y, z, w ) {
  8854. this.normal.set( x, y, z );
  8855. this.constant = w;
  8856. return this;
  8857. }
  8858. setFromNormalAndCoplanarPoint( normal, point ) {
  8859. this.normal.copy( normal );
  8860. this.constant = - point.dot( this.normal );
  8861. return this;
  8862. }
  8863. setFromCoplanarPoints( a, b, c ) {
  8864. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8865. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8866. this.setFromNormalAndCoplanarPoint( normal, a );
  8867. return this;
  8868. }
  8869. copy( plane ) {
  8870. this.normal.copy( plane.normal );
  8871. this.constant = plane.constant;
  8872. return this;
  8873. }
  8874. normalize() {
  8875. // Note: will lead to a divide by zero if the plane is invalid.
  8876. const inverseNormalLength = 1.0 / this.normal.length();
  8877. this.normal.multiplyScalar( inverseNormalLength );
  8878. this.constant *= inverseNormalLength;
  8879. return this;
  8880. }
  8881. negate() {
  8882. this.constant *= - 1;
  8883. this.normal.negate();
  8884. return this;
  8885. }
  8886. distanceToPoint( point ) {
  8887. return this.normal.dot( point ) + this.constant;
  8888. }
  8889. distanceToSphere( sphere ) {
  8890. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8891. }
  8892. projectPoint( point, target ) {
  8893. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8894. }
  8895. intersectLine( line, target ) {
  8896. const direction = line.delta( _vector1 );
  8897. const denominator = this.normal.dot( direction );
  8898. if ( denominator === 0 ) {
  8899. // line is coplanar, return origin
  8900. if ( this.distanceToPoint( line.start ) === 0 ) {
  8901. return target.copy( line.start );
  8902. }
  8903. // Unsure if this is the correct method to handle this case.
  8904. return null;
  8905. }
  8906. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8907. if ( t < 0 || t > 1 ) {
  8908. return null;
  8909. }
  8910. return target.copy( line.start ).addScaledVector( direction, t );
  8911. }
  8912. intersectsLine( line ) {
  8913. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8914. const startSign = this.distanceToPoint( line.start );
  8915. const endSign = this.distanceToPoint( line.end );
  8916. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8917. }
  8918. intersectsBox( box ) {
  8919. return box.intersectsPlane( this );
  8920. }
  8921. intersectsSphere( sphere ) {
  8922. return sphere.intersectsPlane( this );
  8923. }
  8924. coplanarPoint( target ) {
  8925. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8926. }
  8927. applyMatrix4( matrix, optionalNormalMatrix ) {
  8928. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8929. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8930. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8931. this.constant = - referencePoint.dot( normal );
  8932. return this;
  8933. }
  8934. translate( offset ) {
  8935. this.constant -= offset.dot( this.normal );
  8936. return this;
  8937. }
  8938. equals( plane ) {
  8939. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8940. }
  8941. clone() {
  8942. return new this.constructor().copy( this );
  8943. }
  8944. }
  8945. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8946. const _vector$6 = /*@__PURE__*/ new Vector3();
  8947. class Frustum {
  8948. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8949. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8950. }
  8951. set( p0, p1, p2, p3, p4, p5 ) {
  8952. const planes = this.planes;
  8953. planes[ 0 ].copy( p0 );
  8954. planes[ 1 ].copy( p1 );
  8955. planes[ 2 ].copy( p2 );
  8956. planes[ 3 ].copy( p3 );
  8957. planes[ 4 ].copy( p4 );
  8958. planes[ 5 ].copy( p5 );
  8959. return this;
  8960. }
  8961. copy( frustum ) {
  8962. const planes = this.planes;
  8963. for ( let i = 0; i < 6; i ++ ) {
  8964. planes[ i ].copy( frustum.planes[ i ] );
  8965. }
  8966. return this;
  8967. }
  8968. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  8969. const planes = this.planes;
  8970. const me = m.elements;
  8971. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8972. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8973. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8974. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8975. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8976. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8977. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8978. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8979. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8980. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8981. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8982. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8983. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  8984. } else {
  8985. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  8986. }
  8987. return this;
  8988. }
  8989. intersectsObject( object ) {
  8990. if ( object.boundingSphere !== undefined ) {
  8991. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  8992. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  8993. } else {
  8994. const geometry = object.geometry;
  8995. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8996. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8997. }
  8998. return this.intersectsSphere( _sphere$3 );
  8999. }
  9000. intersectsSprite( sprite ) {
  9001. _sphere$3.center.set( 0, 0, 0 );
  9002. _sphere$3.radius = 0.7071067811865476;
  9003. _sphere$3.applyMatrix4( sprite.matrixWorld );
  9004. return this.intersectsSphere( _sphere$3 );
  9005. }
  9006. intersectsSphere( sphere ) {
  9007. const planes = this.planes;
  9008. const center = sphere.center;
  9009. const negRadius = - sphere.radius;
  9010. for ( let i = 0; i < 6; i ++ ) {
  9011. const distance = planes[ i ].distanceToPoint( center );
  9012. if ( distance < negRadius ) {
  9013. return false;
  9014. }
  9015. }
  9016. return true;
  9017. }
  9018. intersectsBox( box ) {
  9019. const planes = this.planes;
  9020. for ( let i = 0; i < 6; i ++ ) {
  9021. const plane = planes[ i ];
  9022. // corner at max distance
  9023. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9024. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9025. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9026. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9027. return false;
  9028. }
  9029. }
  9030. return true;
  9031. }
  9032. containsPoint( point ) {
  9033. const planes = this.planes;
  9034. for ( let i = 0; i < 6; i ++ ) {
  9035. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9036. return false;
  9037. }
  9038. }
  9039. return true;
  9040. }
  9041. clone() {
  9042. return new this.constructor().copy( this );
  9043. }
  9044. }
  9045. function sortOpaque( a, b ) {
  9046. return a.z - b.z;
  9047. }
  9048. function sortTransparent( a, b ) {
  9049. return b.z - a.z;
  9050. }
  9051. class MultiDrawRenderList {
  9052. constructor() {
  9053. this.index = 0;
  9054. this.pool = [];
  9055. this.list = [];
  9056. }
  9057. push( drawRange, z, index ) {
  9058. const pool = this.pool;
  9059. const list = this.list;
  9060. if ( this.index >= pool.length ) {
  9061. pool.push( {
  9062. start: - 1,
  9063. count: - 1,
  9064. z: - 1,
  9065. index: - 1,
  9066. } );
  9067. }
  9068. const item = pool[ this.index ];
  9069. list.push( item );
  9070. this.index ++;
  9071. item.start = drawRange.start;
  9072. item.count = drawRange.count;
  9073. item.z = z;
  9074. item.index = index;
  9075. }
  9076. reset() {
  9077. this.list.length = 0;
  9078. this.index = 0;
  9079. }
  9080. }
  9081. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9082. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  9083. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  9084. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9085. const _projScreenMatrix$3 = /*@__PURE__*/ new Matrix4();
  9086. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9087. const _box$1 = /*@__PURE__*/ new Box3();
  9088. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9089. const _vector$5 = /*@__PURE__*/ new Vector3();
  9090. const _forward = /*@__PURE__*/ new Vector3();
  9091. const _temp = /*@__PURE__*/ new Vector3();
  9092. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9093. const _mesh = /*@__PURE__*/ new Mesh();
  9094. const _batchIntersects = [];
  9095. // @TODO: SkinnedMesh support?
  9096. // @TODO: geometry.groups support?
  9097. // @TODO: geometry.drawRange support?
  9098. // @TODO: geometry.morphAttributes support?
  9099. // @TODO: Support uniform parameter per geometry
  9100. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  9101. // copies data from attribute "src" into "target" starting at "targetOffset"
  9102. function copyAttributeData( src, target, targetOffset = 0 ) {
  9103. const itemSize = target.itemSize;
  9104. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9105. // use the component getters and setters if the array data cannot
  9106. // be copied directly
  9107. const vertexCount = src.count;
  9108. for ( let i = 0; i < vertexCount; i ++ ) {
  9109. for ( let c = 0; c < itemSize; c ++ ) {
  9110. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9111. }
  9112. }
  9113. } else {
  9114. // faster copy approach using typed array set function
  9115. target.array.set( src.array, targetOffset * itemSize );
  9116. }
  9117. target.needsUpdate = true;
  9118. }
  9119. class BatchedMesh extends Mesh {
  9120. get maxInstanceCount() {
  9121. return this._maxInstanceCount;
  9122. }
  9123. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9124. super( new BufferGeometry(), material );
  9125. this.isBatchedMesh = true;
  9126. this.perObjectFrustumCulled = true;
  9127. this.sortObjects = true;
  9128. this.boundingBox = null;
  9129. this.boundingSphere = null;
  9130. this.customSort = null;
  9131. // stores visible, active, and geometry id per object
  9132. this._drawInfo = [];
  9133. // instance ids that have been set as inactive, and are available to be overwritten
  9134. this._availableInstanceIds = [];
  9135. // geometry information
  9136. this._drawRanges = [];
  9137. this._reservedRanges = [];
  9138. this._bounds = [];
  9139. this._maxInstanceCount = maxInstanceCount;
  9140. this._maxVertexCount = maxVertexCount;
  9141. this._maxIndexCount = maxIndexCount;
  9142. this._geometryInitialized = false;
  9143. this._geometryCount = 0;
  9144. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9145. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9146. this._multiDrawCount = 0;
  9147. this._multiDrawInstances = null;
  9148. this._visibilityChanged = true;
  9149. // Local matrix per geometry by using data texture
  9150. this._matricesTexture = null;
  9151. this._indirectTexture = null;
  9152. this._colorsTexture = null;
  9153. this._initMatricesTexture();
  9154. this._initIndirectTexture();
  9155. }
  9156. _initMatricesTexture() {
  9157. // layout (1 matrix = 4 pixels)
  9158. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9159. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9160. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9161. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9162. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9163. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9164. size = Math.ceil( size / 4 ) * 4;
  9165. size = Math.max( size, 4 );
  9166. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9167. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9168. this._matricesTexture = matricesTexture;
  9169. }
  9170. _initIndirectTexture() {
  9171. let size = Math.sqrt( this._maxInstanceCount );
  9172. size = Math.ceil( size );
  9173. const indirectArray = new Uint32Array( size * size );
  9174. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9175. this._indirectTexture = indirectTexture;
  9176. }
  9177. _initColorsTexture() {
  9178. let size = Math.sqrt( this._maxInstanceCount );
  9179. size = Math.ceil( size );
  9180. // 4 floats per RGBA pixel initialized to white
  9181. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9182. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9183. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9184. this._colorsTexture = colorsTexture;
  9185. }
  9186. _initializeGeometry( reference ) {
  9187. const geometry = this.geometry;
  9188. const maxVertexCount = this._maxVertexCount;
  9189. const maxIndexCount = this._maxIndexCount;
  9190. if ( this._geometryInitialized === false ) {
  9191. for ( const attributeName in reference.attributes ) {
  9192. const srcAttribute = reference.getAttribute( attributeName );
  9193. const { array, itemSize, normalized } = srcAttribute;
  9194. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9195. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9196. geometry.setAttribute( attributeName, dstAttribute );
  9197. }
  9198. if ( reference.getIndex() !== null ) {
  9199. // Reserve last u16 index for primitive restart.
  9200. const indexArray = maxVertexCount > 65535
  9201. ? new Uint32Array( maxIndexCount )
  9202. : new Uint16Array( maxIndexCount );
  9203. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9204. }
  9205. this._geometryInitialized = true;
  9206. }
  9207. }
  9208. // Make sure the geometry is compatible with the existing combined geometry attributes
  9209. _validateGeometry( geometry ) {
  9210. // check to ensure the geometries are using consistent attributes and indices
  9211. const batchGeometry = this.geometry;
  9212. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9213. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  9214. }
  9215. for ( const attributeName in batchGeometry.attributes ) {
  9216. if ( ! geometry.hasAttribute( attributeName ) ) {
  9217. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9218. }
  9219. const srcAttribute = geometry.getAttribute( attributeName );
  9220. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9221. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9222. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9223. }
  9224. }
  9225. }
  9226. setCustomSort( func ) {
  9227. this.customSort = func;
  9228. return this;
  9229. }
  9230. computeBoundingBox() {
  9231. if ( this.boundingBox === null ) {
  9232. this.boundingBox = new Box3();
  9233. }
  9234. const boundingBox = this.boundingBox;
  9235. const drawInfo = this._drawInfo;
  9236. boundingBox.makeEmpty();
  9237. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9238. if ( drawInfo[ i ].active === false ) continue;
  9239. const geometryId = drawInfo[ i ].geometryIndex;
  9240. this.getMatrixAt( i, _matrix$1 );
  9241. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9242. boundingBox.union( _box$1 );
  9243. }
  9244. }
  9245. computeBoundingSphere() {
  9246. if ( this.boundingSphere === null ) {
  9247. this.boundingSphere = new Sphere();
  9248. }
  9249. const boundingSphere = this.boundingSphere;
  9250. const drawInfo = this._drawInfo;
  9251. boundingSphere.makeEmpty();
  9252. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9253. if ( drawInfo[ i ].active === false ) continue;
  9254. const geometryId = drawInfo[ i ].geometryIndex;
  9255. this.getMatrixAt( i, _matrix$1 );
  9256. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9257. boundingSphere.union( _sphere$2 );
  9258. }
  9259. }
  9260. addInstance( geometryId ) {
  9261. const atCapacity = this._drawInfo.length >= this.maxInstanceCount;
  9262. // ensure we're not over geometry
  9263. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  9264. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9265. }
  9266. const instanceDrawInfo = {
  9267. visible: true,
  9268. active: true,
  9269. geometryIndex: geometryId,
  9270. };
  9271. let drawId = null;
  9272. // Prioritize using previously freed instance ids
  9273. if ( this._availableInstanceIds.length > 0 ) {
  9274. drawId = this._availableInstanceIds.pop();
  9275. this._drawInfo[ drawId ] = instanceDrawInfo;
  9276. } else {
  9277. drawId = this._drawInfo.length;
  9278. this._drawInfo.push( instanceDrawInfo );
  9279. }
  9280. const matricesTexture = this._matricesTexture;
  9281. const matricesArray = matricesTexture.image.data;
  9282. _identityMatrix.toArray( matricesArray, drawId * 16 );
  9283. matricesTexture.needsUpdate = true;
  9284. const colorsTexture = this._colorsTexture;
  9285. if ( colorsTexture ) {
  9286. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9287. colorsTexture.needsUpdate = true;
  9288. }
  9289. return drawId;
  9290. }
  9291. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  9292. this._initializeGeometry( geometry );
  9293. this._validateGeometry( geometry );
  9294. // ensure we're not over geometry
  9295. if ( this._drawInfo.length >= this._maxInstanceCount ) {
  9296. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9297. }
  9298. // get the necessary range fo the geometry
  9299. const reservedRange = {
  9300. vertexStart: - 1,
  9301. vertexCount: - 1,
  9302. indexStart: - 1,
  9303. indexCount: - 1,
  9304. };
  9305. let lastRange = null;
  9306. const reservedRanges = this._reservedRanges;
  9307. const drawRanges = this._drawRanges;
  9308. const bounds = this._bounds;
  9309. if ( this._geometryCount !== 0 ) {
  9310. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  9311. }
  9312. if ( vertexCount === - 1 ) {
  9313. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  9314. } else {
  9315. reservedRange.vertexCount = vertexCount;
  9316. }
  9317. if ( lastRange === null ) {
  9318. reservedRange.vertexStart = 0;
  9319. } else {
  9320. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  9321. }
  9322. const index = geometry.getIndex();
  9323. const hasIndex = index !== null;
  9324. if ( hasIndex ) {
  9325. if ( indexCount === - 1 ) {
  9326. reservedRange.indexCount = index.count;
  9327. } else {
  9328. reservedRange.indexCount = indexCount;
  9329. }
  9330. if ( lastRange === null ) {
  9331. reservedRange.indexStart = 0;
  9332. } else {
  9333. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  9334. }
  9335. }
  9336. if (
  9337. reservedRange.indexStart !== - 1 &&
  9338. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  9339. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  9340. ) {
  9341. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9342. }
  9343. // update id
  9344. const geometryId = this._geometryCount;
  9345. this._geometryCount ++;
  9346. // add the reserved range and draw range objects
  9347. reservedRanges.push( reservedRange );
  9348. drawRanges.push( {
  9349. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  9350. count: - 1
  9351. } );
  9352. bounds.push( {
  9353. boxInitialized: false,
  9354. box: new Box3(),
  9355. sphereInitialized: false,
  9356. sphere: new Sphere()
  9357. } );
  9358. // update the geometry
  9359. this.setGeometryAt( geometryId, geometry );
  9360. return geometryId;
  9361. }
  9362. setGeometryAt( geometryId, geometry ) {
  9363. if ( geometryId >= this._geometryCount ) {
  9364. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  9365. }
  9366. this._validateGeometry( geometry );
  9367. const batchGeometry = this.geometry;
  9368. const hasIndex = batchGeometry.getIndex() !== null;
  9369. const dstIndex = batchGeometry.getIndex();
  9370. const srcIndex = geometry.getIndex();
  9371. const reservedRange = this._reservedRanges[ geometryId ];
  9372. if (
  9373. hasIndex &&
  9374. srcIndex.count > reservedRange.indexCount ||
  9375. geometry.attributes.position.count > reservedRange.vertexCount
  9376. ) {
  9377. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  9378. }
  9379. // copy geometry over
  9380. const vertexStart = reservedRange.vertexStart;
  9381. const vertexCount = reservedRange.vertexCount;
  9382. for ( const attributeName in batchGeometry.attributes ) {
  9383. // copy attribute data
  9384. const srcAttribute = geometry.getAttribute( attributeName );
  9385. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9386. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9387. // fill the rest in with zeroes
  9388. const itemSize = srcAttribute.itemSize;
  9389. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  9390. const index = vertexStart + i;
  9391. for ( let c = 0; c < itemSize; c ++ ) {
  9392. dstAttribute.setComponent( index, c, 0 );
  9393. }
  9394. }
  9395. dstAttribute.needsUpdate = true;
  9396. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  9397. }
  9398. // copy index
  9399. if ( hasIndex ) {
  9400. const indexStart = reservedRange.indexStart;
  9401. // copy index data over
  9402. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9403. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9404. }
  9405. // fill the rest in with zeroes
  9406. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  9407. dstIndex.setX( indexStart + i, vertexStart );
  9408. }
  9409. dstIndex.needsUpdate = true;
  9410. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  9411. }
  9412. // store the bounding boxes
  9413. const bound = this._bounds[ geometryId ];
  9414. if ( geometry.boundingBox !== null ) {
  9415. bound.box.copy( geometry.boundingBox );
  9416. bound.boxInitialized = true;
  9417. } else {
  9418. bound.boxInitialized = false;
  9419. }
  9420. if ( geometry.boundingSphere !== null ) {
  9421. bound.sphere.copy( geometry.boundingSphere );
  9422. bound.sphereInitialized = true;
  9423. } else {
  9424. bound.sphereInitialized = false;
  9425. }
  9426. // set drawRange count
  9427. const drawRange = this._drawRanges[ geometryId ];
  9428. const posAttr = geometry.getAttribute( 'position' );
  9429. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  9430. this._visibilityChanged = true;
  9431. return geometryId;
  9432. }
  9433. /*
  9434. deleteGeometry( geometryId ) {
  9435. // TODO: delete geometry and associated instances
  9436. }
  9437. */
  9438. deleteInstance( instanceId ) {
  9439. const drawInfo = this._drawInfo;
  9440. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9441. return this;
  9442. }
  9443. drawInfo[ instanceId ].active = false;
  9444. this._availableInstanceIds.push( instanceId );
  9445. this._visibilityChanged = true;
  9446. return this;
  9447. }
  9448. // get bounding box and compute it if it doesn't exist
  9449. getBoundingBoxAt( geometryId, target ) {
  9450. if ( geometryId >= this._geometryCount ) {
  9451. return null;
  9452. }
  9453. // compute bounding box
  9454. const bound = this._bounds[ geometryId ];
  9455. const box = bound.box;
  9456. const geometry = this.geometry;
  9457. if ( bound.boxInitialized === false ) {
  9458. box.makeEmpty();
  9459. const index = geometry.index;
  9460. const position = geometry.attributes.position;
  9461. const drawRange = this._drawRanges[ geometryId ];
  9462. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9463. let iv = i;
  9464. if ( index ) {
  9465. iv = index.getX( iv );
  9466. }
  9467. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9468. }
  9469. bound.boxInitialized = true;
  9470. }
  9471. target.copy( box );
  9472. return target;
  9473. }
  9474. // get bounding sphere and compute it if it doesn't exist
  9475. getBoundingSphereAt( geometryId, target ) {
  9476. if ( geometryId >= this._geometryCount ) {
  9477. return null;
  9478. }
  9479. // compute bounding sphere
  9480. const bound = this._bounds[ geometryId ];
  9481. const sphere = bound.sphere;
  9482. const geometry = this.geometry;
  9483. if ( bound.sphereInitialized === false ) {
  9484. sphere.makeEmpty();
  9485. this.getBoundingBoxAt( geometryId, _box$1 );
  9486. _box$1.getCenter( sphere.center );
  9487. const index = geometry.index;
  9488. const position = geometry.attributes.position;
  9489. const drawRange = this._drawRanges[ geometryId ];
  9490. let maxRadiusSq = 0;
  9491. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9492. let iv = i;
  9493. if ( index ) {
  9494. iv = index.getX( iv );
  9495. }
  9496. _vector$5.fromBufferAttribute( position, iv );
  9497. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9498. }
  9499. sphere.radius = Math.sqrt( maxRadiusSq );
  9500. bound.sphereInitialized = true;
  9501. }
  9502. target.copy( sphere );
  9503. return target;
  9504. }
  9505. setMatrixAt( instanceId, matrix ) {
  9506. // @TODO: Map geometryId to index of the arrays because
  9507. // optimize() can make geometryId mismatch the index
  9508. const drawInfo = this._drawInfo;
  9509. const matricesTexture = this._matricesTexture;
  9510. const matricesArray = this._matricesTexture.image.data;
  9511. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9512. return this;
  9513. }
  9514. matrix.toArray( matricesArray, instanceId * 16 );
  9515. matricesTexture.needsUpdate = true;
  9516. return this;
  9517. }
  9518. getMatrixAt( instanceId, matrix ) {
  9519. const drawInfo = this._drawInfo;
  9520. const matricesArray = this._matricesTexture.image.data;
  9521. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9522. return null;
  9523. }
  9524. return matrix.fromArray( matricesArray, instanceId * 16 );
  9525. }
  9526. setColorAt( instanceId, color ) {
  9527. if ( this._colorsTexture === null ) {
  9528. this._initColorsTexture();
  9529. }
  9530. // @TODO: Map id to index of the arrays because
  9531. // optimize() can make id mismatch the index
  9532. const colorsTexture = this._colorsTexture;
  9533. const colorsArray = this._colorsTexture.image.data;
  9534. const drawInfo = this._drawInfo;
  9535. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9536. return this;
  9537. }
  9538. color.toArray( colorsArray, instanceId * 4 );
  9539. colorsTexture.needsUpdate = true;
  9540. return this;
  9541. }
  9542. getColorAt( instanceId, color ) {
  9543. const colorsArray = this._colorsTexture.image.data;
  9544. const drawInfo = this._drawInfo;
  9545. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9546. return null;
  9547. }
  9548. return color.fromArray( colorsArray, instanceId * 4 );
  9549. }
  9550. setVisibleAt( instanceId, value ) {
  9551. // if the geometry is out of range, not active, or visibility state
  9552. // does not change then return early
  9553. const drawInfo = this._drawInfo;
  9554. if (
  9555. instanceId >= drawInfo.length ||
  9556. drawInfo[ instanceId ].active === false ||
  9557. drawInfo[ instanceId ].visible === value
  9558. ) {
  9559. return this;
  9560. }
  9561. drawInfo[ instanceId ].visible = value;
  9562. this._visibilityChanged = true;
  9563. return this;
  9564. }
  9565. getVisibleAt( instanceId ) {
  9566. // return early if the geometry is out of range or not active
  9567. const drawInfo = this._drawInfo;
  9568. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9569. return false;
  9570. }
  9571. return drawInfo[ instanceId ].visible;
  9572. }
  9573. setGeometryIdAt( instanceId, geometryId ) {
  9574. // return early if the geometry is out of range or not active
  9575. const drawInfo = this._drawInfo;
  9576. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9577. return null;
  9578. }
  9579. // check if the provided geometryId is within the valid range
  9580. if ( geometryId < 0 || geometryId >= this._geometryCount ) {
  9581. return null;
  9582. }
  9583. drawInfo[ instanceId ].geometryIndex = geometryId;
  9584. return this;
  9585. }
  9586. getGeometryIdAt( instanceId ) {
  9587. const drawInfo = this._drawInfo;
  9588. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9589. return - 1;
  9590. }
  9591. return drawInfo[ instanceId ].geometryIndex;
  9592. }
  9593. raycast( raycaster, intersects ) {
  9594. const drawInfo = this._drawInfo;
  9595. const drawRanges = this._drawRanges;
  9596. const matrixWorld = this.matrixWorld;
  9597. const batchGeometry = this.geometry;
  9598. // iterate over each geometry
  9599. _mesh.material = this.material;
  9600. _mesh.geometry.index = batchGeometry.index;
  9601. _mesh.geometry.attributes = batchGeometry.attributes;
  9602. if ( _mesh.geometry.boundingBox === null ) {
  9603. _mesh.geometry.boundingBox = new Box3();
  9604. }
  9605. if ( _mesh.geometry.boundingSphere === null ) {
  9606. _mesh.geometry.boundingSphere = new Sphere();
  9607. }
  9608. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9609. if ( ! drawInfo[ i ].visible || ! drawInfo[ i ].active ) {
  9610. continue;
  9611. }
  9612. const geometryId = drawInfo[ i ].geometryIndex;
  9613. const drawRange = drawRanges[ geometryId ];
  9614. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  9615. // ge the intersects
  9616. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9617. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9618. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9619. _mesh.raycast( raycaster, _batchIntersects );
  9620. // add batch id to the intersects
  9621. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9622. const intersect = _batchIntersects[ j ];
  9623. intersect.object = this;
  9624. intersect.batchId = i;
  9625. intersects.push( intersect );
  9626. }
  9627. _batchIntersects.length = 0;
  9628. }
  9629. _mesh.material = null;
  9630. _mesh.geometry.index = null;
  9631. _mesh.geometry.attributes = {};
  9632. _mesh.geometry.setDrawRange( 0, Infinity );
  9633. }
  9634. copy( source ) {
  9635. super.copy( source );
  9636. this.geometry = source.geometry.clone();
  9637. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9638. this.sortObjects = source.sortObjects;
  9639. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9640. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9641. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  9642. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  9643. this._drawInfo = source._drawInfo.map( inf => ( { ...inf } ) );
  9644. this._bounds = source._bounds.map( bound => ( {
  9645. boxInitialized: bound.boxInitialized,
  9646. box: bound.box.clone(),
  9647. sphereInitialized: bound.sphereInitialized,
  9648. sphere: bound.sphere.clone()
  9649. } ) );
  9650. this._maxInstanceCount = source._maxInstanceCount;
  9651. this._maxVertexCount = source._maxVertexCount;
  9652. this._maxIndexCount = source._maxIndexCount;
  9653. this._geometryInitialized = source._geometryInitialized;
  9654. this._geometryCount = source._geometryCount;
  9655. this._multiDrawCounts = source._multiDrawCounts.slice();
  9656. this._multiDrawStarts = source._multiDrawStarts.slice();
  9657. this._matricesTexture = source._matricesTexture.clone();
  9658. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  9659. if ( this._colorsTexture !== null ) {
  9660. this._colorsTexture = source._colorsTexture.clone();
  9661. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  9662. }
  9663. return this;
  9664. }
  9665. dispose() {
  9666. // Assuming the geometry is not shared with other meshes
  9667. this.geometry.dispose();
  9668. this._matricesTexture.dispose();
  9669. this._matricesTexture = null;
  9670. this._indirectTexture.dispose();
  9671. this._indirectTexture = null;
  9672. if ( this._colorsTexture !== null ) {
  9673. this._colorsTexture.dispose();
  9674. this._colorsTexture = null;
  9675. }
  9676. return this;
  9677. }
  9678. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9679. // if visibility has not changed and frustum culling and object sorting is not required
  9680. // then skip iterating over all items
  9681. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9682. return;
  9683. }
  9684. // the indexed version of the multi draw function requires specifying the start
  9685. // offset in bytes.
  9686. const index = geometry.getIndex();
  9687. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9688. const drawInfo = this._drawInfo;
  9689. const multiDrawStarts = this._multiDrawStarts;
  9690. const multiDrawCounts = this._multiDrawCounts;
  9691. const drawRanges = this._drawRanges;
  9692. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9693. const indirectTexture = this._indirectTexture;
  9694. const indirectArray = indirectTexture.image.data;
  9695. // prepare the frustum in the local frame
  9696. if ( perObjectFrustumCulled ) {
  9697. _projScreenMatrix$3
  9698. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9699. .multiply( this.matrixWorld );
  9700. _frustum$1.setFromProjectionMatrix(
  9701. _projScreenMatrix$3,
  9702. renderer.coordinateSystem
  9703. );
  9704. }
  9705. let count = 0;
  9706. if ( this.sortObjects ) {
  9707. // get the camera position in the local frame
  9708. _invMatrixWorld.copy( this.matrixWorld ).invert();
  9709. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  9710. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  9711. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9712. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9713. const geometryId = drawInfo[ i ].geometryIndex;
  9714. // get the bounds in world space
  9715. this.getMatrixAt( i, _matrix$1 );
  9716. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9717. // determine whether the batched geometry is within the frustum
  9718. let culled = false;
  9719. if ( perObjectFrustumCulled ) {
  9720. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9721. }
  9722. if ( ! culled ) {
  9723. // get the distance from camera used for sorting
  9724. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9725. _renderList.push( drawRanges[ geometryId ], z, i );
  9726. }
  9727. }
  9728. }
  9729. // Sort the draw ranges and prep for rendering
  9730. const list = _renderList.list;
  9731. const customSort = this.customSort;
  9732. if ( customSort === null ) {
  9733. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9734. } else {
  9735. customSort.call( this, list, camera );
  9736. }
  9737. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9738. const item = list[ i ];
  9739. multiDrawStarts[ count ] = item.start * bytesPerElement;
  9740. multiDrawCounts[ count ] = item.count;
  9741. indirectArray[ count ] = item.index;
  9742. count ++;
  9743. }
  9744. _renderList.reset();
  9745. } else {
  9746. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9747. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9748. const geometryId = drawInfo[ i ].geometryIndex;
  9749. // determine whether the batched geometry is within the frustum
  9750. let culled = false;
  9751. if ( perObjectFrustumCulled ) {
  9752. // get the bounds in world space
  9753. this.getMatrixAt( i, _matrix$1 );
  9754. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9755. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9756. }
  9757. if ( ! culled ) {
  9758. const range = drawRanges[ geometryId ];
  9759. multiDrawStarts[ count ] = range.start * bytesPerElement;
  9760. multiDrawCounts[ count ] = range.count;
  9761. indirectArray[ count ] = i;
  9762. count ++;
  9763. }
  9764. }
  9765. }
  9766. }
  9767. indirectTexture.needsUpdate = true;
  9768. this._multiDrawCount = count;
  9769. this._visibilityChanged = false;
  9770. }
  9771. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9772. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9773. }
  9774. }
  9775. class LineBasicMaterial extends Material {
  9776. constructor( parameters ) {
  9777. super();
  9778. this.isLineBasicMaterial = true;
  9779. this.type = 'LineBasicMaterial';
  9780. this.color = new Color( 0xffffff );
  9781. this.map = null;
  9782. this.linewidth = 1;
  9783. this.linecap = 'round';
  9784. this.linejoin = 'round';
  9785. this.fog = true;
  9786. this.setValues( parameters );
  9787. }
  9788. copy( source ) {
  9789. super.copy( source );
  9790. this.color.copy( source.color );
  9791. this.map = source.map;
  9792. this.linewidth = source.linewidth;
  9793. this.linecap = source.linecap;
  9794. this.linejoin = source.linejoin;
  9795. this.fog = source.fog;
  9796. return this;
  9797. }
  9798. }
  9799. const _vStart = /*@__PURE__*/ new Vector3();
  9800. const _vEnd = /*@__PURE__*/ new Vector3();
  9801. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  9802. const _ray$1 = /*@__PURE__*/ new Ray();
  9803. const _sphere$1 = /*@__PURE__*/ new Sphere();
  9804. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  9805. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  9806. class Line extends Object3D {
  9807. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  9808. super();
  9809. this.isLine = true;
  9810. this.type = 'Line';
  9811. this.geometry = geometry;
  9812. this.material = material;
  9813. this.updateMorphTargets();
  9814. }
  9815. copy( source, recursive ) {
  9816. super.copy( source, recursive );
  9817. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9818. this.geometry = source.geometry;
  9819. return this;
  9820. }
  9821. computeLineDistances() {
  9822. const geometry = this.geometry;
  9823. // we assume non-indexed geometry
  9824. if ( geometry.index === null ) {
  9825. const positionAttribute = geometry.attributes.position;
  9826. const lineDistances = [ 0 ];
  9827. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  9828. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  9829. _vEnd.fromBufferAttribute( positionAttribute, i );
  9830. lineDistances[ i ] = lineDistances[ i - 1 ];
  9831. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  9832. }
  9833. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9834. } else {
  9835. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9836. }
  9837. return this;
  9838. }
  9839. raycast( raycaster, intersects ) {
  9840. const geometry = this.geometry;
  9841. const matrixWorld = this.matrixWorld;
  9842. const threshold = raycaster.params.Line.threshold;
  9843. const drawRange = geometry.drawRange;
  9844. // Checking boundingSphere distance to ray
  9845. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9846. _sphere$1.copy( geometry.boundingSphere );
  9847. _sphere$1.applyMatrix4( matrixWorld );
  9848. _sphere$1.radius += threshold;
  9849. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  9850. //
  9851. _inverseMatrix$1.copy( matrixWorld ).invert();
  9852. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  9853. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9854. const localThresholdSq = localThreshold * localThreshold;
  9855. const step = this.isLineSegments ? 2 : 1;
  9856. const index = geometry.index;
  9857. const attributes = geometry.attributes;
  9858. const positionAttribute = attributes.position;
  9859. if ( index !== null ) {
  9860. const start = Math.max( 0, drawRange.start );
  9861. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  9862. for ( let i = start, l = end - 1; i < l; i += step ) {
  9863. const a = index.getX( i );
  9864. const b = index.getX( i + 1 );
  9865. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9866. if ( intersect ) {
  9867. intersects.push( intersect );
  9868. }
  9869. }
  9870. if ( this.isLineLoop ) {
  9871. const a = index.getX( end - 1 );
  9872. const b = index.getX( start );
  9873. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  9874. if ( intersect ) {
  9875. intersects.push( intersect );
  9876. }
  9877. }
  9878. } else {
  9879. const start = Math.max( 0, drawRange.start );
  9880. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  9881. for ( let i = start, l = end - 1; i < l; i += step ) {
  9882. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  9883. if ( intersect ) {
  9884. intersects.push( intersect );
  9885. }
  9886. }
  9887. if ( this.isLineLoop ) {
  9888. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  9889. if ( intersect ) {
  9890. intersects.push( intersect );
  9891. }
  9892. }
  9893. }
  9894. }
  9895. updateMorphTargets() {
  9896. const geometry = this.geometry;
  9897. const morphAttributes = geometry.morphAttributes;
  9898. const keys = Object.keys( morphAttributes );
  9899. if ( keys.length > 0 ) {
  9900. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  9901. if ( morphAttribute !== undefined ) {
  9902. this.morphTargetInfluences = [];
  9903. this.morphTargetDictionary = {};
  9904. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  9905. const name = morphAttribute[ m ].name || String( m );
  9906. this.morphTargetInfluences.push( 0 );
  9907. this.morphTargetDictionary[ name ] = m;
  9908. }
  9909. }
  9910. }
  9911. }
  9912. }
  9913. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  9914. const positionAttribute = object.geometry.attributes.position;
  9915. _vStart.fromBufferAttribute( positionAttribute, a );
  9916. _vEnd.fromBufferAttribute( positionAttribute, b );
  9917. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  9918. if ( distSq > thresholdSq ) return;
  9919. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  9920. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  9921. if ( distance < raycaster.near || distance > raycaster.far ) return;
  9922. return {
  9923. distance: distance,
  9924. // What do we want? intersection point on the ray or on the segment??
  9925. // point: raycaster.ray.at( distance ),
  9926. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  9927. index: a,
  9928. face: null,
  9929. faceIndex: null,
  9930. barycoord: null,
  9931. object: object
  9932. };
  9933. }
  9934. const _start = /*@__PURE__*/ new Vector3();
  9935. const _end = /*@__PURE__*/ new Vector3();
  9936. class LineSegments extends Line {
  9937. constructor( geometry, material ) {
  9938. super( geometry, material );
  9939. this.isLineSegments = true;
  9940. this.type = 'LineSegments';
  9941. }
  9942. computeLineDistances() {
  9943. const geometry = this.geometry;
  9944. // we assume non-indexed geometry
  9945. if ( geometry.index === null ) {
  9946. const positionAttribute = geometry.attributes.position;
  9947. const lineDistances = [];
  9948. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  9949. _start.fromBufferAttribute( positionAttribute, i );
  9950. _end.fromBufferAttribute( positionAttribute, i + 1 );
  9951. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  9952. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  9953. }
  9954. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9955. } else {
  9956. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9957. }
  9958. return this;
  9959. }
  9960. }
  9961. class LineLoop extends Line {
  9962. constructor( geometry, material ) {
  9963. super( geometry, material );
  9964. this.isLineLoop = true;
  9965. this.type = 'LineLoop';
  9966. }
  9967. }
  9968. class PointsMaterial extends Material {
  9969. constructor( parameters ) {
  9970. super();
  9971. this.isPointsMaterial = true;
  9972. this.type = 'PointsMaterial';
  9973. this.color = new Color( 0xffffff );
  9974. this.map = null;
  9975. this.alphaMap = null;
  9976. this.size = 1;
  9977. this.sizeAttenuation = true;
  9978. this.fog = true;
  9979. this.setValues( parameters );
  9980. }
  9981. copy( source ) {
  9982. super.copy( source );
  9983. this.color.copy( source.color );
  9984. this.map = source.map;
  9985. this.alphaMap = source.alphaMap;
  9986. this.size = source.size;
  9987. this.sizeAttenuation = source.sizeAttenuation;
  9988. this.fog = source.fog;
  9989. return this;
  9990. }
  9991. }
  9992. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  9993. const _ray = /*@__PURE__*/ new Ray();
  9994. const _sphere = /*@__PURE__*/ new Sphere();
  9995. const _position$2 = /*@__PURE__*/ new Vector3();
  9996. class Points extends Object3D {
  9997. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  9998. super();
  9999. this.isPoints = true;
  10000. this.type = 'Points';
  10001. this.geometry = geometry;
  10002. this.material = material;
  10003. this.updateMorphTargets();
  10004. }
  10005. copy( source, recursive ) {
  10006. super.copy( source, recursive );
  10007. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10008. this.geometry = source.geometry;
  10009. return this;
  10010. }
  10011. raycast( raycaster, intersects ) {
  10012. const geometry = this.geometry;
  10013. const matrixWorld = this.matrixWorld;
  10014. const threshold = raycaster.params.Points.threshold;
  10015. const drawRange = geometry.drawRange;
  10016. // Checking boundingSphere distance to ray
  10017. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10018. _sphere.copy( geometry.boundingSphere );
  10019. _sphere.applyMatrix4( matrixWorld );
  10020. _sphere.radius += threshold;
  10021. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  10022. //
  10023. _inverseMatrix.copy( matrixWorld ).invert();
  10024. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  10025. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10026. const localThresholdSq = localThreshold * localThreshold;
  10027. const index = geometry.index;
  10028. const attributes = geometry.attributes;
  10029. const positionAttribute = attributes.position;
  10030. if ( index !== null ) {
  10031. const start = Math.max( 0, drawRange.start );
  10032. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10033. for ( let i = start, il = end; i < il; i ++ ) {
  10034. const a = index.getX( i );
  10035. _position$2.fromBufferAttribute( positionAttribute, a );
  10036. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10037. }
  10038. } else {
  10039. const start = Math.max( 0, drawRange.start );
  10040. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10041. for ( let i = start, l = end; i < l; i ++ ) {
  10042. _position$2.fromBufferAttribute( positionAttribute, i );
  10043. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10044. }
  10045. }
  10046. }
  10047. updateMorphTargets() {
  10048. const geometry = this.geometry;
  10049. const morphAttributes = geometry.morphAttributes;
  10050. const keys = Object.keys( morphAttributes );
  10051. if ( keys.length > 0 ) {
  10052. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10053. if ( morphAttribute !== undefined ) {
  10054. this.morphTargetInfluences = [];
  10055. this.morphTargetDictionary = {};
  10056. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10057. const name = morphAttribute[ m ].name || String( m );
  10058. this.morphTargetInfluences.push( 0 );
  10059. this.morphTargetDictionary[ name ] = m;
  10060. }
  10061. }
  10062. }
  10063. }
  10064. }
  10065. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10066. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10067. if ( rayPointDistanceSq < localThresholdSq ) {
  10068. const intersectPoint = new Vector3();
  10069. _ray.closestPointToPoint( point, intersectPoint );
  10070. intersectPoint.applyMatrix4( matrixWorld );
  10071. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10072. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10073. intersects.push( {
  10074. distance: distance,
  10075. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10076. point: intersectPoint,
  10077. index: index,
  10078. face: null,
  10079. faceIndex: null,
  10080. barycoord: null,
  10081. object: object
  10082. } );
  10083. }
  10084. }
  10085. class Group extends Object3D {
  10086. constructor() {
  10087. super();
  10088. this.isGroup = true;
  10089. this.type = 'Group';
  10090. }
  10091. }
  10092. class VideoTexture extends Texture {
  10093. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10094. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10095. this.isVideoTexture = true;
  10096. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10097. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10098. this.generateMipmaps = false;
  10099. const scope = this;
  10100. function updateVideo() {
  10101. scope.needsUpdate = true;
  10102. video.requestVideoFrameCallback( updateVideo );
  10103. }
  10104. if ( 'requestVideoFrameCallback' in video ) {
  10105. video.requestVideoFrameCallback( updateVideo );
  10106. }
  10107. }
  10108. clone() {
  10109. return new this.constructor( this.image ).copy( this );
  10110. }
  10111. update() {
  10112. const video = this.image;
  10113. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10114. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10115. this.needsUpdate = true;
  10116. }
  10117. }
  10118. }
  10119. class FramebufferTexture extends Texture {
  10120. constructor( width, height ) {
  10121. super( { width, height } );
  10122. this.isFramebufferTexture = true;
  10123. this.magFilter = NearestFilter;
  10124. this.minFilter = NearestFilter;
  10125. this.generateMipmaps = false;
  10126. this.needsUpdate = true;
  10127. }
  10128. }
  10129. class CompressedTexture extends Texture {
  10130. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10131. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10132. this.isCompressedTexture = true;
  10133. this.image = { width: width, height: height };
  10134. this.mipmaps = mipmaps;
  10135. // no flipping for cube textures
  10136. // (also flipping doesn't work for compressed textures )
  10137. this.flipY = false;
  10138. // can't generate mipmaps for compressed textures
  10139. // mips must be embedded in DDS files
  10140. this.generateMipmaps = false;
  10141. }
  10142. }
  10143. class CompressedArrayTexture extends CompressedTexture {
  10144. constructor( mipmaps, width, height, depth, format, type ) {
  10145. super( mipmaps, width, height, format, type );
  10146. this.isCompressedArrayTexture = true;
  10147. this.image.depth = depth;
  10148. this.wrapR = ClampToEdgeWrapping;
  10149. this.layerUpdates = new Set();
  10150. }
  10151. addLayerUpdate( layerIndex ) {
  10152. this.layerUpdates.add( layerIndex );
  10153. }
  10154. clearLayerUpdates() {
  10155. this.layerUpdates.clear();
  10156. }
  10157. }
  10158. class CompressedCubeTexture extends CompressedTexture {
  10159. constructor( images, format, type ) {
  10160. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10161. this.isCompressedCubeTexture = true;
  10162. this.isCubeTexture = true;
  10163. this.image = images;
  10164. }
  10165. }
  10166. class CanvasTexture extends Texture {
  10167. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10168. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10169. this.isCanvasTexture = true;
  10170. this.needsUpdate = true;
  10171. }
  10172. }
  10173. class DepthTexture extends Texture {
  10174. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10175. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10176. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10177. }
  10178. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10179. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10180. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10181. this.isDepthTexture = true;
  10182. this.image = { width: width, height: height };
  10183. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10184. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10185. this.flipY = false;
  10186. this.generateMipmaps = false;
  10187. this.compareFunction = null;
  10188. }
  10189. copy( source ) {
  10190. super.copy( source );
  10191. this.compareFunction = source.compareFunction;
  10192. return this;
  10193. }
  10194. toJSON( meta ) {
  10195. const data = super.toJSON( meta );
  10196. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10197. return data;
  10198. }
  10199. }
  10200. /**
  10201. * Extensible curve object.
  10202. *
  10203. * Some common of curve methods:
  10204. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10205. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10206. * .getPoints(), .getSpacedPoints()
  10207. * .getLength()
  10208. * .updateArcLengths()
  10209. *
  10210. * This following curves inherit from THREE.Curve:
  10211. *
  10212. * -- 2D curves --
  10213. * THREE.ArcCurve
  10214. * THREE.CubicBezierCurve
  10215. * THREE.EllipseCurve
  10216. * THREE.LineCurve
  10217. * THREE.QuadraticBezierCurve
  10218. * THREE.SplineCurve
  10219. *
  10220. * -- 3D curves --
  10221. * THREE.CatmullRomCurve3
  10222. * THREE.CubicBezierCurve3
  10223. * THREE.LineCurve3
  10224. * THREE.QuadraticBezierCurve3
  10225. *
  10226. * A series of curves can be represented as a THREE.CurvePath.
  10227. *
  10228. **/
  10229. class Curve {
  10230. constructor() {
  10231. this.type = 'Curve';
  10232. this.arcLengthDivisions = 200;
  10233. }
  10234. // Virtual base class method to overwrite and implement in subclasses
  10235. // - t [0 .. 1]
  10236. getPoint( /* t, optionalTarget */ ) {
  10237. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10238. return null;
  10239. }
  10240. // Get point at relative position in curve according to arc length
  10241. // - u [0 .. 1]
  10242. getPointAt( u, optionalTarget ) {
  10243. const t = this.getUtoTmapping( u );
  10244. return this.getPoint( t, optionalTarget );
  10245. }
  10246. // Get sequence of points using getPoint( t )
  10247. getPoints( divisions = 5 ) {
  10248. const points = [];
  10249. for ( let d = 0; d <= divisions; d ++ ) {
  10250. points.push( this.getPoint( d / divisions ) );
  10251. }
  10252. return points;
  10253. }
  10254. // Get sequence of points using getPointAt( u )
  10255. getSpacedPoints( divisions = 5 ) {
  10256. const points = [];
  10257. for ( let d = 0; d <= divisions; d ++ ) {
  10258. points.push( this.getPointAt( d / divisions ) );
  10259. }
  10260. return points;
  10261. }
  10262. // Get total curve arc length
  10263. getLength() {
  10264. const lengths = this.getLengths();
  10265. return lengths[ lengths.length - 1 ];
  10266. }
  10267. // Get list of cumulative segment lengths
  10268. getLengths( divisions = this.arcLengthDivisions ) {
  10269. if ( this.cacheArcLengths &&
  10270. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10271. ! this.needsUpdate ) {
  10272. return this.cacheArcLengths;
  10273. }
  10274. this.needsUpdate = false;
  10275. const cache = [];
  10276. let current, last = this.getPoint( 0 );
  10277. let sum = 0;
  10278. cache.push( 0 );
  10279. for ( let p = 1; p <= divisions; p ++ ) {
  10280. current = this.getPoint( p / divisions );
  10281. sum += current.distanceTo( last );
  10282. cache.push( sum );
  10283. last = current;
  10284. }
  10285. this.cacheArcLengths = cache;
  10286. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10287. }
  10288. updateArcLengths() {
  10289. this.needsUpdate = true;
  10290. this.getLengths();
  10291. }
  10292. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10293. getUtoTmapping( u, distance ) {
  10294. const arcLengths = this.getLengths();
  10295. let i = 0;
  10296. const il = arcLengths.length;
  10297. let targetArcLength; // The targeted u distance value to get
  10298. if ( distance ) {
  10299. targetArcLength = distance;
  10300. } else {
  10301. targetArcLength = u * arcLengths[ il - 1 ];
  10302. }
  10303. // binary search for the index with largest value smaller than target u distance
  10304. let low = 0, high = il - 1, comparison;
  10305. while ( low <= high ) {
  10306. i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
  10307. comparison = arcLengths[ i ] - targetArcLength;
  10308. if ( comparison < 0 ) {
  10309. low = i + 1;
  10310. } else if ( comparison > 0 ) {
  10311. high = i - 1;
  10312. } else {
  10313. high = i;
  10314. break;
  10315. // DONE
  10316. }
  10317. }
  10318. i = high;
  10319. if ( arcLengths[ i ] === targetArcLength ) {
  10320. return i / ( il - 1 );
  10321. }
  10322. // we could get finer grain at lengths, or use simple interpolation between two points
  10323. const lengthBefore = arcLengths[ i ];
  10324. const lengthAfter = arcLengths[ i + 1 ];
  10325. const segmentLength = lengthAfter - lengthBefore;
  10326. // determine where we are between the 'before' and 'after' points
  10327. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10328. // add that fractional amount to t
  10329. const t = ( i + segmentFraction ) / ( il - 1 );
  10330. return t;
  10331. }
  10332. // Returns a unit vector tangent at t
  10333. // In case any sub curve does not implement its tangent derivation,
  10334. // 2 points a small delta apart will be used to find its gradient
  10335. // which seems to give a reasonable approximation
  10336. getTangent( t, optionalTarget ) {
  10337. const delta = 0.0001;
  10338. let t1 = t - delta;
  10339. let t2 = t + delta;
  10340. // Capping in case of danger
  10341. if ( t1 < 0 ) t1 = 0;
  10342. if ( t2 > 1 ) t2 = 1;
  10343. const pt1 = this.getPoint( t1 );
  10344. const pt2 = this.getPoint( t2 );
  10345. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10346. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10347. return tangent;
  10348. }
  10349. getTangentAt( u, optionalTarget ) {
  10350. const t = this.getUtoTmapping( u );
  10351. return this.getTangent( t, optionalTarget );
  10352. }
  10353. computeFrenetFrames( segments, closed ) {
  10354. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10355. const normal = new Vector3();
  10356. const tangents = [];
  10357. const normals = [];
  10358. const binormals = [];
  10359. const vec = new Vector3();
  10360. const mat = new Matrix4();
  10361. // compute the tangent vectors for each segment on the curve
  10362. for ( let i = 0; i <= segments; i ++ ) {
  10363. const u = i / segments;
  10364. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10365. }
  10366. // select an initial normal vector perpendicular to the first tangent vector,
  10367. // and in the direction of the minimum tangent xyz component
  10368. normals[ 0 ] = new Vector3();
  10369. binormals[ 0 ] = new Vector3();
  10370. let min = Number.MAX_VALUE;
  10371. const tx = Math.abs( tangents[ 0 ].x );
  10372. const ty = Math.abs( tangents[ 0 ].y );
  10373. const tz = Math.abs( tangents[ 0 ].z );
  10374. if ( tx <= min ) {
  10375. min = tx;
  10376. normal.set( 1, 0, 0 );
  10377. }
  10378. if ( ty <= min ) {
  10379. min = ty;
  10380. normal.set( 0, 1, 0 );
  10381. }
  10382. if ( tz <= min ) {
  10383. normal.set( 0, 0, 1 );
  10384. }
  10385. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10386. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10387. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10388. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10389. for ( let i = 1; i <= segments; i ++ ) {
  10390. normals[ i ] = normals[ i - 1 ].clone();
  10391. binormals[ i ] = binormals[ i - 1 ].clone();
  10392. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10393. if ( vec.length() > Number.EPSILON ) {
  10394. vec.normalize();
  10395. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10396. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10397. }
  10398. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10399. }
  10400. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10401. if ( closed === true ) {
  10402. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10403. theta /= segments;
  10404. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10405. theta = - theta;
  10406. }
  10407. for ( let i = 1; i <= segments; i ++ ) {
  10408. // twist a little...
  10409. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10410. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10411. }
  10412. }
  10413. return {
  10414. tangents: tangents,
  10415. normals: normals,
  10416. binormals: binormals
  10417. };
  10418. }
  10419. clone() {
  10420. return new this.constructor().copy( this );
  10421. }
  10422. copy( source ) {
  10423. this.arcLengthDivisions = source.arcLengthDivisions;
  10424. return this;
  10425. }
  10426. toJSON() {
  10427. const data = {
  10428. metadata: {
  10429. version: 4.6,
  10430. type: 'Curve',
  10431. generator: 'Curve.toJSON'
  10432. }
  10433. };
  10434. data.arcLengthDivisions = this.arcLengthDivisions;
  10435. data.type = this.type;
  10436. return data;
  10437. }
  10438. fromJSON( json ) {
  10439. this.arcLengthDivisions = json.arcLengthDivisions;
  10440. return this;
  10441. }
  10442. }
  10443. class EllipseCurve extends Curve {
  10444. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10445. super();
  10446. this.isEllipseCurve = true;
  10447. this.type = 'EllipseCurve';
  10448. this.aX = aX;
  10449. this.aY = aY;
  10450. this.xRadius = xRadius;
  10451. this.yRadius = yRadius;
  10452. this.aStartAngle = aStartAngle;
  10453. this.aEndAngle = aEndAngle;
  10454. this.aClockwise = aClockwise;
  10455. this.aRotation = aRotation;
  10456. }
  10457. getPoint( t, optionalTarget = new Vector2() ) {
  10458. const point = optionalTarget;
  10459. const twoPi = Math.PI * 2;
  10460. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10461. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10462. // ensures that deltaAngle is 0 .. 2 PI
  10463. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10464. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10465. if ( deltaAngle < Number.EPSILON ) {
  10466. if ( samePoints ) {
  10467. deltaAngle = 0;
  10468. } else {
  10469. deltaAngle = twoPi;
  10470. }
  10471. }
  10472. if ( this.aClockwise === true && ! samePoints ) {
  10473. if ( deltaAngle === twoPi ) {
  10474. deltaAngle = - twoPi;
  10475. } else {
  10476. deltaAngle = deltaAngle - twoPi;
  10477. }
  10478. }
  10479. const angle = this.aStartAngle + t * deltaAngle;
  10480. let x = this.aX + this.xRadius * Math.cos( angle );
  10481. let y = this.aY + this.yRadius * Math.sin( angle );
  10482. if ( this.aRotation !== 0 ) {
  10483. const cos = Math.cos( this.aRotation );
  10484. const sin = Math.sin( this.aRotation );
  10485. const tx = x - this.aX;
  10486. const ty = y - this.aY;
  10487. // Rotate the point about the center of the ellipse.
  10488. x = tx * cos - ty * sin + this.aX;
  10489. y = tx * sin + ty * cos + this.aY;
  10490. }
  10491. return point.set( x, y );
  10492. }
  10493. copy( source ) {
  10494. super.copy( source );
  10495. this.aX = source.aX;
  10496. this.aY = source.aY;
  10497. this.xRadius = source.xRadius;
  10498. this.yRadius = source.yRadius;
  10499. this.aStartAngle = source.aStartAngle;
  10500. this.aEndAngle = source.aEndAngle;
  10501. this.aClockwise = source.aClockwise;
  10502. this.aRotation = source.aRotation;
  10503. return this;
  10504. }
  10505. toJSON() {
  10506. const data = super.toJSON();
  10507. data.aX = this.aX;
  10508. data.aY = this.aY;
  10509. data.xRadius = this.xRadius;
  10510. data.yRadius = this.yRadius;
  10511. data.aStartAngle = this.aStartAngle;
  10512. data.aEndAngle = this.aEndAngle;
  10513. data.aClockwise = this.aClockwise;
  10514. data.aRotation = this.aRotation;
  10515. return data;
  10516. }
  10517. fromJSON( json ) {
  10518. super.fromJSON( json );
  10519. this.aX = json.aX;
  10520. this.aY = json.aY;
  10521. this.xRadius = json.xRadius;
  10522. this.yRadius = json.yRadius;
  10523. this.aStartAngle = json.aStartAngle;
  10524. this.aEndAngle = json.aEndAngle;
  10525. this.aClockwise = json.aClockwise;
  10526. this.aRotation = json.aRotation;
  10527. return this;
  10528. }
  10529. }
  10530. class ArcCurve extends EllipseCurve {
  10531. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10532. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10533. this.isArcCurve = true;
  10534. this.type = 'ArcCurve';
  10535. }
  10536. }
  10537. /**
  10538. * Centripetal CatmullRom Curve - which is useful for avoiding
  10539. * cusps and self-intersections in non-uniform catmull rom curves.
  10540. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10541. *
  10542. * curve.type accepts centripetal(default), chordal and catmullrom
  10543. * curve.tension is used for catmullrom which defaults to 0.5
  10544. */
  10545. /*
  10546. Based on an optimized c++ solution in
  10547. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10548. - http://ideone.com/NoEbVM
  10549. This CubicPoly class could be used for reusing some variables and calculations,
  10550. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10551. which can be placed in CurveUtils.
  10552. */
  10553. function CubicPoly() {
  10554. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10555. /*
  10556. * Compute coefficients for a cubic polynomial
  10557. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10558. * such that
  10559. * p(0) = x0, p(1) = x1
  10560. * and
  10561. * p'(0) = t0, p'(1) = t1.
  10562. */
  10563. function init( x0, x1, t0, t1 ) {
  10564. c0 = x0;
  10565. c1 = t0;
  10566. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10567. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10568. }
  10569. return {
  10570. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10571. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10572. },
  10573. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10574. // compute tangents when parameterized in [t1,t2]
  10575. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10576. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10577. // rescale tangents for parametrization in [0,1]
  10578. t1 *= dt1;
  10579. t2 *= dt1;
  10580. init( x1, x2, t1, t2 );
  10581. },
  10582. calc: function ( t ) {
  10583. const t2 = t * t;
  10584. const t3 = t2 * t;
  10585. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10586. }
  10587. };
  10588. }
  10589. //
  10590. const tmp = /*@__PURE__*/ new Vector3();
  10591. const px = /*@__PURE__*/ new CubicPoly();
  10592. const py = /*@__PURE__*/ new CubicPoly();
  10593. const pz = /*@__PURE__*/ new CubicPoly();
  10594. class CatmullRomCurve3 extends Curve {
  10595. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10596. super();
  10597. this.isCatmullRomCurve3 = true;
  10598. this.type = 'CatmullRomCurve3';
  10599. this.points = points;
  10600. this.closed = closed;
  10601. this.curveType = curveType;
  10602. this.tension = tension;
  10603. }
  10604. getPoint( t, optionalTarget = new Vector3() ) {
  10605. const point = optionalTarget;
  10606. const points = this.points;
  10607. const l = points.length;
  10608. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10609. let intPoint = Math.floor( p );
  10610. let weight = p - intPoint;
  10611. if ( this.closed ) {
  10612. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10613. } else if ( weight === 0 && intPoint === l - 1 ) {
  10614. intPoint = l - 2;
  10615. weight = 1;
  10616. }
  10617. let p0, p3; // 4 points (p1 & p2 defined below)
  10618. if ( this.closed || intPoint > 0 ) {
  10619. p0 = points[ ( intPoint - 1 ) % l ];
  10620. } else {
  10621. // extrapolate first point
  10622. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10623. p0 = tmp;
  10624. }
  10625. const p1 = points[ intPoint % l ];
  10626. const p2 = points[ ( intPoint + 1 ) % l ];
  10627. if ( this.closed || intPoint + 2 < l ) {
  10628. p3 = points[ ( intPoint + 2 ) % l ];
  10629. } else {
  10630. // extrapolate last point
  10631. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10632. p3 = tmp;
  10633. }
  10634. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10635. // init Centripetal / Chordal Catmull-Rom
  10636. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10637. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10638. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10639. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10640. // safety check for repeated points
  10641. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10642. if ( dt0 < 1e-4 ) dt0 = dt1;
  10643. if ( dt2 < 1e-4 ) dt2 = dt1;
  10644. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10645. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10646. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10647. } else if ( this.curveType === 'catmullrom' ) {
  10648. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10649. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10650. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10651. }
  10652. point.set(
  10653. px.calc( weight ),
  10654. py.calc( weight ),
  10655. pz.calc( weight )
  10656. );
  10657. return point;
  10658. }
  10659. copy( source ) {
  10660. super.copy( source );
  10661. this.points = [];
  10662. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10663. const point = source.points[ i ];
  10664. this.points.push( point.clone() );
  10665. }
  10666. this.closed = source.closed;
  10667. this.curveType = source.curveType;
  10668. this.tension = source.tension;
  10669. return this;
  10670. }
  10671. toJSON() {
  10672. const data = super.toJSON();
  10673. data.points = [];
  10674. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10675. const point = this.points[ i ];
  10676. data.points.push( point.toArray() );
  10677. }
  10678. data.closed = this.closed;
  10679. data.curveType = this.curveType;
  10680. data.tension = this.tension;
  10681. return data;
  10682. }
  10683. fromJSON( json ) {
  10684. super.fromJSON( json );
  10685. this.points = [];
  10686. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10687. const point = json.points[ i ];
  10688. this.points.push( new Vector3().fromArray( point ) );
  10689. }
  10690. this.closed = json.closed;
  10691. this.curveType = json.curveType;
  10692. this.tension = json.tension;
  10693. return this;
  10694. }
  10695. }
  10696. /**
  10697. * Bezier Curves formulas obtained from
  10698. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10699. */
  10700. function CatmullRom( t, p0, p1, p2, p3 ) {
  10701. const v0 = ( p2 - p0 ) * 0.5;
  10702. const v1 = ( p3 - p1 ) * 0.5;
  10703. const t2 = t * t;
  10704. const t3 = t * t2;
  10705. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10706. }
  10707. //
  10708. function QuadraticBezierP0( t, p ) {
  10709. const k = 1 - t;
  10710. return k * k * p;
  10711. }
  10712. function QuadraticBezierP1( t, p ) {
  10713. return 2 * ( 1 - t ) * t * p;
  10714. }
  10715. function QuadraticBezierP2( t, p ) {
  10716. return t * t * p;
  10717. }
  10718. function QuadraticBezier( t, p0, p1, p2 ) {
  10719. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10720. QuadraticBezierP2( t, p2 );
  10721. }
  10722. //
  10723. function CubicBezierP0( t, p ) {
  10724. const k = 1 - t;
  10725. return k * k * k * p;
  10726. }
  10727. function CubicBezierP1( t, p ) {
  10728. const k = 1 - t;
  10729. return 3 * k * k * t * p;
  10730. }
  10731. function CubicBezierP2( t, p ) {
  10732. return 3 * ( 1 - t ) * t * t * p;
  10733. }
  10734. function CubicBezierP3( t, p ) {
  10735. return t * t * t * p;
  10736. }
  10737. function CubicBezier( t, p0, p1, p2, p3 ) {
  10738. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10739. CubicBezierP3( t, p3 );
  10740. }
  10741. class CubicBezierCurve extends Curve {
  10742. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10743. super();
  10744. this.isCubicBezierCurve = true;
  10745. this.type = 'CubicBezierCurve';
  10746. this.v0 = v0;
  10747. this.v1 = v1;
  10748. this.v2 = v2;
  10749. this.v3 = v3;
  10750. }
  10751. getPoint( t, optionalTarget = new Vector2() ) {
  10752. const point = optionalTarget;
  10753. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10754. point.set(
  10755. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10756. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10757. );
  10758. return point;
  10759. }
  10760. copy( source ) {
  10761. super.copy( source );
  10762. this.v0.copy( source.v0 );
  10763. this.v1.copy( source.v1 );
  10764. this.v2.copy( source.v2 );
  10765. this.v3.copy( source.v3 );
  10766. return this;
  10767. }
  10768. toJSON() {
  10769. const data = super.toJSON();
  10770. data.v0 = this.v0.toArray();
  10771. data.v1 = this.v1.toArray();
  10772. data.v2 = this.v2.toArray();
  10773. data.v3 = this.v3.toArray();
  10774. return data;
  10775. }
  10776. fromJSON( json ) {
  10777. super.fromJSON( json );
  10778. this.v0.fromArray( json.v0 );
  10779. this.v1.fromArray( json.v1 );
  10780. this.v2.fromArray( json.v2 );
  10781. this.v3.fromArray( json.v3 );
  10782. return this;
  10783. }
  10784. }
  10785. class CubicBezierCurve3 extends Curve {
  10786. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10787. super();
  10788. this.isCubicBezierCurve3 = true;
  10789. this.type = 'CubicBezierCurve3';
  10790. this.v0 = v0;
  10791. this.v1 = v1;
  10792. this.v2 = v2;
  10793. this.v3 = v3;
  10794. }
  10795. getPoint( t, optionalTarget = new Vector3() ) {
  10796. const point = optionalTarget;
  10797. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10798. point.set(
  10799. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10800. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  10801. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  10802. );
  10803. return point;
  10804. }
  10805. copy( source ) {
  10806. super.copy( source );
  10807. this.v0.copy( source.v0 );
  10808. this.v1.copy( source.v1 );
  10809. this.v2.copy( source.v2 );
  10810. this.v3.copy( source.v3 );
  10811. return this;
  10812. }
  10813. toJSON() {
  10814. const data = super.toJSON();
  10815. data.v0 = this.v0.toArray();
  10816. data.v1 = this.v1.toArray();
  10817. data.v2 = this.v2.toArray();
  10818. data.v3 = this.v3.toArray();
  10819. return data;
  10820. }
  10821. fromJSON( json ) {
  10822. super.fromJSON( json );
  10823. this.v0.fromArray( json.v0 );
  10824. this.v1.fromArray( json.v1 );
  10825. this.v2.fromArray( json.v2 );
  10826. this.v3.fromArray( json.v3 );
  10827. return this;
  10828. }
  10829. }
  10830. class LineCurve extends Curve {
  10831. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  10832. super();
  10833. this.isLineCurve = true;
  10834. this.type = 'LineCurve';
  10835. this.v1 = v1;
  10836. this.v2 = v2;
  10837. }
  10838. getPoint( t, optionalTarget = new Vector2() ) {
  10839. const point = optionalTarget;
  10840. if ( t === 1 ) {
  10841. point.copy( this.v2 );
  10842. } else {
  10843. point.copy( this.v2 ).sub( this.v1 );
  10844. point.multiplyScalar( t ).add( this.v1 );
  10845. }
  10846. return point;
  10847. }
  10848. // Line curve is linear, so we can overwrite default getPointAt
  10849. getPointAt( u, optionalTarget ) {
  10850. return this.getPoint( u, optionalTarget );
  10851. }
  10852. getTangent( t, optionalTarget = new Vector2() ) {
  10853. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10854. }
  10855. getTangentAt( u, optionalTarget ) {
  10856. return this.getTangent( u, optionalTarget );
  10857. }
  10858. copy( source ) {
  10859. super.copy( source );
  10860. this.v1.copy( source.v1 );
  10861. this.v2.copy( source.v2 );
  10862. return this;
  10863. }
  10864. toJSON() {
  10865. const data = super.toJSON();
  10866. data.v1 = this.v1.toArray();
  10867. data.v2 = this.v2.toArray();
  10868. return data;
  10869. }
  10870. fromJSON( json ) {
  10871. super.fromJSON( json );
  10872. this.v1.fromArray( json.v1 );
  10873. this.v2.fromArray( json.v2 );
  10874. return this;
  10875. }
  10876. }
  10877. class LineCurve3 extends Curve {
  10878. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  10879. super();
  10880. this.isLineCurve3 = true;
  10881. this.type = 'LineCurve3';
  10882. this.v1 = v1;
  10883. this.v2 = v2;
  10884. }
  10885. getPoint( t, optionalTarget = new Vector3() ) {
  10886. const point = optionalTarget;
  10887. if ( t === 1 ) {
  10888. point.copy( this.v2 );
  10889. } else {
  10890. point.copy( this.v2 ).sub( this.v1 );
  10891. point.multiplyScalar( t ).add( this.v1 );
  10892. }
  10893. return point;
  10894. }
  10895. // Line curve is linear, so we can overwrite default getPointAt
  10896. getPointAt( u, optionalTarget ) {
  10897. return this.getPoint( u, optionalTarget );
  10898. }
  10899. getTangent( t, optionalTarget = new Vector3() ) {
  10900. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  10901. }
  10902. getTangentAt( u, optionalTarget ) {
  10903. return this.getTangent( u, optionalTarget );
  10904. }
  10905. copy( source ) {
  10906. super.copy( source );
  10907. this.v1.copy( source.v1 );
  10908. this.v2.copy( source.v2 );
  10909. return this;
  10910. }
  10911. toJSON() {
  10912. const data = super.toJSON();
  10913. data.v1 = this.v1.toArray();
  10914. data.v2 = this.v2.toArray();
  10915. return data;
  10916. }
  10917. fromJSON( json ) {
  10918. super.fromJSON( json );
  10919. this.v1.fromArray( json.v1 );
  10920. this.v2.fromArray( json.v2 );
  10921. return this;
  10922. }
  10923. }
  10924. class QuadraticBezierCurve extends Curve {
  10925. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  10926. super();
  10927. this.isQuadraticBezierCurve = true;
  10928. this.type = 'QuadraticBezierCurve';
  10929. this.v0 = v0;
  10930. this.v1 = v1;
  10931. this.v2 = v2;
  10932. }
  10933. getPoint( t, optionalTarget = new Vector2() ) {
  10934. const point = optionalTarget;
  10935. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10936. point.set(
  10937. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10938. QuadraticBezier( t, v0.y, v1.y, v2.y )
  10939. );
  10940. return point;
  10941. }
  10942. copy( source ) {
  10943. super.copy( source );
  10944. this.v0.copy( source.v0 );
  10945. this.v1.copy( source.v1 );
  10946. this.v2.copy( source.v2 );
  10947. return this;
  10948. }
  10949. toJSON() {
  10950. const data = super.toJSON();
  10951. data.v0 = this.v0.toArray();
  10952. data.v1 = this.v1.toArray();
  10953. data.v2 = this.v2.toArray();
  10954. return data;
  10955. }
  10956. fromJSON( json ) {
  10957. super.fromJSON( json );
  10958. this.v0.fromArray( json.v0 );
  10959. this.v1.fromArray( json.v1 );
  10960. this.v2.fromArray( json.v2 );
  10961. return this;
  10962. }
  10963. }
  10964. class QuadraticBezierCurve3 extends Curve {
  10965. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  10966. super();
  10967. this.isQuadraticBezierCurve3 = true;
  10968. this.type = 'QuadraticBezierCurve3';
  10969. this.v0 = v0;
  10970. this.v1 = v1;
  10971. this.v2 = v2;
  10972. }
  10973. getPoint( t, optionalTarget = new Vector3() ) {
  10974. const point = optionalTarget;
  10975. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  10976. point.set(
  10977. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  10978. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  10979. QuadraticBezier( t, v0.z, v1.z, v2.z )
  10980. );
  10981. return point;
  10982. }
  10983. copy( source ) {
  10984. super.copy( source );
  10985. this.v0.copy( source.v0 );
  10986. this.v1.copy( source.v1 );
  10987. this.v2.copy( source.v2 );
  10988. return this;
  10989. }
  10990. toJSON() {
  10991. const data = super.toJSON();
  10992. data.v0 = this.v0.toArray();
  10993. data.v1 = this.v1.toArray();
  10994. data.v2 = this.v2.toArray();
  10995. return data;
  10996. }
  10997. fromJSON( json ) {
  10998. super.fromJSON( json );
  10999. this.v0.fromArray( json.v0 );
  11000. this.v1.fromArray( json.v1 );
  11001. this.v2.fromArray( json.v2 );
  11002. return this;
  11003. }
  11004. }
  11005. class SplineCurve extends Curve {
  11006. constructor( points = [] ) {
  11007. super();
  11008. this.isSplineCurve = true;
  11009. this.type = 'SplineCurve';
  11010. this.points = points;
  11011. }
  11012. getPoint( t, optionalTarget = new Vector2() ) {
  11013. const point = optionalTarget;
  11014. const points = this.points;
  11015. const p = ( points.length - 1 ) * t;
  11016. const intPoint = Math.floor( p );
  11017. const weight = p - intPoint;
  11018. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  11019. const p1 = points[ intPoint ];
  11020. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  11021. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  11022. point.set(
  11023. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  11024. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  11025. );
  11026. return point;
  11027. }
  11028. copy( source ) {
  11029. super.copy( source );
  11030. this.points = [];
  11031. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  11032. const point = source.points[ i ];
  11033. this.points.push( point.clone() );
  11034. }
  11035. return this;
  11036. }
  11037. toJSON() {
  11038. const data = super.toJSON();
  11039. data.points = [];
  11040. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  11041. const point = this.points[ i ];
  11042. data.points.push( point.toArray() );
  11043. }
  11044. return data;
  11045. }
  11046. fromJSON( json ) {
  11047. super.fromJSON( json );
  11048. this.points = [];
  11049. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11050. const point = json.points[ i ];
  11051. this.points.push( new Vector2().fromArray( point ) );
  11052. }
  11053. return this;
  11054. }
  11055. }
  11056. var Curves = /*#__PURE__*/Object.freeze({
  11057. __proto__: null,
  11058. ArcCurve: ArcCurve,
  11059. CatmullRomCurve3: CatmullRomCurve3,
  11060. CubicBezierCurve: CubicBezierCurve,
  11061. CubicBezierCurve3: CubicBezierCurve3,
  11062. EllipseCurve: EllipseCurve,
  11063. LineCurve: LineCurve,
  11064. LineCurve3: LineCurve3,
  11065. QuadraticBezierCurve: QuadraticBezierCurve,
  11066. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11067. SplineCurve: SplineCurve
  11068. });
  11069. /**************************************************************
  11070. * Curved Path - a curve path is simply a array of connected
  11071. * curves, but retains the api of a curve
  11072. **************************************************************/
  11073. class CurvePath extends Curve {
  11074. constructor() {
  11075. super();
  11076. this.type = 'CurvePath';
  11077. this.curves = [];
  11078. this.autoClose = false; // Automatically closes the path
  11079. }
  11080. add( curve ) {
  11081. this.curves.push( curve );
  11082. }
  11083. closePath() {
  11084. // Add a line curve if start and end of lines are not connected
  11085. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11086. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11087. if ( ! startPoint.equals( endPoint ) ) {
  11088. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11089. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11090. }
  11091. return this;
  11092. }
  11093. // To get accurate point with reference to
  11094. // entire path distance at time t,
  11095. // following has to be done:
  11096. // 1. Length of each sub path have to be known
  11097. // 2. Locate and identify type of curve
  11098. // 3. Get t for the curve
  11099. // 4. Return curve.getPointAt(t')
  11100. getPoint( t, optionalTarget ) {
  11101. const d = t * this.getLength();
  11102. const curveLengths = this.getCurveLengths();
  11103. let i = 0;
  11104. // To think about boundaries points.
  11105. while ( i < curveLengths.length ) {
  11106. if ( curveLengths[ i ] >= d ) {
  11107. const diff = curveLengths[ i ] - d;
  11108. const curve = this.curves[ i ];
  11109. const segmentLength = curve.getLength();
  11110. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11111. return curve.getPointAt( u, optionalTarget );
  11112. }
  11113. i ++;
  11114. }
  11115. return null;
  11116. // loop where sum != 0, sum > d , sum+1 <d
  11117. }
  11118. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11119. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11120. // getPoint() depends on getLength
  11121. getLength() {
  11122. const lens = this.getCurveLengths();
  11123. return lens[ lens.length - 1 ];
  11124. }
  11125. // cacheLengths must be recalculated.
  11126. updateArcLengths() {
  11127. this.needsUpdate = true;
  11128. this.cacheLengths = null;
  11129. this.getCurveLengths();
  11130. }
  11131. // Compute lengths and cache them
  11132. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11133. getCurveLengths() {
  11134. // We use cache values if curves and cache array are same length
  11135. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11136. return this.cacheLengths;
  11137. }
  11138. // Get length of sub-curve
  11139. // Push sums into cached array
  11140. const lengths = [];
  11141. let sums = 0;
  11142. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11143. sums += this.curves[ i ].getLength();
  11144. lengths.push( sums );
  11145. }
  11146. this.cacheLengths = lengths;
  11147. return lengths;
  11148. }
  11149. getSpacedPoints( divisions = 40 ) {
  11150. const points = [];
  11151. for ( let i = 0; i <= divisions; i ++ ) {
  11152. points.push( this.getPoint( i / divisions ) );
  11153. }
  11154. if ( this.autoClose ) {
  11155. points.push( points[ 0 ] );
  11156. }
  11157. return points;
  11158. }
  11159. getPoints( divisions = 12 ) {
  11160. const points = [];
  11161. let last;
  11162. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11163. const curve = curves[ i ];
  11164. const resolution = curve.isEllipseCurve ? divisions * 2
  11165. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11166. : curve.isSplineCurve ? divisions * curve.points.length
  11167. : divisions;
  11168. const pts = curve.getPoints( resolution );
  11169. for ( let j = 0; j < pts.length; j ++ ) {
  11170. const point = pts[ j ];
  11171. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11172. points.push( point );
  11173. last = point;
  11174. }
  11175. }
  11176. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11177. points.push( points[ 0 ] );
  11178. }
  11179. return points;
  11180. }
  11181. copy( source ) {
  11182. super.copy( source );
  11183. this.curves = [];
  11184. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11185. const curve = source.curves[ i ];
  11186. this.curves.push( curve.clone() );
  11187. }
  11188. this.autoClose = source.autoClose;
  11189. return this;
  11190. }
  11191. toJSON() {
  11192. const data = super.toJSON();
  11193. data.autoClose = this.autoClose;
  11194. data.curves = [];
  11195. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11196. const curve = this.curves[ i ];
  11197. data.curves.push( curve.toJSON() );
  11198. }
  11199. return data;
  11200. }
  11201. fromJSON( json ) {
  11202. super.fromJSON( json );
  11203. this.autoClose = json.autoClose;
  11204. this.curves = [];
  11205. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11206. const curve = json.curves[ i ];
  11207. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11208. }
  11209. return this;
  11210. }
  11211. }
  11212. class Path extends CurvePath {
  11213. constructor( points ) {
  11214. super();
  11215. this.type = 'Path';
  11216. this.currentPoint = new Vector2();
  11217. if ( points ) {
  11218. this.setFromPoints( points );
  11219. }
  11220. }
  11221. setFromPoints( points ) {
  11222. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11223. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11224. this.lineTo( points[ i ].x, points[ i ].y );
  11225. }
  11226. return this;
  11227. }
  11228. moveTo( x, y ) {
  11229. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11230. return this;
  11231. }
  11232. lineTo( x, y ) {
  11233. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11234. this.curves.push( curve );
  11235. this.currentPoint.set( x, y );
  11236. return this;
  11237. }
  11238. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11239. const curve = new QuadraticBezierCurve(
  11240. this.currentPoint.clone(),
  11241. new Vector2( aCPx, aCPy ),
  11242. new Vector2( aX, aY )
  11243. );
  11244. this.curves.push( curve );
  11245. this.currentPoint.set( aX, aY );
  11246. return this;
  11247. }
  11248. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11249. const curve = new CubicBezierCurve(
  11250. this.currentPoint.clone(),
  11251. new Vector2( aCP1x, aCP1y ),
  11252. new Vector2( aCP2x, aCP2y ),
  11253. new Vector2( aX, aY )
  11254. );
  11255. this.curves.push( curve );
  11256. this.currentPoint.set( aX, aY );
  11257. return this;
  11258. }
  11259. splineThru( pts /*Array of Vector*/ ) {
  11260. const npts = [ this.currentPoint.clone() ].concat( pts );
  11261. const curve = new SplineCurve( npts );
  11262. this.curves.push( curve );
  11263. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11264. return this;
  11265. }
  11266. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11267. const x0 = this.currentPoint.x;
  11268. const y0 = this.currentPoint.y;
  11269. this.absarc( aX + x0, aY + y0, aRadius,
  11270. aStartAngle, aEndAngle, aClockwise );
  11271. return this;
  11272. }
  11273. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11274. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11275. return this;
  11276. }
  11277. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11278. const x0 = this.currentPoint.x;
  11279. const y0 = this.currentPoint.y;
  11280. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11281. return this;
  11282. }
  11283. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11284. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11285. if ( this.curves.length > 0 ) {
  11286. // if a previous curve is present, attempt to join
  11287. const firstPoint = curve.getPoint( 0 );
  11288. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11289. this.lineTo( firstPoint.x, firstPoint.y );
  11290. }
  11291. }
  11292. this.curves.push( curve );
  11293. const lastPoint = curve.getPoint( 1 );
  11294. this.currentPoint.copy( lastPoint );
  11295. return this;
  11296. }
  11297. copy( source ) {
  11298. super.copy( source );
  11299. this.currentPoint.copy( source.currentPoint );
  11300. return this;
  11301. }
  11302. toJSON() {
  11303. const data = super.toJSON();
  11304. data.currentPoint = this.currentPoint.toArray();
  11305. return data;
  11306. }
  11307. fromJSON( json ) {
  11308. super.fromJSON( json );
  11309. this.currentPoint.fromArray( json.currentPoint );
  11310. return this;
  11311. }
  11312. }
  11313. class LatheGeometry extends BufferGeometry {
  11314. constructor( points = [ new Vector2( 0, - 0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  11315. super();
  11316. this.type = 'LatheGeometry';
  11317. this.parameters = {
  11318. points: points,
  11319. segments: segments,
  11320. phiStart: phiStart,
  11321. phiLength: phiLength
  11322. };
  11323. segments = Math.floor( segments );
  11324. // clamp phiLength so it's in range of [ 0, 2PI ]
  11325. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11326. // buffers
  11327. const indices = [];
  11328. const vertices = [];
  11329. const uvs = [];
  11330. const initNormals = [];
  11331. const normals = [];
  11332. // helper variables
  11333. const inverseSegments = 1.0 / segments;
  11334. const vertex = new Vector3();
  11335. const uv = new Vector2();
  11336. const normal = new Vector3();
  11337. const curNormal = new Vector3();
  11338. const prevNormal = new Vector3();
  11339. let dx = 0;
  11340. let dy = 0;
  11341. // pre-compute normals for initial "meridian"
  11342. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11343. switch ( j ) {
  11344. case 0: // special handling for 1st vertex on path
  11345. dx = points[ j + 1 ].x - points[ j ].x;
  11346. dy = points[ j + 1 ].y - points[ j ].y;
  11347. normal.x = dy * 1.0;
  11348. normal.y = - dx;
  11349. normal.z = dy * 0.0;
  11350. prevNormal.copy( normal );
  11351. normal.normalize();
  11352. initNormals.push( normal.x, normal.y, normal.z );
  11353. break;
  11354. case ( points.length - 1 ): // special handling for last Vertex on path
  11355. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11356. break;
  11357. default: // default handling for all vertices in between
  11358. dx = points[ j + 1 ].x - points[ j ].x;
  11359. dy = points[ j + 1 ].y - points[ j ].y;
  11360. normal.x = dy * 1.0;
  11361. normal.y = - dx;
  11362. normal.z = dy * 0.0;
  11363. curNormal.copy( normal );
  11364. normal.x += prevNormal.x;
  11365. normal.y += prevNormal.y;
  11366. normal.z += prevNormal.z;
  11367. normal.normalize();
  11368. initNormals.push( normal.x, normal.y, normal.z );
  11369. prevNormal.copy( curNormal );
  11370. }
  11371. }
  11372. // generate vertices, uvs and normals
  11373. for ( let i = 0; i <= segments; i ++ ) {
  11374. const phi = phiStart + i * inverseSegments * phiLength;
  11375. const sin = Math.sin( phi );
  11376. const cos = Math.cos( phi );
  11377. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11378. // vertex
  11379. vertex.x = points[ j ].x * sin;
  11380. vertex.y = points[ j ].y;
  11381. vertex.z = points[ j ].x * cos;
  11382. vertices.push( vertex.x, vertex.y, vertex.z );
  11383. // uv
  11384. uv.x = i / segments;
  11385. uv.y = j / ( points.length - 1 );
  11386. uvs.push( uv.x, uv.y );
  11387. // normal
  11388. const x = initNormals[ 3 * j + 0 ] * sin;
  11389. const y = initNormals[ 3 * j + 1 ];
  11390. const z = initNormals[ 3 * j + 0 ] * cos;
  11391. normals.push( x, y, z );
  11392. }
  11393. }
  11394. // indices
  11395. for ( let i = 0; i < segments; i ++ ) {
  11396. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11397. const base = j + i * points.length;
  11398. const a = base;
  11399. const b = base + points.length;
  11400. const c = base + points.length + 1;
  11401. const d = base + 1;
  11402. // faces
  11403. indices.push( a, b, d );
  11404. indices.push( c, d, b );
  11405. }
  11406. }
  11407. // build geometry
  11408. this.setIndex( indices );
  11409. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11410. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11411. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11412. }
  11413. copy( source ) {
  11414. super.copy( source );
  11415. this.parameters = Object.assign( {}, source.parameters );
  11416. return this;
  11417. }
  11418. static fromJSON( data ) {
  11419. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11420. }
  11421. }
  11422. class CapsuleGeometry extends LatheGeometry {
  11423. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11424. const path = new Path();
  11425. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11426. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11427. super( path.getPoints( capSegments ), radialSegments );
  11428. this.type = 'CapsuleGeometry';
  11429. this.parameters = {
  11430. radius: radius,
  11431. length: length,
  11432. capSegments: capSegments,
  11433. radialSegments: radialSegments,
  11434. };
  11435. }
  11436. static fromJSON( data ) {
  11437. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11438. }
  11439. }
  11440. class CircleGeometry extends BufferGeometry {
  11441. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11442. super();
  11443. this.type = 'CircleGeometry';
  11444. this.parameters = {
  11445. radius: radius,
  11446. segments: segments,
  11447. thetaStart: thetaStart,
  11448. thetaLength: thetaLength
  11449. };
  11450. segments = Math.max( 3, segments );
  11451. // buffers
  11452. const indices = [];
  11453. const vertices = [];
  11454. const normals = [];
  11455. const uvs = [];
  11456. // helper variables
  11457. const vertex = new Vector3();
  11458. const uv = new Vector2();
  11459. // center point
  11460. vertices.push( 0, 0, 0 );
  11461. normals.push( 0, 0, 1 );
  11462. uvs.push( 0.5, 0.5 );
  11463. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11464. const segment = thetaStart + s / segments * thetaLength;
  11465. // vertex
  11466. vertex.x = radius * Math.cos( segment );
  11467. vertex.y = radius * Math.sin( segment );
  11468. vertices.push( vertex.x, vertex.y, vertex.z );
  11469. // normal
  11470. normals.push( 0, 0, 1 );
  11471. // uvs
  11472. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11473. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11474. uvs.push( uv.x, uv.y );
  11475. }
  11476. // indices
  11477. for ( let i = 1; i <= segments; i ++ ) {
  11478. indices.push( i, i + 1, 0 );
  11479. }
  11480. // build geometry
  11481. this.setIndex( indices );
  11482. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11483. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11484. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11485. }
  11486. copy( source ) {
  11487. super.copy( source );
  11488. this.parameters = Object.assign( {}, source.parameters );
  11489. return this;
  11490. }
  11491. static fromJSON( data ) {
  11492. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11493. }
  11494. }
  11495. class CylinderGeometry extends BufferGeometry {
  11496. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11497. super();
  11498. this.type = 'CylinderGeometry';
  11499. this.parameters = {
  11500. radiusTop: radiusTop,
  11501. radiusBottom: radiusBottom,
  11502. height: height,
  11503. radialSegments: radialSegments,
  11504. heightSegments: heightSegments,
  11505. openEnded: openEnded,
  11506. thetaStart: thetaStart,
  11507. thetaLength: thetaLength
  11508. };
  11509. const scope = this;
  11510. radialSegments = Math.floor( radialSegments );
  11511. heightSegments = Math.floor( heightSegments );
  11512. // buffers
  11513. const indices = [];
  11514. const vertices = [];
  11515. const normals = [];
  11516. const uvs = [];
  11517. // helper variables
  11518. let index = 0;
  11519. const indexArray = [];
  11520. const halfHeight = height / 2;
  11521. let groupStart = 0;
  11522. // generate geometry
  11523. generateTorso();
  11524. if ( openEnded === false ) {
  11525. if ( radiusTop > 0 ) generateCap( true );
  11526. if ( radiusBottom > 0 ) generateCap( false );
  11527. }
  11528. // build geometry
  11529. this.setIndex( indices );
  11530. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11531. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11532. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11533. function generateTorso() {
  11534. const normal = new Vector3();
  11535. const vertex = new Vector3();
  11536. let groupCount = 0;
  11537. // this will be used to calculate the normal
  11538. const slope = ( radiusBottom - radiusTop ) / height;
  11539. // generate vertices, normals and uvs
  11540. for ( let y = 0; y <= heightSegments; y ++ ) {
  11541. const indexRow = [];
  11542. const v = y / heightSegments;
  11543. // calculate the radius of the current row
  11544. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11545. for ( let x = 0; x <= radialSegments; x ++ ) {
  11546. const u = x / radialSegments;
  11547. const theta = u * thetaLength + thetaStart;
  11548. const sinTheta = Math.sin( theta );
  11549. const cosTheta = Math.cos( theta );
  11550. // vertex
  11551. vertex.x = radius * sinTheta;
  11552. vertex.y = - v * height + halfHeight;
  11553. vertex.z = radius * cosTheta;
  11554. vertices.push( vertex.x, vertex.y, vertex.z );
  11555. // normal
  11556. normal.set( sinTheta, slope, cosTheta ).normalize();
  11557. normals.push( normal.x, normal.y, normal.z );
  11558. // uv
  11559. uvs.push( u, 1 - v );
  11560. // save index of vertex in respective row
  11561. indexRow.push( index ++ );
  11562. }
  11563. // now save vertices of the row in our index array
  11564. indexArray.push( indexRow );
  11565. }
  11566. // generate indices
  11567. for ( let x = 0; x < radialSegments; x ++ ) {
  11568. for ( let y = 0; y < heightSegments; y ++ ) {
  11569. // we use the index array to access the correct indices
  11570. const a = indexArray[ y ][ x ];
  11571. const b = indexArray[ y + 1 ][ x ];
  11572. const c = indexArray[ y + 1 ][ x + 1 ];
  11573. const d = indexArray[ y ][ x + 1 ];
  11574. // faces
  11575. if ( radiusTop > 0 ) {
  11576. indices.push( a, b, d );
  11577. groupCount += 3;
  11578. }
  11579. if ( radiusBottom > 0 ) {
  11580. indices.push( b, c, d );
  11581. groupCount += 3;
  11582. }
  11583. }
  11584. }
  11585. // add a group to the geometry. this will ensure multi material support
  11586. scope.addGroup( groupStart, groupCount, 0 );
  11587. // calculate new start value for groups
  11588. groupStart += groupCount;
  11589. }
  11590. function generateCap( top ) {
  11591. // save the index of the first center vertex
  11592. const centerIndexStart = index;
  11593. const uv = new Vector2();
  11594. const vertex = new Vector3();
  11595. let groupCount = 0;
  11596. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11597. const sign = ( top === true ) ? 1 : - 1;
  11598. // first we generate the center vertex data of the cap.
  11599. // because the geometry needs one set of uvs per face,
  11600. // we must generate a center vertex per face/segment
  11601. for ( let x = 1; x <= radialSegments; x ++ ) {
  11602. // vertex
  11603. vertices.push( 0, halfHeight * sign, 0 );
  11604. // normal
  11605. normals.push( 0, sign, 0 );
  11606. // uv
  11607. uvs.push( 0.5, 0.5 );
  11608. // increase index
  11609. index ++;
  11610. }
  11611. // save the index of the last center vertex
  11612. const centerIndexEnd = index;
  11613. // now we generate the surrounding vertices, normals and uvs
  11614. for ( let x = 0; x <= radialSegments; x ++ ) {
  11615. const u = x / radialSegments;
  11616. const theta = u * thetaLength + thetaStart;
  11617. const cosTheta = Math.cos( theta );
  11618. const sinTheta = Math.sin( theta );
  11619. // vertex
  11620. vertex.x = radius * sinTheta;
  11621. vertex.y = halfHeight * sign;
  11622. vertex.z = radius * cosTheta;
  11623. vertices.push( vertex.x, vertex.y, vertex.z );
  11624. // normal
  11625. normals.push( 0, sign, 0 );
  11626. // uv
  11627. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11628. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11629. uvs.push( uv.x, uv.y );
  11630. // increase index
  11631. index ++;
  11632. }
  11633. // generate indices
  11634. for ( let x = 0; x < radialSegments; x ++ ) {
  11635. const c = centerIndexStart + x;
  11636. const i = centerIndexEnd + x;
  11637. if ( top === true ) {
  11638. // face top
  11639. indices.push( i, i + 1, c );
  11640. } else {
  11641. // face bottom
  11642. indices.push( i + 1, i, c );
  11643. }
  11644. groupCount += 3;
  11645. }
  11646. // add a group to the geometry. this will ensure multi material support
  11647. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11648. // calculate new start value for groups
  11649. groupStart += groupCount;
  11650. }
  11651. }
  11652. copy( source ) {
  11653. super.copy( source );
  11654. this.parameters = Object.assign( {}, source.parameters );
  11655. return this;
  11656. }
  11657. static fromJSON( data ) {
  11658. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11659. }
  11660. }
  11661. class ConeGeometry extends CylinderGeometry {
  11662. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11663. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11664. this.type = 'ConeGeometry';
  11665. this.parameters = {
  11666. radius: radius,
  11667. height: height,
  11668. radialSegments: radialSegments,
  11669. heightSegments: heightSegments,
  11670. openEnded: openEnded,
  11671. thetaStart: thetaStart,
  11672. thetaLength: thetaLength
  11673. };
  11674. }
  11675. static fromJSON( data ) {
  11676. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11677. }
  11678. }
  11679. class PolyhedronGeometry extends BufferGeometry {
  11680. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11681. super();
  11682. this.type = 'PolyhedronGeometry';
  11683. this.parameters = {
  11684. vertices: vertices,
  11685. indices: indices,
  11686. radius: radius,
  11687. detail: detail
  11688. };
  11689. // default buffer data
  11690. const vertexBuffer = [];
  11691. const uvBuffer = [];
  11692. // the subdivision creates the vertex buffer data
  11693. subdivide( detail );
  11694. // all vertices should lie on a conceptual sphere with a given radius
  11695. applyRadius( radius );
  11696. // finally, create the uv data
  11697. generateUVs();
  11698. // build non-indexed geometry
  11699. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11700. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11701. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11702. if ( detail === 0 ) {
  11703. this.computeVertexNormals(); // flat normals
  11704. } else {
  11705. this.normalizeNormals(); // smooth normals
  11706. }
  11707. // helper functions
  11708. function subdivide( detail ) {
  11709. const a = new Vector3();
  11710. const b = new Vector3();
  11711. const c = new Vector3();
  11712. // iterate over all faces and apply a subdivision with the given detail value
  11713. for ( let i = 0; i < indices.length; i += 3 ) {
  11714. // get the vertices of the face
  11715. getVertexByIndex( indices[ i + 0 ], a );
  11716. getVertexByIndex( indices[ i + 1 ], b );
  11717. getVertexByIndex( indices[ i + 2 ], c );
  11718. // perform subdivision
  11719. subdivideFace( a, b, c, detail );
  11720. }
  11721. }
  11722. function subdivideFace( a, b, c, detail ) {
  11723. const cols = detail + 1;
  11724. // we use this multidimensional array as a data structure for creating the subdivision
  11725. const v = [];
  11726. // construct all of the vertices for this subdivision
  11727. for ( let i = 0; i <= cols; i ++ ) {
  11728. v[ i ] = [];
  11729. const aj = a.clone().lerp( c, i / cols );
  11730. const bj = b.clone().lerp( c, i / cols );
  11731. const rows = cols - i;
  11732. for ( let j = 0; j <= rows; j ++ ) {
  11733. if ( j === 0 && i === cols ) {
  11734. v[ i ][ j ] = aj;
  11735. } else {
  11736. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11737. }
  11738. }
  11739. }
  11740. // construct all of the faces
  11741. for ( let i = 0; i < cols; i ++ ) {
  11742. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11743. const k = Math.floor( j / 2 );
  11744. if ( j % 2 === 0 ) {
  11745. pushVertex( v[ i ][ k + 1 ] );
  11746. pushVertex( v[ i + 1 ][ k ] );
  11747. pushVertex( v[ i ][ k ] );
  11748. } else {
  11749. pushVertex( v[ i ][ k + 1 ] );
  11750. pushVertex( v[ i + 1 ][ k + 1 ] );
  11751. pushVertex( v[ i + 1 ][ k ] );
  11752. }
  11753. }
  11754. }
  11755. }
  11756. function applyRadius( radius ) {
  11757. const vertex = new Vector3();
  11758. // iterate over the entire buffer and apply the radius to each vertex
  11759. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11760. vertex.x = vertexBuffer[ i + 0 ];
  11761. vertex.y = vertexBuffer[ i + 1 ];
  11762. vertex.z = vertexBuffer[ i + 2 ];
  11763. vertex.normalize().multiplyScalar( radius );
  11764. vertexBuffer[ i + 0 ] = vertex.x;
  11765. vertexBuffer[ i + 1 ] = vertex.y;
  11766. vertexBuffer[ i + 2 ] = vertex.z;
  11767. }
  11768. }
  11769. function generateUVs() {
  11770. const vertex = new Vector3();
  11771. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11772. vertex.x = vertexBuffer[ i + 0 ];
  11773. vertex.y = vertexBuffer[ i + 1 ];
  11774. vertex.z = vertexBuffer[ i + 2 ];
  11775. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11776. const v = inclination( vertex ) / Math.PI + 0.5;
  11777. uvBuffer.push( u, 1 - v );
  11778. }
  11779. correctUVs();
  11780. correctSeam();
  11781. }
  11782. function correctSeam() {
  11783. // handle case when face straddles the seam, see #3269
  11784. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11785. // uv data of a single face
  11786. const x0 = uvBuffer[ i + 0 ];
  11787. const x1 = uvBuffer[ i + 2 ];
  11788. const x2 = uvBuffer[ i + 4 ];
  11789. const max = Math.max( x0, x1, x2 );
  11790. const min = Math.min( x0, x1, x2 );
  11791. // 0.9 is somewhat arbitrary
  11792. if ( max > 0.9 && min < 0.1 ) {
  11793. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  11794. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  11795. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  11796. }
  11797. }
  11798. }
  11799. function pushVertex( vertex ) {
  11800. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  11801. }
  11802. function getVertexByIndex( index, vertex ) {
  11803. const stride = index * 3;
  11804. vertex.x = vertices[ stride + 0 ];
  11805. vertex.y = vertices[ stride + 1 ];
  11806. vertex.z = vertices[ stride + 2 ];
  11807. }
  11808. function correctUVs() {
  11809. const a = new Vector3();
  11810. const b = new Vector3();
  11811. const c = new Vector3();
  11812. const centroid = new Vector3();
  11813. const uvA = new Vector2();
  11814. const uvB = new Vector2();
  11815. const uvC = new Vector2();
  11816. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  11817. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  11818. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  11819. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  11820. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  11821. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  11822. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  11823. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  11824. const azi = azimuth( centroid );
  11825. correctUV( uvA, j + 0, a, azi );
  11826. correctUV( uvB, j + 2, b, azi );
  11827. correctUV( uvC, j + 4, c, azi );
  11828. }
  11829. }
  11830. function correctUV( uv, stride, vector, azimuth ) {
  11831. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  11832. uvBuffer[ stride ] = uv.x - 1;
  11833. }
  11834. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  11835. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  11836. }
  11837. }
  11838. // Angle around the Y axis, counter-clockwise when looking from above.
  11839. function azimuth( vector ) {
  11840. return Math.atan2( vector.z, - vector.x );
  11841. }
  11842. // Angle above the XZ plane.
  11843. function inclination( vector ) {
  11844. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  11845. }
  11846. }
  11847. copy( source ) {
  11848. super.copy( source );
  11849. this.parameters = Object.assign( {}, source.parameters );
  11850. return this;
  11851. }
  11852. static fromJSON( data ) {
  11853. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  11854. }
  11855. }
  11856. class DodecahedronGeometry extends PolyhedronGeometry {
  11857. constructor( radius = 1, detail = 0 ) {
  11858. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  11859. const r = 1 / t;
  11860. const vertices = [
  11861. // (±1, ±1, ±1)
  11862. - 1, - 1, - 1, - 1, - 1, 1,
  11863. - 1, 1, - 1, - 1, 1, 1,
  11864. 1, - 1, - 1, 1, - 1, 1,
  11865. 1, 1, - 1, 1, 1, 1,
  11866. // (0, ±1/φ, ±φ)
  11867. 0, - r, - t, 0, - r, t,
  11868. 0, r, - t, 0, r, t,
  11869. // (±1/φ, ±φ, 0)
  11870. - r, - t, 0, - r, t, 0,
  11871. r, - t, 0, r, t, 0,
  11872. // (±φ, 0, ±1/φ)
  11873. - t, 0, - r, t, 0, - r,
  11874. - t, 0, r, t, 0, r
  11875. ];
  11876. const indices = [
  11877. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  11878. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  11879. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  11880. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  11881. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  11882. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  11883. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  11884. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  11885. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  11886. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  11887. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  11888. 1, 12, 14, 1, 14, 5, 1, 5, 9
  11889. ];
  11890. super( vertices, indices, radius, detail );
  11891. this.type = 'DodecahedronGeometry';
  11892. this.parameters = {
  11893. radius: radius,
  11894. detail: detail
  11895. };
  11896. }
  11897. static fromJSON( data ) {
  11898. return new DodecahedronGeometry( data.radius, data.detail );
  11899. }
  11900. }
  11901. const _v0 = /*@__PURE__*/ new Vector3();
  11902. const _v1$1 = /*@__PURE__*/ new Vector3();
  11903. const _normal$1 = /*@__PURE__*/ new Vector3();
  11904. const _triangle = /*@__PURE__*/ new Triangle();
  11905. class EdgesGeometry extends BufferGeometry {
  11906. constructor( geometry = null, thresholdAngle = 1 ) {
  11907. super();
  11908. this.type = 'EdgesGeometry';
  11909. this.parameters = {
  11910. geometry: geometry,
  11911. thresholdAngle: thresholdAngle
  11912. };
  11913. if ( geometry !== null ) {
  11914. const precisionPoints = 4;
  11915. const precision = Math.pow( 10, precisionPoints );
  11916. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  11917. const indexAttr = geometry.getIndex();
  11918. const positionAttr = geometry.getAttribute( 'position' );
  11919. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  11920. const indexArr = [ 0, 0, 0 ];
  11921. const vertKeys = [ 'a', 'b', 'c' ];
  11922. const hashes = new Array( 3 );
  11923. const edgeData = {};
  11924. const vertices = [];
  11925. for ( let i = 0; i < indexCount; i += 3 ) {
  11926. if ( indexAttr ) {
  11927. indexArr[ 0 ] = indexAttr.getX( i );
  11928. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  11929. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  11930. } else {
  11931. indexArr[ 0 ] = i;
  11932. indexArr[ 1 ] = i + 1;
  11933. indexArr[ 2 ] = i + 2;
  11934. }
  11935. const { a, b, c } = _triangle;
  11936. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  11937. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  11938. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  11939. _triangle.getNormal( _normal$1 );
  11940. // create hashes for the edge from the vertices
  11941. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  11942. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  11943. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  11944. // skip degenerate triangles
  11945. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  11946. continue;
  11947. }
  11948. // iterate over every edge
  11949. for ( let j = 0; j < 3; j ++ ) {
  11950. // get the first and next vertex making up the edge
  11951. const jNext = ( j + 1 ) % 3;
  11952. const vecHash0 = hashes[ j ];
  11953. const vecHash1 = hashes[ jNext ];
  11954. const v0 = _triangle[ vertKeys[ j ] ];
  11955. const v1 = _triangle[ vertKeys[ jNext ] ];
  11956. const hash = `${ vecHash0 }_${ vecHash1 }`;
  11957. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  11958. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  11959. // if we found a sibling edge add it into the vertex array if
  11960. // it meets the angle threshold and delete the edge from the map.
  11961. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  11962. vertices.push( v0.x, v0.y, v0.z );
  11963. vertices.push( v1.x, v1.y, v1.z );
  11964. }
  11965. edgeData[ reverseHash ] = null;
  11966. } else if ( ! ( hash in edgeData ) ) {
  11967. // if we've already got an edge here then skip adding a new one
  11968. edgeData[ hash ] = {
  11969. index0: indexArr[ j ],
  11970. index1: indexArr[ jNext ],
  11971. normal: _normal$1.clone(),
  11972. };
  11973. }
  11974. }
  11975. }
  11976. // iterate over all remaining, unmatched edges and add them to the vertex array
  11977. for ( const key in edgeData ) {
  11978. if ( edgeData[ key ] ) {
  11979. const { index0, index1 } = edgeData[ key ];
  11980. _v0.fromBufferAttribute( positionAttr, index0 );
  11981. _v1$1.fromBufferAttribute( positionAttr, index1 );
  11982. vertices.push( _v0.x, _v0.y, _v0.z );
  11983. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  11984. }
  11985. }
  11986. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11987. }
  11988. }
  11989. copy( source ) {
  11990. super.copy( source );
  11991. this.parameters = Object.assign( {}, source.parameters );
  11992. return this;
  11993. }
  11994. }
  11995. class Shape extends Path {
  11996. constructor( points ) {
  11997. super( points );
  11998. this.uuid = generateUUID();
  11999. this.type = 'Shape';
  12000. this.holes = [];
  12001. }
  12002. getPointsHoles( divisions ) {
  12003. const holesPts = [];
  12004. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12005. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  12006. }
  12007. return holesPts;
  12008. }
  12009. // get points of shape and holes (keypoints based on segments parameter)
  12010. extractPoints( divisions ) {
  12011. return {
  12012. shape: this.getPoints( divisions ),
  12013. holes: this.getPointsHoles( divisions )
  12014. };
  12015. }
  12016. copy( source ) {
  12017. super.copy( source );
  12018. this.holes = [];
  12019. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  12020. const hole = source.holes[ i ];
  12021. this.holes.push( hole.clone() );
  12022. }
  12023. return this;
  12024. }
  12025. toJSON() {
  12026. const data = super.toJSON();
  12027. data.uuid = this.uuid;
  12028. data.holes = [];
  12029. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12030. const hole = this.holes[ i ];
  12031. data.holes.push( hole.toJSON() );
  12032. }
  12033. return data;
  12034. }
  12035. fromJSON( json ) {
  12036. super.fromJSON( json );
  12037. this.uuid = json.uuid;
  12038. this.holes = [];
  12039. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  12040. const hole = json.holes[ i ];
  12041. this.holes.push( new Path().fromJSON( hole ) );
  12042. }
  12043. return this;
  12044. }
  12045. }
  12046. /**
  12047. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12048. */
  12049. const Earcut = {
  12050. triangulate: function ( data, holeIndices, dim = 2 ) {
  12051. const hasHoles = holeIndices && holeIndices.length;
  12052. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12053. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12054. const triangles = [];
  12055. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12056. let minX, minY, maxX, maxY, x, y, invSize;
  12057. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12058. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12059. if ( data.length > 80 * dim ) {
  12060. minX = maxX = data[ 0 ];
  12061. minY = maxY = data[ 1 ];
  12062. for ( let i = dim; i < outerLen; i += dim ) {
  12063. x = data[ i ];
  12064. y = data[ i + 1 ];
  12065. if ( x < minX ) minX = x;
  12066. if ( y < minY ) minY = y;
  12067. if ( x > maxX ) maxX = x;
  12068. if ( y > maxY ) maxY = y;
  12069. }
  12070. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12071. invSize = Math.max( maxX - minX, maxY - minY );
  12072. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12073. }
  12074. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12075. return triangles;
  12076. }
  12077. };
  12078. // create a circular doubly linked list from polygon points in the specified winding order
  12079. function linkedList( data, start, end, dim, clockwise ) {
  12080. let i, last;
  12081. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12082. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12083. } else {
  12084. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12085. }
  12086. if ( last && equals$1( last, last.next ) ) {
  12087. removeNode( last );
  12088. last = last.next;
  12089. }
  12090. return last;
  12091. }
  12092. // eliminate colinear or duplicate points
  12093. function filterPoints( start, end ) {
  12094. if ( ! start ) return start;
  12095. if ( ! end ) end = start;
  12096. let p = start,
  12097. again;
  12098. do {
  12099. again = false;
  12100. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12101. removeNode( p );
  12102. p = end = p.prev;
  12103. if ( p === p.next ) break;
  12104. again = true;
  12105. } else {
  12106. p = p.next;
  12107. }
  12108. } while ( again || p !== end );
  12109. return end;
  12110. }
  12111. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12112. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12113. if ( ! ear ) return;
  12114. // interlink polygon nodes in z-order
  12115. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12116. let stop = ear,
  12117. prev, next;
  12118. // iterate through ears, slicing them one by one
  12119. while ( ear.prev !== ear.next ) {
  12120. prev = ear.prev;
  12121. next = ear.next;
  12122. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12123. // cut off the triangle
  12124. triangles.push( prev.i / dim | 0 );
  12125. triangles.push( ear.i / dim | 0 );
  12126. triangles.push( next.i / dim | 0 );
  12127. removeNode( ear );
  12128. // skipping the next vertex leads to less sliver triangles
  12129. ear = next.next;
  12130. stop = next.next;
  12131. continue;
  12132. }
  12133. ear = next;
  12134. // if we looped through the whole remaining polygon and can't find any more ears
  12135. if ( ear === stop ) {
  12136. // try filtering points and slicing again
  12137. if ( ! pass ) {
  12138. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12139. // if this didn't work, try curing all small self-intersections locally
  12140. } else if ( pass === 1 ) {
  12141. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12142. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12143. // as a last resort, try splitting the remaining polygon into two
  12144. } else if ( pass === 2 ) {
  12145. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12146. }
  12147. break;
  12148. }
  12149. }
  12150. }
  12151. // check whether a polygon node forms a valid ear with adjacent nodes
  12152. function isEar( ear ) {
  12153. const a = ear.prev,
  12154. b = ear,
  12155. c = ear.next;
  12156. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12157. // now make sure we don't have other points inside the potential ear
  12158. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12159. // triangle bbox; min & max are calculated like this for speed
  12160. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12161. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12162. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12163. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12164. let p = c.next;
  12165. while ( p !== a ) {
  12166. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12167. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12168. area( p.prev, p, p.next ) >= 0 ) return false;
  12169. p = p.next;
  12170. }
  12171. return true;
  12172. }
  12173. function isEarHashed( ear, minX, minY, invSize ) {
  12174. const a = ear.prev,
  12175. b = ear,
  12176. c = ear.next;
  12177. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12178. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12179. // triangle bbox; min & max are calculated like this for speed
  12180. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12181. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12182. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12183. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12184. // z-order range for the current triangle bbox;
  12185. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12186. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12187. let p = ear.prevZ,
  12188. n = ear.nextZ;
  12189. // look for points inside the triangle in both directions
  12190. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12191. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12192. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12193. p = p.prevZ;
  12194. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12195. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12196. n = n.nextZ;
  12197. }
  12198. // look for remaining points in decreasing z-order
  12199. while ( p && p.z >= minZ ) {
  12200. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12201. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12202. p = p.prevZ;
  12203. }
  12204. // look for remaining points in increasing z-order
  12205. while ( n && n.z <= maxZ ) {
  12206. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12207. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12208. n = n.nextZ;
  12209. }
  12210. return true;
  12211. }
  12212. // go through all polygon nodes and cure small local self-intersections
  12213. function cureLocalIntersections( start, triangles, dim ) {
  12214. let p = start;
  12215. do {
  12216. const a = p.prev,
  12217. b = p.next.next;
  12218. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12219. triangles.push( a.i / dim | 0 );
  12220. triangles.push( p.i / dim | 0 );
  12221. triangles.push( b.i / dim | 0 );
  12222. // remove two nodes involved
  12223. removeNode( p );
  12224. removeNode( p.next );
  12225. p = start = b;
  12226. }
  12227. p = p.next;
  12228. } while ( p !== start );
  12229. return filterPoints( p );
  12230. }
  12231. // try splitting polygon into two and triangulate them independently
  12232. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12233. // look for a valid diagonal that divides the polygon into two
  12234. let a = start;
  12235. do {
  12236. let b = a.next.next;
  12237. while ( b !== a.prev ) {
  12238. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12239. // split the polygon in two by the diagonal
  12240. let c = splitPolygon( a, b );
  12241. // filter colinear points around the cuts
  12242. a = filterPoints( a, a.next );
  12243. c = filterPoints( c, c.next );
  12244. // run earcut on each half
  12245. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12246. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12247. return;
  12248. }
  12249. b = b.next;
  12250. }
  12251. a = a.next;
  12252. } while ( a !== start );
  12253. }
  12254. // link every hole into the outer loop, producing a single-ring polygon without holes
  12255. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12256. const queue = [];
  12257. let i, len, start, end, list;
  12258. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12259. start = holeIndices[ i ] * dim;
  12260. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12261. list = linkedList( data, start, end, dim, false );
  12262. if ( list === list.next ) list.steiner = true;
  12263. queue.push( getLeftmost( list ) );
  12264. }
  12265. queue.sort( compareX );
  12266. // process holes from left to right
  12267. for ( i = 0; i < queue.length; i ++ ) {
  12268. outerNode = eliminateHole( queue[ i ], outerNode );
  12269. }
  12270. return outerNode;
  12271. }
  12272. function compareX( a, b ) {
  12273. return a.x - b.x;
  12274. }
  12275. // find a bridge between vertices that connects hole with an outer ring and link it
  12276. function eliminateHole( hole, outerNode ) {
  12277. const bridge = findHoleBridge( hole, outerNode );
  12278. if ( ! bridge ) {
  12279. return outerNode;
  12280. }
  12281. const bridgeReverse = splitPolygon( bridge, hole );
  12282. // filter collinear points around the cuts
  12283. filterPoints( bridgeReverse, bridgeReverse.next );
  12284. return filterPoints( bridge, bridge.next );
  12285. }
  12286. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12287. function findHoleBridge( hole, outerNode ) {
  12288. let p = outerNode,
  12289. qx = - Infinity,
  12290. m;
  12291. const hx = hole.x, hy = hole.y;
  12292. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12293. // segment's endpoint with lesser x will be potential connection point
  12294. do {
  12295. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12296. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12297. if ( x <= hx && x > qx ) {
  12298. qx = x;
  12299. m = p.x < p.next.x ? p : p.next;
  12300. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12301. }
  12302. }
  12303. p = p.next;
  12304. } while ( p !== outerNode );
  12305. if ( ! m ) return null;
  12306. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12307. // if there are no points found, we have a valid connection;
  12308. // otherwise choose the point of the minimum angle with the ray as connection point
  12309. const stop = m,
  12310. mx = m.x,
  12311. my = m.y;
  12312. let tanMin = Infinity, tan;
  12313. p = m;
  12314. do {
  12315. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12316. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12317. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12318. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12319. m = p;
  12320. tanMin = tan;
  12321. }
  12322. }
  12323. p = p.next;
  12324. } while ( p !== stop );
  12325. return m;
  12326. }
  12327. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12328. function sectorContainsSector( m, p ) {
  12329. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12330. }
  12331. // interlink polygon nodes in z-order
  12332. function indexCurve( start, minX, minY, invSize ) {
  12333. let p = start;
  12334. do {
  12335. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12336. p.prevZ = p.prev;
  12337. p.nextZ = p.next;
  12338. p = p.next;
  12339. } while ( p !== start );
  12340. p.prevZ.nextZ = null;
  12341. p.prevZ = null;
  12342. sortLinked( p );
  12343. }
  12344. // Simon Tatham's linked list merge sort algorithm
  12345. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12346. function sortLinked( list ) {
  12347. let i, p, q, e, tail, numMerges, pSize, qSize,
  12348. inSize = 1;
  12349. do {
  12350. p = list;
  12351. list = null;
  12352. tail = null;
  12353. numMerges = 0;
  12354. while ( p ) {
  12355. numMerges ++;
  12356. q = p;
  12357. pSize = 0;
  12358. for ( i = 0; i < inSize; i ++ ) {
  12359. pSize ++;
  12360. q = q.nextZ;
  12361. if ( ! q ) break;
  12362. }
  12363. qSize = inSize;
  12364. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12365. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12366. e = p;
  12367. p = p.nextZ;
  12368. pSize --;
  12369. } else {
  12370. e = q;
  12371. q = q.nextZ;
  12372. qSize --;
  12373. }
  12374. if ( tail ) tail.nextZ = e;
  12375. else list = e;
  12376. e.prevZ = tail;
  12377. tail = e;
  12378. }
  12379. p = q;
  12380. }
  12381. tail.nextZ = null;
  12382. inSize *= 2;
  12383. } while ( numMerges > 1 );
  12384. return list;
  12385. }
  12386. // z-order of a point given coords and inverse of the longer side of data bbox
  12387. function zOrder( x, y, minX, minY, invSize ) {
  12388. // coords are transformed into non-negative 15-bit integer range
  12389. x = ( x - minX ) * invSize | 0;
  12390. y = ( y - minY ) * invSize | 0;
  12391. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12392. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12393. x = ( x | ( x << 2 ) ) & 0x33333333;
  12394. x = ( x | ( x << 1 ) ) & 0x55555555;
  12395. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12396. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12397. y = ( y | ( y << 2 ) ) & 0x33333333;
  12398. y = ( y | ( y << 1 ) ) & 0x55555555;
  12399. return x | ( y << 1 );
  12400. }
  12401. // find the leftmost node of a polygon ring
  12402. function getLeftmost( start ) {
  12403. let p = start,
  12404. leftmost = start;
  12405. do {
  12406. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12407. p = p.next;
  12408. } while ( p !== start );
  12409. return leftmost;
  12410. }
  12411. // check if a point lies within a convex triangle
  12412. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12413. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12414. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12415. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12416. }
  12417. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12418. function isValidDiagonal( a, b ) {
  12419. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12420. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12421. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12422. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12423. }
  12424. // signed area of a triangle
  12425. function area( p, q, r ) {
  12426. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12427. }
  12428. // check if two points are equal
  12429. function equals$1( p1, p2 ) {
  12430. return p1.x === p2.x && p1.y === p2.y;
  12431. }
  12432. // check if two segments intersect
  12433. function intersects( p1, q1, p2, q2 ) {
  12434. const o1 = sign$1( area( p1, q1, p2 ) );
  12435. const o2 = sign$1( area( p1, q1, q2 ) );
  12436. const o3 = sign$1( area( p2, q2, p1 ) );
  12437. const o4 = sign$1( area( p2, q2, q1 ) );
  12438. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12439. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12440. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12441. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12442. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12443. return false;
  12444. }
  12445. // for collinear points p, q, r, check if point q lies on segment pr
  12446. function onSegment( p, q, r ) {
  12447. return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y );
  12448. }
  12449. function sign$1( num ) {
  12450. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12451. }
  12452. // check if a polygon diagonal intersects any polygon segments
  12453. function intersectsPolygon( a, b ) {
  12454. let p = a;
  12455. do {
  12456. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12457. intersects( p, p.next, a, b ) ) return true;
  12458. p = p.next;
  12459. } while ( p !== a );
  12460. return false;
  12461. }
  12462. // check if a polygon diagonal is locally inside the polygon
  12463. function locallyInside( a, b ) {
  12464. return area( a.prev, a, a.next ) < 0 ?
  12465. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12466. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12467. }
  12468. // check if the middle point of a polygon diagonal is inside the polygon
  12469. function middleInside( a, b ) {
  12470. let p = a,
  12471. inside = false;
  12472. const px = ( a.x + b.x ) / 2,
  12473. py = ( a.y + b.y ) / 2;
  12474. do {
  12475. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12476. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12477. inside = ! inside;
  12478. p = p.next;
  12479. } while ( p !== a );
  12480. return inside;
  12481. }
  12482. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12483. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12484. function splitPolygon( a, b ) {
  12485. const a2 = new Node$1( a.i, a.x, a.y ),
  12486. b2 = new Node$1( b.i, b.x, b.y ),
  12487. an = a.next,
  12488. bp = b.prev;
  12489. a.next = b;
  12490. b.prev = a;
  12491. a2.next = an;
  12492. an.prev = a2;
  12493. b2.next = a2;
  12494. a2.prev = b2;
  12495. bp.next = b2;
  12496. b2.prev = bp;
  12497. return b2;
  12498. }
  12499. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12500. function insertNode( i, x, y, last ) {
  12501. const p = new Node$1( i, x, y );
  12502. if ( ! last ) {
  12503. p.prev = p;
  12504. p.next = p;
  12505. } else {
  12506. p.next = last.next;
  12507. p.prev = last;
  12508. last.next.prev = p;
  12509. last.next = p;
  12510. }
  12511. return p;
  12512. }
  12513. function removeNode( p ) {
  12514. p.next.prev = p.prev;
  12515. p.prev.next = p.next;
  12516. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12517. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12518. }
  12519. function Node$1( i, x, y ) {
  12520. // vertex index in coordinates array
  12521. this.i = i;
  12522. // vertex coordinates
  12523. this.x = x;
  12524. this.y = y;
  12525. // previous and next vertex nodes in a polygon ring
  12526. this.prev = null;
  12527. this.next = null;
  12528. // z-order curve value
  12529. this.z = 0;
  12530. // previous and next nodes in z-order
  12531. this.prevZ = null;
  12532. this.nextZ = null;
  12533. // indicates whether this is a steiner point
  12534. this.steiner = false;
  12535. }
  12536. function signedArea( data, start, end, dim ) {
  12537. let sum = 0;
  12538. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12539. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12540. j = i;
  12541. }
  12542. return sum;
  12543. }
  12544. class ShapeUtils {
  12545. // calculate area of the contour polygon
  12546. static area( contour ) {
  12547. const n = contour.length;
  12548. let a = 0.0;
  12549. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12550. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12551. }
  12552. return a * 0.5;
  12553. }
  12554. static isClockWise( pts ) {
  12555. return ShapeUtils.area( pts ) < 0;
  12556. }
  12557. static triangulateShape( contour, holes ) {
  12558. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12559. const holeIndices = []; // array of hole indices
  12560. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12561. removeDupEndPts( contour );
  12562. addContour( vertices, contour );
  12563. //
  12564. let holeIndex = contour.length;
  12565. holes.forEach( removeDupEndPts );
  12566. for ( let i = 0; i < holes.length; i ++ ) {
  12567. holeIndices.push( holeIndex );
  12568. holeIndex += holes[ i ].length;
  12569. addContour( vertices, holes[ i ] );
  12570. }
  12571. //
  12572. const triangles = Earcut.triangulate( vertices, holeIndices );
  12573. //
  12574. for ( let i = 0; i < triangles.length; i += 3 ) {
  12575. faces.push( triangles.slice( i, i + 3 ) );
  12576. }
  12577. return faces;
  12578. }
  12579. }
  12580. function removeDupEndPts( points ) {
  12581. const l = points.length;
  12582. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12583. points.pop();
  12584. }
  12585. }
  12586. function addContour( vertices, contour ) {
  12587. for ( let i = 0; i < contour.length; i ++ ) {
  12588. vertices.push( contour[ i ].x );
  12589. vertices.push( contour[ i ].y );
  12590. }
  12591. }
  12592. /**
  12593. * Creates extruded geometry from a path shape.
  12594. *
  12595. * parameters = {
  12596. *
  12597. * curveSegments: <int>, // number of points on the curves
  12598. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12599. * depth: <float>, // Depth to extrude the shape
  12600. *
  12601. * bevelEnabled: <bool>, // turn on bevel
  12602. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12603. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12604. * bevelOffset: <float>, // how far from shape outline does bevel start
  12605. * bevelSegments: <int>, // number of bevel layers
  12606. *
  12607. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12608. *
  12609. * UVGenerator: <Object> // object that provides UV generator functions
  12610. *
  12611. * }
  12612. */
  12613. class ExtrudeGeometry extends BufferGeometry {
  12614. constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) {
  12615. super();
  12616. this.type = 'ExtrudeGeometry';
  12617. this.parameters = {
  12618. shapes: shapes,
  12619. options: options
  12620. };
  12621. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12622. const scope = this;
  12623. const verticesArray = [];
  12624. const uvArray = [];
  12625. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12626. const shape = shapes[ i ];
  12627. addShape( shape );
  12628. }
  12629. // build geometry
  12630. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12631. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12632. this.computeVertexNormals();
  12633. // functions
  12634. function addShape( shape ) {
  12635. const placeholder = [];
  12636. // options
  12637. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12638. const steps = options.steps !== undefined ? options.steps : 1;
  12639. const depth = options.depth !== undefined ? options.depth : 1;
  12640. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12641. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12642. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12643. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12644. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12645. const extrudePath = options.extrudePath;
  12646. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12647. //
  12648. let extrudePts, extrudeByPath = false;
  12649. let splineTube, binormal, normal, position2;
  12650. if ( extrudePath ) {
  12651. extrudePts = extrudePath.getSpacedPoints( steps );
  12652. extrudeByPath = true;
  12653. bevelEnabled = false; // bevels not supported for path extrusion
  12654. // SETUP TNB variables
  12655. // TODO1 - have a .isClosed in spline?
  12656. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12657. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12658. binormal = new Vector3();
  12659. normal = new Vector3();
  12660. position2 = new Vector3();
  12661. }
  12662. // Safeguards if bevels are not enabled
  12663. if ( ! bevelEnabled ) {
  12664. bevelSegments = 0;
  12665. bevelThickness = 0;
  12666. bevelSize = 0;
  12667. bevelOffset = 0;
  12668. }
  12669. // Variables initialization
  12670. const shapePoints = shape.extractPoints( curveSegments );
  12671. let vertices = shapePoints.shape;
  12672. const holes = shapePoints.holes;
  12673. const reverse = ! ShapeUtils.isClockWise( vertices );
  12674. if ( reverse ) {
  12675. vertices = vertices.reverse();
  12676. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12677. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12678. const ahole = holes[ h ];
  12679. if ( ShapeUtils.isClockWise( ahole ) ) {
  12680. holes[ h ] = ahole.reverse();
  12681. }
  12682. }
  12683. }
  12684. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12685. /* Vertices */
  12686. const contour = vertices; // vertices has all points but contour has only points of circumference
  12687. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12688. const ahole = holes[ h ];
  12689. vertices = vertices.concat( ahole );
  12690. }
  12691. function scalePt2( pt, vec, size ) {
  12692. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12693. return pt.clone().addScaledVector( vec, size );
  12694. }
  12695. const vlen = vertices.length, flen = faces.length;
  12696. // Find directions for point movement
  12697. function getBevelVec( inPt, inPrev, inNext ) {
  12698. // computes for inPt the corresponding point inPt' on a new contour
  12699. // shifted by 1 unit (length of normalized vector) to the left
  12700. // if we walk along contour clockwise, this new contour is outside the old one
  12701. //
  12702. // inPt' is the intersection of the two lines parallel to the two
  12703. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12704. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12705. // good reading for geometry algorithms (here: line-line intersection)
  12706. // http://geomalgorithms.com/a05-_intersect-1.html
  12707. const v_prev_x = inPt.x - inPrev.x,
  12708. v_prev_y = inPt.y - inPrev.y;
  12709. const v_next_x = inNext.x - inPt.x,
  12710. v_next_y = inNext.y - inPt.y;
  12711. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12712. // check for collinear edges
  12713. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12714. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12715. // not collinear
  12716. // length of vectors for normalizing
  12717. const v_prev_len = Math.sqrt( v_prev_lensq );
  12718. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12719. // shift adjacent points by unit vectors to the left
  12720. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12721. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12722. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12723. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12724. // scaling factor for v_prev to intersection point
  12725. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12726. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12727. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12728. // vector from inPt to intersection point
  12729. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12730. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12731. // Don't normalize!, otherwise sharp corners become ugly
  12732. // but prevent crazy spikes
  12733. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12734. if ( v_trans_lensq <= 2 ) {
  12735. return new Vector2( v_trans_x, v_trans_y );
  12736. } else {
  12737. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12738. }
  12739. } else {
  12740. // handle special case of collinear edges
  12741. let direction_eq = false; // assumes: opposite
  12742. if ( v_prev_x > Number.EPSILON ) {
  12743. if ( v_next_x > Number.EPSILON ) {
  12744. direction_eq = true;
  12745. }
  12746. } else {
  12747. if ( v_prev_x < - Number.EPSILON ) {
  12748. if ( v_next_x < - Number.EPSILON ) {
  12749. direction_eq = true;
  12750. }
  12751. } else {
  12752. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12753. direction_eq = true;
  12754. }
  12755. }
  12756. }
  12757. if ( direction_eq ) {
  12758. // console.log("Warning: lines are a straight sequence");
  12759. v_trans_x = - v_prev_y;
  12760. v_trans_y = v_prev_x;
  12761. shrink_by = Math.sqrt( v_prev_lensq );
  12762. } else {
  12763. // console.log("Warning: lines are a straight spike");
  12764. v_trans_x = v_prev_x;
  12765. v_trans_y = v_prev_y;
  12766. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12767. }
  12768. }
  12769. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12770. }
  12771. const contourMovements = [];
  12772. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12773. if ( j === il ) j = 0;
  12774. if ( k === il ) k = 0;
  12775. // (j)---(i)---(k)
  12776. // console.log('i,j,k', i, j , k)
  12777. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12778. }
  12779. const holesMovements = [];
  12780. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12781. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12782. const ahole = holes[ h ];
  12783. oneHoleMovements = [];
  12784. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12785. if ( j === il ) j = 0;
  12786. if ( k === il ) k = 0;
  12787. // (j)---(i)---(k)
  12788. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12789. }
  12790. holesMovements.push( oneHoleMovements );
  12791. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12792. }
  12793. // Loop bevelSegments, 1 for the front, 1 for the back
  12794. for ( let b = 0; b < bevelSegments; b ++ ) {
  12795. //for ( b = bevelSegments; b > 0; b -- ) {
  12796. const t = b / bevelSegments;
  12797. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12798. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12799. // contract shape
  12800. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12801. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12802. v( vert.x, vert.y, - z );
  12803. }
  12804. // expand holes
  12805. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12806. const ahole = holes[ h ];
  12807. oneHoleMovements = holesMovements[ h ];
  12808. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12809. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12810. v( vert.x, vert.y, - z );
  12811. }
  12812. }
  12813. }
  12814. const bs = bevelSize + bevelOffset;
  12815. // Back facing vertices
  12816. for ( let i = 0; i < vlen; i ++ ) {
  12817. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12818. if ( ! extrudeByPath ) {
  12819. v( vert.x, vert.y, 0 );
  12820. } else {
  12821. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  12822. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  12823. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  12824. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  12825. v( position2.x, position2.y, position2.z );
  12826. }
  12827. }
  12828. // Add stepped vertices...
  12829. // Including front facing vertices
  12830. for ( let s = 1; s <= steps; s ++ ) {
  12831. for ( let i = 0; i < vlen; i ++ ) {
  12832. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12833. if ( ! extrudeByPath ) {
  12834. v( vert.x, vert.y, depth / steps * s );
  12835. } else {
  12836. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  12837. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  12838. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  12839. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  12840. v( position2.x, position2.y, position2.z );
  12841. }
  12842. }
  12843. }
  12844. // Add bevel segments planes
  12845. //for ( b = 1; b <= bevelSegments; b ++ ) {
  12846. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  12847. const t = b / bevelSegments;
  12848. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12849. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12850. // contract shape
  12851. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12852. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12853. v( vert.x, vert.y, depth + z );
  12854. }
  12855. // expand holes
  12856. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12857. const ahole = holes[ h ];
  12858. oneHoleMovements = holesMovements[ h ];
  12859. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12860. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12861. if ( ! extrudeByPath ) {
  12862. v( vert.x, vert.y, depth + z );
  12863. } else {
  12864. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  12865. }
  12866. }
  12867. }
  12868. }
  12869. /* Faces */
  12870. // Top and bottom faces
  12871. buildLidFaces();
  12872. // Sides faces
  12873. buildSideFaces();
  12874. ///// Internal functions
  12875. function buildLidFaces() {
  12876. const start = verticesArray.length / 3;
  12877. if ( bevelEnabled ) {
  12878. let layer = 0; // steps + 1
  12879. let offset = vlen * layer;
  12880. // Bottom faces
  12881. for ( let i = 0; i < flen; i ++ ) {
  12882. const face = faces[ i ];
  12883. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  12884. }
  12885. layer = steps + bevelSegments * 2;
  12886. offset = vlen * layer;
  12887. // Top faces
  12888. for ( let i = 0; i < flen; i ++ ) {
  12889. const face = faces[ i ];
  12890. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  12891. }
  12892. } else {
  12893. // Bottom faces
  12894. for ( let i = 0; i < flen; i ++ ) {
  12895. const face = faces[ i ];
  12896. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  12897. }
  12898. // Top faces
  12899. for ( let i = 0; i < flen; i ++ ) {
  12900. const face = faces[ i ];
  12901. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  12902. }
  12903. }
  12904. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  12905. }
  12906. // Create faces for the z-sides of the shape
  12907. function buildSideFaces() {
  12908. const start = verticesArray.length / 3;
  12909. let layeroffset = 0;
  12910. sidewalls( contour, layeroffset );
  12911. layeroffset += contour.length;
  12912. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12913. const ahole = holes[ h ];
  12914. sidewalls( ahole, layeroffset );
  12915. //, true
  12916. layeroffset += ahole.length;
  12917. }
  12918. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  12919. }
  12920. function sidewalls( contour, layeroffset ) {
  12921. let i = contour.length;
  12922. while ( -- i >= 0 ) {
  12923. const j = i;
  12924. let k = i - 1;
  12925. if ( k < 0 ) k = contour.length - 1;
  12926. //console.log('b', i,j, i-1, k,vertices.length);
  12927. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  12928. const slen1 = vlen * s;
  12929. const slen2 = vlen * ( s + 1 );
  12930. const a = layeroffset + j + slen1,
  12931. b = layeroffset + k + slen1,
  12932. c = layeroffset + k + slen2,
  12933. d = layeroffset + j + slen2;
  12934. f4( a, b, c, d );
  12935. }
  12936. }
  12937. }
  12938. function v( x, y, z ) {
  12939. placeholder.push( x );
  12940. placeholder.push( y );
  12941. placeholder.push( z );
  12942. }
  12943. function f3( a, b, c ) {
  12944. addVertex( a );
  12945. addVertex( b );
  12946. addVertex( c );
  12947. const nextIndex = verticesArray.length / 3;
  12948. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12949. addUV( uvs[ 0 ] );
  12950. addUV( uvs[ 1 ] );
  12951. addUV( uvs[ 2 ] );
  12952. }
  12953. function f4( a, b, c, d ) {
  12954. addVertex( a );
  12955. addVertex( b );
  12956. addVertex( d );
  12957. addVertex( b );
  12958. addVertex( c );
  12959. addVertex( d );
  12960. const nextIndex = verticesArray.length / 3;
  12961. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  12962. addUV( uvs[ 0 ] );
  12963. addUV( uvs[ 1 ] );
  12964. addUV( uvs[ 3 ] );
  12965. addUV( uvs[ 1 ] );
  12966. addUV( uvs[ 2 ] );
  12967. addUV( uvs[ 3 ] );
  12968. }
  12969. function addVertex( index ) {
  12970. verticesArray.push( placeholder[ index * 3 + 0 ] );
  12971. verticesArray.push( placeholder[ index * 3 + 1 ] );
  12972. verticesArray.push( placeholder[ index * 3 + 2 ] );
  12973. }
  12974. function addUV( vector2 ) {
  12975. uvArray.push( vector2.x );
  12976. uvArray.push( vector2.y );
  12977. }
  12978. }
  12979. }
  12980. copy( source ) {
  12981. super.copy( source );
  12982. this.parameters = Object.assign( {}, source.parameters );
  12983. return this;
  12984. }
  12985. toJSON() {
  12986. const data = super.toJSON();
  12987. const shapes = this.parameters.shapes;
  12988. const options = this.parameters.options;
  12989. return toJSON$1( shapes, options, data );
  12990. }
  12991. static fromJSON( data, shapes ) {
  12992. const geometryShapes = [];
  12993. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  12994. const shape = shapes[ data.shapes[ j ] ];
  12995. geometryShapes.push( shape );
  12996. }
  12997. const extrudePath = data.options.extrudePath;
  12998. if ( extrudePath !== undefined ) {
  12999. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  13000. }
  13001. return new ExtrudeGeometry( geometryShapes, data.options );
  13002. }
  13003. }
  13004. const WorldUVGenerator = {
  13005. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  13006. const a_x = vertices[ indexA * 3 ];
  13007. const a_y = vertices[ indexA * 3 + 1 ];
  13008. const b_x = vertices[ indexB * 3 ];
  13009. const b_y = vertices[ indexB * 3 + 1 ];
  13010. const c_x = vertices[ indexC * 3 ];
  13011. const c_y = vertices[ indexC * 3 + 1 ];
  13012. return [
  13013. new Vector2( a_x, a_y ),
  13014. new Vector2( b_x, b_y ),
  13015. new Vector2( c_x, c_y )
  13016. ];
  13017. },
  13018. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  13019. const a_x = vertices[ indexA * 3 ];
  13020. const a_y = vertices[ indexA * 3 + 1 ];
  13021. const a_z = vertices[ indexA * 3 + 2 ];
  13022. const b_x = vertices[ indexB * 3 ];
  13023. const b_y = vertices[ indexB * 3 + 1 ];
  13024. const b_z = vertices[ indexB * 3 + 2 ];
  13025. const c_x = vertices[ indexC * 3 ];
  13026. const c_y = vertices[ indexC * 3 + 1 ];
  13027. const c_z = vertices[ indexC * 3 + 2 ];
  13028. const d_x = vertices[ indexD * 3 ];
  13029. const d_y = vertices[ indexD * 3 + 1 ];
  13030. const d_z = vertices[ indexD * 3 + 2 ];
  13031. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  13032. return [
  13033. new Vector2( a_x, 1 - a_z ),
  13034. new Vector2( b_x, 1 - b_z ),
  13035. new Vector2( c_x, 1 - c_z ),
  13036. new Vector2( d_x, 1 - d_z )
  13037. ];
  13038. } else {
  13039. return [
  13040. new Vector2( a_y, 1 - a_z ),
  13041. new Vector2( b_y, 1 - b_z ),
  13042. new Vector2( c_y, 1 - c_z ),
  13043. new Vector2( d_y, 1 - d_z )
  13044. ];
  13045. }
  13046. }
  13047. };
  13048. function toJSON$1( shapes, options, data ) {
  13049. data.shapes = [];
  13050. if ( Array.isArray( shapes ) ) {
  13051. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13052. const shape = shapes[ i ];
  13053. data.shapes.push( shape.uuid );
  13054. }
  13055. } else {
  13056. data.shapes.push( shapes.uuid );
  13057. }
  13058. data.options = Object.assign( {}, options );
  13059. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13060. return data;
  13061. }
  13062. class IcosahedronGeometry extends PolyhedronGeometry {
  13063. constructor( radius = 1, detail = 0 ) {
  13064. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13065. const vertices = [
  13066. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13067. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13068. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13069. ];
  13070. const indices = [
  13071. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13072. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13073. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13074. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13075. ];
  13076. super( vertices, indices, radius, detail );
  13077. this.type = 'IcosahedronGeometry';
  13078. this.parameters = {
  13079. radius: radius,
  13080. detail: detail
  13081. };
  13082. }
  13083. static fromJSON( data ) {
  13084. return new IcosahedronGeometry( data.radius, data.detail );
  13085. }
  13086. }
  13087. class OctahedronGeometry extends PolyhedronGeometry {
  13088. constructor( radius = 1, detail = 0 ) {
  13089. const vertices = [
  13090. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13091. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13092. ];
  13093. const indices = [
  13094. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13095. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13096. 1, 3, 4, 1, 4, 2
  13097. ];
  13098. super( vertices, indices, radius, detail );
  13099. this.type = 'OctahedronGeometry';
  13100. this.parameters = {
  13101. radius: radius,
  13102. detail: detail
  13103. };
  13104. }
  13105. static fromJSON( data ) {
  13106. return new OctahedronGeometry( data.radius, data.detail );
  13107. }
  13108. }
  13109. class PlaneGeometry extends BufferGeometry {
  13110. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13111. super();
  13112. this.type = 'PlaneGeometry';
  13113. this.parameters = {
  13114. width: width,
  13115. height: height,
  13116. widthSegments: widthSegments,
  13117. heightSegments: heightSegments
  13118. };
  13119. const width_half = width / 2;
  13120. const height_half = height / 2;
  13121. const gridX = Math.floor( widthSegments );
  13122. const gridY = Math.floor( heightSegments );
  13123. const gridX1 = gridX + 1;
  13124. const gridY1 = gridY + 1;
  13125. const segment_width = width / gridX;
  13126. const segment_height = height / gridY;
  13127. //
  13128. const indices = [];
  13129. const vertices = [];
  13130. const normals = [];
  13131. const uvs = [];
  13132. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13133. const y = iy * segment_height - height_half;
  13134. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13135. const x = ix * segment_width - width_half;
  13136. vertices.push( x, - y, 0 );
  13137. normals.push( 0, 0, 1 );
  13138. uvs.push( ix / gridX );
  13139. uvs.push( 1 - ( iy / gridY ) );
  13140. }
  13141. }
  13142. for ( let iy = 0; iy < gridY; iy ++ ) {
  13143. for ( let ix = 0; ix < gridX; ix ++ ) {
  13144. const a = ix + gridX1 * iy;
  13145. const b = ix + gridX1 * ( iy + 1 );
  13146. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13147. const d = ( ix + 1 ) + gridX1 * iy;
  13148. indices.push( a, b, d );
  13149. indices.push( b, c, d );
  13150. }
  13151. }
  13152. this.setIndex( indices );
  13153. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13154. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13155. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13156. }
  13157. copy( source ) {
  13158. super.copy( source );
  13159. this.parameters = Object.assign( {}, source.parameters );
  13160. return this;
  13161. }
  13162. static fromJSON( data ) {
  13163. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13164. }
  13165. }
  13166. class RingGeometry extends BufferGeometry {
  13167. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13168. super();
  13169. this.type = 'RingGeometry';
  13170. this.parameters = {
  13171. innerRadius: innerRadius,
  13172. outerRadius: outerRadius,
  13173. thetaSegments: thetaSegments,
  13174. phiSegments: phiSegments,
  13175. thetaStart: thetaStart,
  13176. thetaLength: thetaLength
  13177. };
  13178. thetaSegments = Math.max( 3, thetaSegments );
  13179. phiSegments = Math.max( 1, phiSegments );
  13180. // buffers
  13181. const indices = [];
  13182. const vertices = [];
  13183. const normals = [];
  13184. const uvs = [];
  13185. // some helper variables
  13186. let radius = innerRadius;
  13187. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13188. const vertex = new Vector3();
  13189. const uv = new Vector2();
  13190. // generate vertices, normals and uvs
  13191. for ( let j = 0; j <= phiSegments; j ++ ) {
  13192. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13193. // values are generate from the inside of the ring to the outside
  13194. const segment = thetaStart + i / thetaSegments * thetaLength;
  13195. // vertex
  13196. vertex.x = radius * Math.cos( segment );
  13197. vertex.y = radius * Math.sin( segment );
  13198. vertices.push( vertex.x, vertex.y, vertex.z );
  13199. // normal
  13200. normals.push( 0, 0, 1 );
  13201. // uv
  13202. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13203. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13204. uvs.push( uv.x, uv.y );
  13205. }
  13206. // increase the radius for next row of vertices
  13207. radius += radiusStep;
  13208. }
  13209. // indices
  13210. for ( let j = 0; j < phiSegments; j ++ ) {
  13211. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13212. for ( let i = 0; i < thetaSegments; i ++ ) {
  13213. const segment = i + thetaSegmentLevel;
  13214. const a = segment;
  13215. const b = segment + thetaSegments + 1;
  13216. const c = segment + thetaSegments + 2;
  13217. const d = segment + 1;
  13218. // faces
  13219. indices.push( a, b, d );
  13220. indices.push( b, c, d );
  13221. }
  13222. }
  13223. // build geometry
  13224. this.setIndex( indices );
  13225. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13226. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13227. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13228. }
  13229. copy( source ) {
  13230. super.copy( source );
  13231. this.parameters = Object.assign( {}, source.parameters );
  13232. return this;
  13233. }
  13234. static fromJSON( data ) {
  13235. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13236. }
  13237. }
  13238. class ShapeGeometry extends BufferGeometry {
  13239. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13240. super();
  13241. this.type = 'ShapeGeometry';
  13242. this.parameters = {
  13243. shapes: shapes,
  13244. curveSegments: curveSegments
  13245. };
  13246. // buffers
  13247. const indices = [];
  13248. const vertices = [];
  13249. const normals = [];
  13250. const uvs = [];
  13251. // helper variables
  13252. let groupStart = 0;
  13253. let groupCount = 0;
  13254. // allow single and array values for "shapes" parameter
  13255. if ( Array.isArray( shapes ) === false ) {
  13256. addShape( shapes );
  13257. } else {
  13258. for ( let i = 0; i < shapes.length; i ++ ) {
  13259. addShape( shapes[ i ] );
  13260. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13261. groupStart += groupCount;
  13262. groupCount = 0;
  13263. }
  13264. }
  13265. // build geometry
  13266. this.setIndex( indices );
  13267. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13268. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13269. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13270. // helper functions
  13271. function addShape( shape ) {
  13272. const indexOffset = vertices.length / 3;
  13273. const points = shape.extractPoints( curveSegments );
  13274. let shapeVertices = points.shape;
  13275. const shapeHoles = points.holes;
  13276. // check direction of vertices
  13277. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13278. shapeVertices = shapeVertices.reverse();
  13279. }
  13280. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13281. const shapeHole = shapeHoles[ i ];
  13282. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13283. shapeHoles[ i ] = shapeHole.reverse();
  13284. }
  13285. }
  13286. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13287. // join vertices of inner and outer paths to a single array
  13288. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13289. const shapeHole = shapeHoles[ i ];
  13290. shapeVertices = shapeVertices.concat( shapeHole );
  13291. }
  13292. // vertices, normals, uvs
  13293. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13294. const vertex = shapeVertices[ i ];
  13295. vertices.push( vertex.x, vertex.y, 0 );
  13296. normals.push( 0, 0, 1 );
  13297. uvs.push( vertex.x, vertex.y ); // world uvs
  13298. }
  13299. // indices
  13300. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13301. const face = faces[ i ];
  13302. const a = face[ 0 ] + indexOffset;
  13303. const b = face[ 1 ] + indexOffset;
  13304. const c = face[ 2 ] + indexOffset;
  13305. indices.push( a, b, c );
  13306. groupCount += 3;
  13307. }
  13308. }
  13309. }
  13310. copy( source ) {
  13311. super.copy( source );
  13312. this.parameters = Object.assign( {}, source.parameters );
  13313. return this;
  13314. }
  13315. toJSON() {
  13316. const data = super.toJSON();
  13317. const shapes = this.parameters.shapes;
  13318. return toJSON( shapes, data );
  13319. }
  13320. static fromJSON( data, shapes ) {
  13321. const geometryShapes = [];
  13322. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13323. const shape = shapes[ data.shapes[ j ] ];
  13324. geometryShapes.push( shape );
  13325. }
  13326. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13327. }
  13328. }
  13329. function toJSON( shapes, data ) {
  13330. data.shapes = [];
  13331. if ( Array.isArray( shapes ) ) {
  13332. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13333. const shape = shapes[ i ];
  13334. data.shapes.push( shape.uuid );
  13335. }
  13336. } else {
  13337. data.shapes.push( shapes.uuid );
  13338. }
  13339. return data;
  13340. }
  13341. class SphereGeometry extends BufferGeometry {
  13342. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13343. super();
  13344. this.type = 'SphereGeometry';
  13345. this.parameters = {
  13346. radius: radius,
  13347. widthSegments: widthSegments,
  13348. heightSegments: heightSegments,
  13349. phiStart: phiStart,
  13350. phiLength: phiLength,
  13351. thetaStart: thetaStart,
  13352. thetaLength: thetaLength
  13353. };
  13354. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13355. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13356. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13357. let index = 0;
  13358. const grid = [];
  13359. const vertex = new Vector3();
  13360. const normal = new Vector3();
  13361. // buffers
  13362. const indices = [];
  13363. const vertices = [];
  13364. const normals = [];
  13365. const uvs = [];
  13366. // generate vertices, normals and uvs
  13367. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13368. const verticesRow = [];
  13369. const v = iy / heightSegments;
  13370. // special case for the poles
  13371. let uOffset = 0;
  13372. if ( iy === 0 && thetaStart === 0 ) {
  13373. uOffset = 0.5 / widthSegments;
  13374. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13375. uOffset = - 0.5 / widthSegments;
  13376. }
  13377. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13378. const u = ix / widthSegments;
  13379. // vertex
  13380. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13381. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13382. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13383. vertices.push( vertex.x, vertex.y, vertex.z );
  13384. // normal
  13385. normal.copy( vertex ).normalize();
  13386. normals.push( normal.x, normal.y, normal.z );
  13387. // uv
  13388. uvs.push( u + uOffset, 1 - v );
  13389. verticesRow.push( index ++ );
  13390. }
  13391. grid.push( verticesRow );
  13392. }
  13393. // indices
  13394. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13395. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13396. const a = grid[ iy ][ ix + 1 ];
  13397. const b = grid[ iy ][ ix ];
  13398. const c = grid[ iy + 1 ][ ix ];
  13399. const d = grid[ iy + 1 ][ ix + 1 ];
  13400. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13401. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13402. }
  13403. }
  13404. // build geometry
  13405. this.setIndex( indices );
  13406. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13407. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13408. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13409. }
  13410. copy( source ) {
  13411. super.copy( source );
  13412. this.parameters = Object.assign( {}, source.parameters );
  13413. return this;
  13414. }
  13415. static fromJSON( data ) {
  13416. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13417. }
  13418. }
  13419. class TetrahedronGeometry extends PolyhedronGeometry {
  13420. constructor( radius = 1, detail = 0 ) {
  13421. const vertices = [
  13422. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13423. ];
  13424. const indices = [
  13425. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13426. ];
  13427. super( vertices, indices, radius, detail );
  13428. this.type = 'TetrahedronGeometry';
  13429. this.parameters = {
  13430. radius: radius,
  13431. detail: detail
  13432. };
  13433. }
  13434. static fromJSON( data ) {
  13435. return new TetrahedronGeometry( data.radius, data.detail );
  13436. }
  13437. }
  13438. class TorusGeometry extends BufferGeometry {
  13439. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13440. super();
  13441. this.type = 'TorusGeometry';
  13442. this.parameters = {
  13443. radius: radius,
  13444. tube: tube,
  13445. radialSegments: radialSegments,
  13446. tubularSegments: tubularSegments,
  13447. arc: arc
  13448. };
  13449. radialSegments = Math.floor( radialSegments );
  13450. tubularSegments = Math.floor( tubularSegments );
  13451. // buffers
  13452. const indices = [];
  13453. const vertices = [];
  13454. const normals = [];
  13455. const uvs = [];
  13456. // helper variables
  13457. const center = new Vector3();
  13458. const vertex = new Vector3();
  13459. const normal = new Vector3();
  13460. // generate vertices, normals and uvs
  13461. for ( let j = 0; j <= radialSegments; j ++ ) {
  13462. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13463. const u = i / tubularSegments * arc;
  13464. const v = j / radialSegments * Math.PI * 2;
  13465. // vertex
  13466. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13467. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13468. vertex.z = tube * Math.sin( v );
  13469. vertices.push( vertex.x, vertex.y, vertex.z );
  13470. // normal
  13471. center.x = radius * Math.cos( u );
  13472. center.y = radius * Math.sin( u );
  13473. normal.subVectors( vertex, center ).normalize();
  13474. normals.push( normal.x, normal.y, normal.z );
  13475. // uv
  13476. uvs.push( i / tubularSegments );
  13477. uvs.push( j / radialSegments );
  13478. }
  13479. }
  13480. // generate indices
  13481. for ( let j = 1; j <= radialSegments; j ++ ) {
  13482. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13483. // indices
  13484. const a = ( tubularSegments + 1 ) * j + i - 1;
  13485. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13486. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13487. const d = ( tubularSegments + 1 ) * j + i;
  13488. // faces
  13489. indices.push( a, b, d );
  13490. indices.push( b, c, d );
  13491. }
  13492. }
  13493. // build geometry
  13494. this.setIndex( indices );
  13495. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13496. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13497. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13498. }
  13499. copy( source ) {
  13500. super.copy( source );
  13501. this.parameters = Object.assign( {}, source.parameters );
  13502. return this;
  13503. }
  13504. static fromJSON( data ) {
  13505. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13506. }
  13507. }
  13508. class TorusKnotGeometry extends BufferGeometry {
  13509. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13510. super();
  13511. this.type = 'TorusKnotGeometry';
  13512. this.parameters = {
  13513. radius: radius,
  13514. tube: tube,
  13515. tubularSegments: tubularSegments,
  13516. radialSegments: radialSegments,
  13517. p: p,
  13518. q: q
  13519. };
  13520. tubularSegments = Math.floor( tubularSegments );
  13521. radialSegments = Math.floor( radialSegments );
  13522. // buffers
  13523. const indices = [];
  13524. const vertices = [];
  13525. const normals = [];
  13526. const uvs = [];
  13527. // helper variables
  13528. const vertex = new Vector3();
  13529. const normal = new Vector3();
  13530. const P1 = new Vector3();
  13531. const P2 = new Vector3();
  13532. const B = new Vector3();
  13533. const T = new Vector3();
  13534. const N = new Vector3();
  13535. // generate vertices, normals and uvs
  13536. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13537. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13538. const u = i / tubularSegments * p * Math.PI * 2;
  13539. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13540. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13541. calculatePositionOnCurve( u, p, q, radius, P1 );
  13542. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13543. // calculate orthonormal basis
  13544. T.subVectors( P2, P1 );
  13545. N.addVectors( P2, P1 );
  13546. B.crossVectors( T, N );
  13547. N.crossVectors( B, T );
  13548. // normalize B, N. T can be ignored, we don't use it
  13549. B.normalize();
  13550. N.normalize();
  13551. for ( let j = 0; j <= radialSegments; ++ j ) {
  13552. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13553. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13554. const v = j / radialSegments * Math.PI * 2;
  13555. const cx = - tube * Math.cos( v );
  13556. const cy = tube * Math.sin( v );
  13557. // now calculate the final vertex position.
  13558. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13559. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13560. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13561. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13562. vertices.push( vertex.x, vertex.y, vertex.z );
  13563. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13564. normal.subVectors( vertex, P1 ).normalize();
  13565. normals.push( normal.x, normal.y, normal.z );
  13566. // uv
  13567. uvs.push( i / tubularSegments );
  13568. uvs.push( j / radialSegments );
  13569. }
  13570. }
  13571. // generate indices
  13572. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13573. for ( let i = 1; i <= radialSegments; i ++ ) {
  13574. // indices
  13575. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13576. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13577. const c = ( radialSegments + 1 ) * j + i;
  13578. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13579. // faces
  13580. indices.push( a, b, d );
  13581. indices.push( b, c, d );
  13582. }
  13583. }
  13584. // build geometry
  13585. this.setIndex( indices );
  13586. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13587. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13588. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13589. // this function calculates the current position on the torus curve
  13590. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13591. const cu = Math.cos( u );
  13592. const su = Math.sin( u );
  13593. const quOverP = q / p * u;
  13594. const cs = Math.cos( quOverP );
  13595. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13596. position.y = radius * ( 2 + cs ) * su * 0.5;
  13597. position.z = radius * Math.sin( quOverP ) * 0.5;
  13598. }
  13599. }
  13600. copy( source ) {
  13601. super.copy( source );
  13602. this.parameters = Object.assign( {}, source.parameters );
  13603. return this;
  13604. }
  13605. static fromJSON( data ) {
  13606. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13607. }
  13608. }
  13609. class TubeGeometry extends BufferGeometry {
  13610. constructor( path = new QuadraticBezierCurve3( new Vector3( - 1, - 1, 0 ), new Vector3( - 1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  13611. super();
  13612. this.type = 'TubeGeometry';
  13613. this.parameters = {
  13614. path: path,
  13615. tubularSegments: tubularSegments,
  13616. radius: radius,
  13617. radialSegments: radialSegments,
  13618. closed: closed
  13619. };
  13620. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13621. // expose internals
  13622. this.tangents = frames.tangents;
  13623. this.normals = frames.normals;
  13624. this.binormals = frames.binormals;
  13625. // helper variables
  13626. const vertex = new Vector3();
  13627. const normal = new Vector3();
  13628. const uv = new Vector2();
  13629. let P = new Vector3();
  13630. // buffer
  13631. const vertices = [];
  13632. const normals = [];
  13633. const uvs = [];
  13634. const indices = [];
  13635. // create buffer data
  13636. generateBufferData();
  13637. // build geometry
  13638. this.setIndex( indices );
  13639. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13640. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13641. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13642. // functions
  13643. function generateBufferData() {
  13644. for ( let i = 0; i < tubularSegments; i ++ ) {
  13645. generateSegment( i );
  13646. }
  13647. // if the geometry is not closed, generate the last row of vertices and normals
  13648. // at the regular position on the given path
  13649. //
  13650. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13651. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13652. // uvs are generated in a separate function.
  13653. // this makes it easy compute correct values for closed geometries
  13654. generateUVs();
  13655. // finally create faces
  13656. generateIndices();
  13657. }
  13658. function generateSegment( i ) {
  13659. // we use getPointAt to sample evenly distributed points from the given path
  13660. P = path.getPointAt( i / tubularSegments, P );
  13661. // retrieve corresponding normal and binormal
  13662. const N = frames.normals[ i ];
  13663. const B = frames.binormals[ i ];
  13664. // generate normals and vertices for the current segment
  13665. for ( let j = 0; j <= radialSegments; j ++ ) {
  13666. const v = j / radialSegments * Math.PI * 2;
  13667. const sin = Math.sin( v );
  13668. const cos = - Math.cos( v );
  13669. // normal
  13670. normal.x = ( cos * N.x + sin * B.x );
  13671. normal.y = ( cos * N.y + sin * B.y );
  13672. normal.z = ( cos * N.z + sin * B.z );
  13673. normal.normalize();
  13674. normals.push( normal.x, normal.y, normal.z );
  13675. // vertex
  13676. vertex.x = P.x + radius * normal.x;
  13677. vertex.y = P.y + radius * normal.y;
  13678. vertex.z = P.z + radius * normal.z;
  13679. vertices.push( vertex.x, vertex.y, vertex.z );
  13680. }
  13681. }
  13682. function generateIndices() {
  13683. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13684. for ( let i = 1; i <= radialSegments; i ++ ) {
  13685. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13686. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13687. const c = ( radialSegments + 1 ) * j + i;
  13688. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13689. // faces
  13690. indices.push( a, b, d );
  13691. indices.push( b, c, d );
  13692. }
  13693. }
  13694. }
  13695. function generateUVs() {
  13696. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13697. for ( let j = 0; j <= radialSegments; j ++ ) {
  13698. uv.x = i / tubularSegments;
  13699. uv.y = j / radialSegments;
  13700. uvs.push( uv.x, uv.y );
  13701. }
  13702. }
  13703. }
  13704. }
  13705. copy( source ) {
  13706. super.copy( source );
  13707. this.parameters = Object.assign( {}, source.parameters );
  13708. return this;
  13709. }
  13710. toJSON() {
  13711. const data = super.toJSON();
  13712. data.path = this.parameters.path.toJSON();
  13713. return data;
  13714. }
  13715. static fromJSON( data ) {
  13716. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13717. // User defined curves or instances of CurvePath will not be deserialized.
  13718. return new TubeGeometry(
  13719. new Curves[ data.path.type ]().fromJSON( data.path ),
  13720. data.tubularSegments,
  13721. data.radius,
  13722. data.radialSegments,
  13723. data.closed
  13724. );
  13725. }
  13726. }
  13727. class WireframeGeometry extends BufferGeometry {
  13728. constructor( geometry = null ) {
  13729. super();
  13730. this.type = 'WireframeGeometry';
  13731. this.parameters = {
  13732. geometry: geometry
  13733. };
  13734. if ( geometry !== null ) {
  13735. // buffer
  13736. const vertices = [];
  13737. const edges = new Set();
  13738. // helper variables
  13739. const start = new Vector3();
  13740. const end = new Vector3();
  13741. if ( geometry.index !== null ) {
  13742. // indexed BufferGeometry
  13743. const position = geometry.attributes.position;
  13744. const indices = geometry.index;
  13745. let groups = geometry.groups;
  13746. if ( groups.length === 0 ) {
  13747. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13748. }
  13749. // create a data structure that contains all edges without duplicates
  13750. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13751. const group = groups[ o ];
  13752. const groupStart = group.start;
  13753. const groupCount = group.count;
  13754. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13755. for ( let j = 0; j < 3; j ++ ) {
  13756. const index1 = indices.getX( i + j );
  13757. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13758. start.fromBufferAttribute( position, index1 );
  13759. end.fromBufferAttribute( position, index2 );
  13760. if ( isUniqueEdge( start, end, edges ) === true ) {
  13761. vertices.push( start.x, start.y, start.z );
  13762. vertices.push( end.x, end.y, end.z );
  13763. }
  13764. }
  13765. }
  13766. }
  13767. } else {
  13768. // non-indexed BufferGeometry
  13769. const position = geometry.attributes.position;
  13770. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13771. for ( let j = 0; j < 3; j ++ ) {
  13772. // three edges per triangle, an edge is represented as (index1, index2)
  13773. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13774. const index1 = 3 * i + j;
  13775. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13776. start.fromBufferAttribute( position, index1 );
  13777. end.fromBufferAttribute( position, index2 );
  13778. if ( isUniqueEdge( start, end, edges ) === true ) {
  13779. vertices.push( start.x, start.y, start.z );
  13780. vertices.push( end.x, end.y, end.z );
  13781. }
  13782. }
  13783. }
  13784. }
  13785. // build geometry
  13786. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13787. }
  13788. }
  13789. copy( source ) {
  13790. super.copy( source );
  13791. this.parameters = Object.assign( {}, source.parameters );
  13792. return this;
  13793. }
  13794. }
  13795. function isUniqueEdge( start, end, edges ) {
  13796. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  13797. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  13798. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  13799. return false;
  13800. } else {
  13801. edges.add( hash1 );
  13802. edges.add( hash2 );
  13803. return true;
  13804. }
  13805. }
  13806. var Geometries$1 = /*#__PURE__*/Object.freeze({
  13807. __proto__: null,
  13808. BoxGeometry: BoxGeometry,
  13809. CapsuleGeometry: CapsuleGeometry,
  13810. CircleGeometry: CircleGeometry,
  13811. ConeGeometry: ConeGeometry,
  13812. CylinderGeometry: CylinderGeometry,
  13813. DodecahedronGeometry: DodecahedronGeometry,
  13814. EdgesGeometry: EdgesGeometry,
  13815. ExtrudeGeometry: ExtrudeGeometry,
  13816. IcosahedronGeometry: IcosahedronGeometry,
  13817. LatheGeometry: LatheGeometry,
  13818. OctahedronGeometry: OctahedronGeometry,
  13819. PlaneGeometry: PlaneGeometry,
  13820. PolyhedronGeometry: PolyhedronGeometry,
  13821. RingGeometry: RingGeometry,
  13822. ShapeGeometry: ShapeGeometry,
  13823. SphereGeometry: SphereGeometry,
  13824. TetrahedronGeometry: TetrahedronGeometry,
  13825. TorusGeometry: TorusGeometry,
  13826. TorusKnotGeometry: TorusKnotGeometry,
  13827. TubeGeometry: TubeGeometry,
  13828. WireframeGeometry: WireframeGeometry
  13829. });
  13830. class ShadowMaterial extends Material {
  13831. constructor( parameters ) {
  13832. super();
  13833. this.isShadowMaterial = true;
  13834. this.type = 'ShadowMaterial';
  13835. this.color = new Color( 0x000000 );
  13836. this.transparent = true;
  13837. this.fog = true;
  13838. this.setValues( parameters );
  13839. }
  13840. copy( source ) {
  13841. super.copy( source );
  13842. this.color.copy( source.color );
  13843. this.fog = source.fog;
  13844. return this;
  13845. }
  13846. }
  13847. class RawShaderMaterial extends ShaderMaterial {
  13848. constructor( parameters ) {
  13849. super( parameters );
  13850. this.isRawShaderMaterial = true;
  13851. this.type = 'RawShaderMaterial';
  13852. }
  13853. }
  13854. class MeshStandardMaterial extends Material {
  13855. constructor( parameters ) {
  13856. super();
  13857. this.isMeshStandardMaterial = true;
  13858. this.defines = { 'STANDARD': '' };
  13859. this.type = 'MeshStandardMaterial';
  13860. this.color = new Color( 0xffffff ); // diffuse
  13861. this.roughness = 1.0;
  13862. this.metalness = 0.0;
  13863. this.map = null;
  13864. this.lightMap = null;
  13865. this.lightMapIntensity = 1.0;
  13866. this.aoMap = null;
  13867. this.aoMapIntensity = 1.0;
  13868. this.emissive = new Color( 0x000000 );
  13869. this.emissiveIntensity = 1.0;
  13870. this.emissiveMap = null;
  13871. this.bumpMap = null;
  13872. this.bumpScale = 1;
  13873. this.normalMap = null;
  13874. this.normalMapType = TangentSpaceNormalMap;
  13875. this.normalScale = new Vector2( 1, 1 );
  13876. this.displacementMap = null;
  13877. this.displacementScale = 1;
  13878. this.displacementBias = 0;
  13879. this.roughnessMap = null;
  13880. this.metalnessMap = null;
  13881. this.alphaMap = null;
  13882. this.envMap = null;
  13883. this.envMapRotation = new Euler();
  13884. this.envMapIntensity = 1.0;
  13885. this.wireframe = false;
  13886. this.wireframeLinewidth = 1;
  13887. this.wireframeLinecap = 'round';
  13888. this.wireframeLinejoin = 'round';
  13889. this.flatShading = false;
  13890. this.fog = true;
  13891. this.setValues( parameters );
  13892. }
  13893. copy( source ) {
  13894. super.copy( source );
  13895. this.defines = { 'STANDARD': '' };
  13896. this.color.copy( source.color );
  13897. this.roughness = source.roughness;
  13898. this.metalness = source.metalness;
  13899. this.map = source.map;
  13900. this.lightMap = source.lightMap;
  13901. this.lightMapIntensity = source.lightMapIntensity;
  13902. this.aoMap = source.aoMap;
  13903. this.aoMapIntensity = source.aoMapIntensity;
  13904. this.emissive.copy( source.emissive );
  13905. this.emissiveMap = source.emissiveMap;
  13906. this.emissiveIntensity = source.emissiveIntensity;
  13907. this.bumpMap = source.bumpMap;
  13908. this.bumpScale = source.bumpScale;
  13909. this.normalMap = source.normalMap;
  13910. this.normalMapType = source.normalMapType;
  13911. this.normalScale.copy( source.normalScale );
  13912. this.displacementMap = source.displacementMap;
  13913. this.displacementScale = source.displacementScale;
  13914. this.displacementBias = source.displacementBias;
  13915. this.roughnessMap = source.roughnessMap;
  13916. this.metalnessMap = source.metalnessMap;
  13917. this.alphaMap = source.alphaMap;
  13918. this.envMap = source.envMap;
  13919. this.envMapRotation.copy( source.envMapRotation );
  13920. this.envMapIntensity = source.envMapIntensity;
  13921. this.wireframe = source.wireframe;
  13922. this.wireframeLinewidth = source.wireframeLinewidth;
  13923. this.wireframeLinecap = source.wireframeLinecap;
  13924. this.wireframeLinejoin = source.wireframeLinejoin;
  13925. this.flatShading = source.flatShading;
  13926. this.fog = source.fog;
  13927. return this;
  13928. }
  13929. }
  13930. class MeshPhysicalMaterial extends MeshStandardMaterial {
  13931. constructor( parameters ) {
  13932. super();
  13933. this.isMeshPhysicalMaterial = true;
  13934. this.defines = {
  13935. 'STANDARD': '',
  13936. 'PHYSICAL': ''
  13937. };
  13938. this.type = 'MeshPhysicalMaterial';
  13939. this.anisotropyRotation = 0;
  13940. this.anisotropyMap = null;
  13941. this.clearcoatMap = null;
  13942. this.clearcoatRoughness = 0.0;
  13943. this.clearcoatRoughnessMap = null;
  13944. this.clearcoatNormalScale = new Vector2( 1, 1 );
  13945. this.clearcoatNormalMap = null;
  13946. this.ior = 1.5;
  13947. Object.defineProperty( this, 'reflectivity', {
  13948. get: function () {
  13949. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  13950. },
  13951. set: function ( reflectivity ) {
  13952. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  13953. }
  13954. } );
  13955. this.iridescenceMap = null;
  13956. this.iridescenceIOR = 1.3;
  13957. this.iridescenceThicknessRange = [ 100, 400 ];
  13958. this.iridescenceThicknessMap = null;
  13959. this.sheenColor = new Color( 0x000000 );
  13960. this.sheenColorMap = null;
  13961. this.sheenRoughness = 1.0;
  13962. this.sheenRoughnessMap = null;
  13963. this.transmissionMap = null;
  13964. this.thickness = 0;
  13965. this.thicknessMap = null;
  13966. this.attenuationDistance = Infinity;
  13967. this.attenuationColor = new Color( 1, 1, 1 );
  13968. this.specularIntensity = 1.0;
  13969. this.specularIntensityMap = null;
  13970. this.specularColor = new Color( 1, 1, 1 );
  13971. this.specularColorMap = null;
  13972. this._anisotropy = 0;
  13973. this._clearcoat = 0;
  13974. this._dispersion = 0;
  13975. this._iridescence = 0;
  13976. this._sheen = 0.0;
  13977. this._transmission = 0;
  13978. this.setValues( parameters );
  13979. }
  13980. get anisotropy() {
  13981. return this._anisotropy;
  13982. }
  13983. set anisotropy( value ) {
  13984. if ( this._anisotropy > 0 !== value > 0 ) {
  13985. this.version ++;
  13986. }
  13987. this._anisotropy = value;
  13988. }
  13989. get clearcoat() {
  13990. return this._clearcoat;
  13991. }
  13992. set clearcoat( value ) {
  13993. if ( this._clearcoat > 0 !== value > 0 ) {
  13994. this.version ++;
  13995. }
  13996. this._clearcoat = value;
  13997. }
  13998. get iridescence() {
  13999. return this._iridescence;
  14000. }
  14001. set iridescence( value ) {
  14002. if ( this._iridescence > 0 !== value > 0 ) {
  14003. this.version ++;
  14004. }
  14005. this._iridescence = value;
  14006. }
  14007. get dispersion() {
  14008. return this._dispersion;
  14009. }
  14010. set dispersion( value ) {
  14011. if ( this._dispersion > 0 !== value > 0 ) {
  14012. this.version ++;
  14013. }
  14014. this._dispersion = value;
  14015. }
  14016. get sheen() {
  14017. return this._sheen;
  14018. }
  14019. set sheen( value ) {
  14020. if ( this._sheen > 0 !== value > 0 ) {
  14021. this.version ++;
  14022. }
  14023. this._sheen = value;
  14024. }
  14025. get transmission() {
  14026. return this._transmission;
  14027. }
  14028. set transmission( value ) {
  14029. if ( this._transmission > 0 !== value > 0 ) {
  14030. this.version ++;
  14031. }
  14032. this._transmission = value;
  14033. }
  14034. copy( source ) {
  14035. super.copy( source );
  14036. this.defines = {
  14037. 'STANDARD': '',
  14038. 'PHYSICAL': ''
  14039. };
  14040. this.anisotropy = source.anisotropy;
  14041. this.anisotropyRotation = source.anisotropyRotation;
  14042. this.anisotropyMap = source.anisotropyMap;
  14043. this.clearcoat = source.clearcoat;
  14044. this.clearcoatMap = source.clearcoatMap;
  14045. this.clearcoatRoughness = source.clearcoatRoughness;
  14046. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14047. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14048. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14049. this.dispersion = source.dispersion;
  14050. this.ior = source.ior;
  14051. this.iridescence = source.iridescence;
  14052. this.iridescenceMap = source.iridescenceMap;
  14053. this.iridescenceIOR = source.iridescenceIOR;
  14054. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14055. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14056. this.sheen = source.sheen;
  14057. this.sheenColor.copy( source.sheenColor );
  14058. this.sheenColorMap = source.sheenColorMap;
  14059. this.sheenRoughness = source.sheenRoughness;
  14060. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14061. this.transmission = source.transmission;
  14062. this.transmissionMap = source.transmissionMap;
  14063. this.thickness = source.thickness;
  14064. this.thicknessMap = source.thicknessMap;
  14065. this.attenuationDistance = source.attenuationDistance;
  14066. this.attenuationColor.copy( source.attenuationColor );
  14067. this.specularIntensity = source.specularIntensity;
  14068. this.specularIntensityMap = source.specularIntensityMap;
  14069. this.specularColor.copy( source.specularColor );
  14070. this.specularColorMap = source.specularColorMap;
  14071. return this;
  14072. }
  14073. }
  14074. class MeshPhongMaterial extends Material {
  14075. constructor( parameters ) {
  14076. super();
  14077. this.isMeshPhongMaterial = true;
  14078. this.type = 'MeshPhongMaterial';
  14079. this.color = new Color( 0xffffff ); // diffuse
  14080. this.specular = new Color( 0x111111 );
  14081. this.shininess = 30;
  14082. this.map = null;
  14083. this.lightMap = null;
  14084. this.lightMapIntensity = 1.0;
  14085. this.aoMap = null;
  14086. this.aoMapIntensity = 1.0;
  14087. this.emissive = new Color( 0x000000 );
  14088. this.emissiveIntensity = 1.0;
  14089. this.emissiveMap = null;
  14090. this.bumpMap = null;
  14091. this.bumpScale = 1;
  14092. this.normalMap = null;
  14093. this.normalMapType = TangentSpaceNormalMap;
  14094. this.normalScale = new Vector2( 1, 1 );
  14095. this.displacementMap = null;
  14096. this.displacementScale = 1;
  14097. this.displacementBias = 0;
  14098. this.specularMap = null;
  14099. this.alphaMap = null;
  14100. this.envMap = null;
  14101. this.envMapRotation = new Euler();
  14102. this.combine = MultiplyOperation;
  14103. this.reflectivity = 1;
  14104. this.refractionRatio = 0.98;
  14105. this.wireframe = false;
  14106. this.wireframeLinewidth = 1;
  14107. this.wireframeLinecap = 'round';
  14108. this.wireframeLinejoin = 'round';
  14109. this.flatShading = false;
  14110. this.fog = true;
  14111. this.setValues( parameters );
  14112. }
  14113. copy( source ) {
  14114. super.copy( source );
  14115. this.color.copy( source.color );
  14116. this.specular.copy( source.specular );
  14117. this.shininess = source.shininess;
  14118. this.map = source.map;
  14119. this.lightMap = source.lightMap;
  14120. this.lightMapIntensity = source.lightMapIntensity;
  14121. this.aoMap = source.aoMap;
  14122. this.aoMapIntensity = source.aoMapIntensity;
  14123. this.emissive.copy( source.emissive );
  14124. this.emissiveMap = source.emissiveMap;
  14125. this.emissiveIntensity = source.emissiveIntensity;
  14126. this.bumpMap = source.bumpMap;
  14127. this.bumpScale = source.bumpScale;
  14128. this.normalMap = source.normalMap;
  14129. this.normalMapType = source.normalMapType;
  14130. this.normalScale.copy( source.normalScale );
  14131. this.displacementMap = source.displacementMap;
  14132. this.displacementScale = source.displacementScale;
  14133. this.displacementBias = source.displacementBias;
  14134. this.specularMap = source.specularMap;
  14135. this.alphaMap = source.alphaMap;
  14136. this.envMap = source.envMap;
  14137. this.envMapRotation.copy( source.envMapRotation );
  14138. this.combine = source.combine;
  14139. this.reflectivity = source.reflectivity;
  14140. this.refractionRatio = source.refractionRatio;
  14141. this.wireframe = source.wireframe;
  14142. this.wireframeLinewidth = source.wireframeLinewidth;
  14143. this.wireframeLinecap = source.wireframeLinecap;
  14144. this.wireframeLinejoin = source.wireframeLinejoin;
  14145. this.flatShading = source.flatShading;
  14146. this.fog = source.fog;
  14147. return this;
  14148. }
  14149. }
  14150. class MeshToonMaterial extends Material {
  14151. constructor( parameters ) {
  14152. super();
  14153. this.isMeshToonMaterial = true;
  14154. this.defines = { 'TOON': '' };
  14155. this.type = 'MeshToonMaterial';
  14156. this.color = new Color( 0xffffff );
  14157. this.map = null;
  14158. this.gradientMap = null;
  14159. this.lightMap = null;
  14160. this.lightMapIntensity = 1.0;
  14161. this.aoMap = null;
  14162. this.aoMapIntensity = 1.0;
  14163. this.emissive = new Color( 0x000000 );
  14164. this.emissiveIntensity = 1.0;
  14165. this.emissiveMap = null;
  14166. this.bumpMap = null;
  14167. this.bumpScale = 1;
  14168. this.normalMap = null;
  14169. this.normalMapType = TangentSpaceNormalMap;
  14170. this.normalScale = new Vector2( 1, 1 );
  14171. this.displacementMap = null;
  14172. this.displacementScale = 1;
  14173. this.displacementBias = 0;
  14174. this.alphaMap = null;
  14175. this.wireframe = false;
  14176. this.wireframeLinewidth = 1;
  14177. this.wireframeLinecap = 'round';
  14178. this.wireframeLinejoin = 'round';
  14179. this.fog = true;
  14180. this.setValues( parameters );
  14181. }
  14182. copy( source ) {
  14183. super.copy( source );
  14184. this.color.copy( source.color );
  14185. this.map = source.map;
  14186. this.gradientMap = source.gradientMap;
  14187. this.lightMap = source.lightMap;
  14188. this.lightMapIntensity = source.lightMapIntensity;
  14189. this.aoMap = source.aoMap;
  14190. this.aoMapIntensity = source.aoMapIntensity;
  14191. this.emissive.copy( source.emissive );
  14192. this.emissiveMap = source.emissiveMap;
  14193. this.emissiveIntensity = source.emissiveIntensity;
  14194. this.bumpMap = source.bumpMap;
  14195. this.bumpScale = source.bumpScale;
  14196. this.normalMap = source.normalMap;
  14197. this.normalMapType = source.normalMapType;
  14198. this.normalScale.copy( source.normalScale );
  14199. this.displacementMap = source.displacementMap;
  14200. this.displacementScale = source.displacementScale;
  14201. this.displacementBias = source.displacementBias;
  14202. this.alphaMap = source.alphaMap;
  14203. this.wireframe = source.wireframe;
  14204. this.wireframeLinewidth = source.wireframeLinewidth;
  14205. this.wireframeLinecap = source.wireframeLinecap;
  14206. this.wireframeLinejoin = source.wireframeLinejoin;
  14207. this.fog = source.fog;
  14208. return this;
  14209. }
  14210. }
  14211. class MeshNormalMaterial extends Material {
  14212. constructor( parameters ) {
  14213. super();
  14214. this.isMeshNormalMaterial = true;
  14215. this.type = 'MeshNormalMaterial';
  14216. this.bumpMap = null;
  14217. this.bumpScale = 1;
  14218. this.normalMap = null;
  14219. this.normalMapType = TangentSpaceNormalMap;
  14220. this.normalScale = new Vector2( 1, 1 );
  14221. this.displacementMap = null;
  14222. this.displacementScale = 1;
  14223. this.displacementBias = 0;
  14224. this.wireframe = false;
  14225. this.wireframeLinewidth = 1;
  14226. this.flatShading = false;
  14227. this.setValues( parameters );
  14228. }
  14229. copy( source ) {
  14230. super.copy( source );
  14231. this.bumpMap = source.bumpMap;
  14232. this.bumpScale = source.bumpScale;
  14233. this.normalMap = source.normalMap;
  14234. this.normalMapType = source.normalMapType;
  14235. this.normalScale.copy( source.normalScale );
  14236. this.displacementMap = source.displacementMap;
  14237. this.displacementScale = source.displacementScale;
  14238. this.displacementBias = source.displacementBias;
  14239. this.wireframe = source.wireframe;
  14240. this.wireframeLinewidth = source.wireframeLinewidth;
  14241. this.flatShading = source.flatShading;
  14242. return this;
  14243. }
  14244. }
  14245. class MeshLambertMaterial extends Material {
  14246. constructor( parameters ) {
  14247. super();
  14248. this.isMeshLambertMaterial = true;
  14249. this.type = 'MeshLambertMaterial';
  14250. this.color = new Color( 0xffffff ); // diffuse
  14251. this.map = null;
  14252. this.lightMap = null;
  14253. this.lightMapIntensity = 1.0;
  14254. this.aoMap = null;
  14255. this.aoMapIntensity = 1.0;
  14256. this.emissive = new Color( 0x000000 );
  14257. this.emissiveIntensity = 1.0;
  14258. this.emissiveMap = null;
  14259. this.bumpMap = null;
  14260. this.bumpScale = 1;
  14261. this.normalMap = null;
  14262. this.normalMapType = TangentSpaceNormalMap;
  14263. this.normalScale = new Vector2( 1, 1 );
  14264. this.displacementMap = null;
  14265. this.displacementScale = 1;
  14266. this.displacementBias = 0;
  14267. this.specularMap = null;
  14268. this.alphaMap = null;
  14269. this.envMap = null;
  14270. this.envMapRotation = new Euler();
  14271. this.combine = MultiplyOperation;
  14272. this.reflectivity = 1;
  14273. this.refractionRatio = 0.98;
  14274. this.wireframe = false;
  14275. this.wireframeLinewidth = 1;
  14276. this.wireframeLinecap = 'round';
  14277. this.wireframeLinejoin = 'round';
  14278. this.flatShading = false;
  14279. this.fog = true;
  14280. this.setValues( parameters );
  14281. }
  14282. copy( source ) {
  14283. super.copy( source );
  14284. this.color.copy( source.color );
  14285. this.map = source.map;
  14286. this.lightMap = source.lightMap;
  14287. this.lightMapIntensity = source.lightMapIntensity;
  14288. this.aoMap = source.aoMap;
  14289. this.aoMapIntensity = source.aoMapIntensity;
  14290. this.emissive.copy( source.emissive );
  14291. this.emissiveMap = source.emissiveMap;
  14292. this.emissiveIntensity = source.emissiveIntensity;
  14293. this.bumpMap = source.bumpMap;
  14294. this.bumpScale = source.bumpScale;
  14295. this.normalMap = source.normalMap;
  14296. this.normalMapType = source.normalMapType;
  14297. this.normalScale.copy( source.normalScale );
  14298. this.displacementMap = source.displacementMap;
  14299. this.displacementScale = source.displacementScale;
  14300. this.displacementBias = source.displacementBias;
  14301. this.specularMap = source.specularMap;
  14302. this.alphaMap = source.alphaMap;
  14303. this.envMap = source.envMap;
  14304. this.envMapRotation.copy( source.envMapRotation );
  14305. this.combine = source.combine;
  14306. this.reflectivity = source.reflectivity;
  14307. this.refractionRatio = source.refractionRatio;
  14308. this.wireframe = source.wireframe;
  14309. this.wireframeLinewidth = source.wireframeLinewidth;
  14310. this.wireframeLinecap = source.wireframeLinecap;
  14311. this.wireframeLinejoin = source.wireframeLinejoin;
  14312. this.flatShading = source.flatShading;
  14313. this.fog = source.fog;
  14314. return this;
  14315. }
  14316. }
  14317. class MeshDepthMaterial extends Material {
  14318. constructor( parameters ) {
  14319. super();
  14320. this.isMeshDepthMaterial = true;
  14321. this.type = 'MeshDepthMaterial';
  14322. this.depthPacking = BasicDepthPacking;
  14323. this.map = null;
  14324. this.alphaMap = null;
  14325. this.displacementMap = null;
  14326. this.displacementScale = 1;
  14327. this.displacementBias = 0;
  14328. this.wireframe = false;
  14329. this.wireframeLinewidth = 1;
  14330. this.setValues( parameters );
  14331. }
  14332. copy( source ) {
  14333. super.copy( source );
  14334. this.depthPacking = source.depthPacking;
  14335. this.map = source.map;
  14336. this.alphaMap = source.alphaMap;
  14337. this.displacementMap = source.displacementMap;
  14338. this.displacementScale = source.displacementScale;
  14339. this.displacementBias = source.displacementBias;
  14340. this.wireframe = source.wireframe;
  14341. this.wireframeLinewidth = source.wireframeLinewidth;
  14342. return this;
  14343. }
  14344. }
  14345. class MeshDistanceMaterial extends Material {
  14346. constructor( parameters ) {
  14347. super();
  14348. this.isMeshDistanceMaterial = true;
  14349. this.type = 'MeshDistanceMaterial';
  14350. this.map = null;
  14351. this.alphaMap = null;
  14352. this.displacementMap = null;
  14353. this.displacementScale = 1;
  14354. this.displacementBias = 0;
  14355. this.setValues( parameters );
  14356. }
  14357. copy( source ) {
  14358. super.copy( source );
  14359. this.map = source.map;
  14360. this.alphaMap = source.alphaMap;
  14361. this.displacementMap = source.displacementMap;
  14362. this.displacementScale = source.displacementScale;
  14363. this.displacementBias = source.displacementBias;
  14364. return this;
  14365. }
  14366. }
  14367. class MeshMatcapMaterial extends Material {
  14368. constructor( parameters ) {
  14369. super();
  14370. this.isMeshMatcapMaterial = true;
  14371. this.defines = { 'MATCAP': '' };
  14372. this.type = 'MeshMatcapMaterial';
  14373. this.color = new Color( 0xffffff ); // diffuse
  14374. this.matcap = null;
  14375. this.map = null;
  14376. this.bumpMap = null;
  14377. this.bumpScale = 1;
  14378. this.normalMap = null;
  14379. this.normalMapType = TangentSpaceNormalMap;
  14380. this.normalScale = new Vector2( 1, 1 );
  14381. this.displacementMap = null;
  14382. this.displacementScale = 1;
  14383. this.displacementBias = 0;
  14384. this.alphaMap = null;
  14385. this.flatShading = false;
  14386. this.fog = true;
  14387. this.setValues( parameters );
  14388. }
  14389. copy( source ) {
  14390. super.copy( source );
  14391. this.defines = { 'MATCAP': '' };
  14392. this.color.copy( source.color );
  14393. this.matcap = source.matcap;
  14394. this.map = source.map;
  14395. this.bumpMap = source.bumpMap;
  14396. this.bumpScale = source.bumpScale;
  14397. this.normalMap = source.normalMap;
  14398. this.normalMapType = source.normalMapType;
  14399. this.normalScale.copy( source.normalScale );
  14400. this.displacementMap = source.displacementMap;
  14401. this.displacementScale = source.displacementScale;
  14402. this.displacementBias = source.displacementBias;
  14403. this.alphaMap = source.alphaMap;
  14404. this.flatShading = source.flatShading;
  14405. this.fog = source.fog;
  14406. return this;
  14407. }
  14408. }
  14409. class LineDashedMaterial extends LineBasicMaterial {
  14410. constructor( parameters ) {
  14411. super();
  14412. this.isLineDashedMaterial = true;
  14413. this.type = 'LineDashedMaterial';
  14414. this.scale = 1;
  14415. this.dashSize = 3;
  14416. this.gapSize = 1;
  14417. this.setValues( parameters );
  14418. }
  14419. copy( source ) {
  14420. super.copy( source );
  14421. this.scale = source.scale;
  14422. this.dashSize = source.dashSize;
  14423. this.gapSize = source.gapSize;
  14424. return this;
  14425. }
  14426. }
  14427. // converts an array to a specific type
  14428. function convertArray( array, type, forceClone ) {
  14429. if ( ! array || // let 'undefined' and 'null' pass
  14430. ! forceClone && array.constructor === type ) return array;
  14431. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14432. return new type( array ); // create typed array
  14433. }
  14434. return Array.prototype.slice.call( array ); // create Array
  14435. }
  14436. function isTypedArray( object ) {
  14437. return ArrayBuffer.isView( object ) &&
  14438. ! ( object instanceof DataView );
  14439. }
  14440. // returns an array by which times and values can be sorted
  14441. function getKeyframeOrder( times ) {
  14442. function compareTime( i, j ) {
  14443. return times[ i ] - times[ j ];
  14444. }
  14445. const n = times.length;
  14446. const result = new Array( n );
  14447. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14448. result.sort( compareTime );
  14449. return result;
  14450. }
  14451. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14452. function sortedArray( values, stride, order ) {
  14453. const nValues = values.length;
  14454. const result = new values.constructor( nValues );
  14455. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14456. const srcOffset = order[ i ] * stride;
  14457. for ( let j = 0; j !== stride; ++ j ) {
  14458. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14459. }
  14460. }
  14461. return result;
  14462. }
  14463. // function for parsing AOS keyframe formats
  14464. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14465. let i = 1, key = jsonKeys[ 0 ];
  14466. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14467. key = jsonKeys[ i ++ ];
  14468. }
  14469. if ( key === undefined ) return; // no data
  14470. let value = key[ valuePropertyName ];
  14471. if ( value === undefined ) return; // no data
  14472. if ( Array.isArray( value ) ) {
  14473. do {
  14474. value = key[ valuePropertyName ];
  14475. if ( value !== undefined ) {
  14476. times.push( key.time );
  14477. values.push.apply( values, value ); // push all elements
  14478. }
  14479. key = jsonKeys[ i ++ ];
  14480. } while ( key !== undefined );
  14481. } else if ( value.toArray !== undefined ) {
  14482. // ...assume THREE.Math-ish
  14483. do {
  14484. value = key[ valuePropertyName ];
  14485. if ( value !== undefined ) {
  14486. times.push( key.time );
  14487. value.toArray( values, values.length );
  14488. }
  14489. key = jsonKeys[ i ++ ];
  14490. } while ( key !== undefined );
  14491. } else {
  14492. // otherwise push as-is
  14493. do {
  14494. value = key[ valuePropertyName ];
  14495. if ( value !== undefined ) {
  14496. times.push( key.time );
  14497. values.push( value );
  14498. }
  14499. key = jsonKeys[ i ++ ];
  14500. } while ( key !== undefined );
  14501. }
  14502. }
  14503. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14504. const clip = sourceClip.clone();
  14505. clip.name = name;
  14506. const tracks = [];
  14507. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14508. const track = clip.tracks[ i ];
  14509. const valueSize = track.getValueSize();
  14510. const times = [];
  14511. const values = [];
  14512. for ( let j = 0; j < track.times.length; ++ j ) {
  14513. const frame = track.times[ j ] * fps;
  14514. if ( frame < startFrame || frame >= endFrame ) continue;
  14515. times.push( track.times[ j ] );
  14516. for ( let k = 0; k < valueSize; ++ k ) {
  14517. values.push( track.values[ j * valueSize + k ] );
  14518. }
  14519. }
  14520. if ( times.length === 0 ) continue;
  14521. track.times = convertArray( times, track.times.constructor );
  14522. track.values = convertArray( values, track.values.constructor );
  14523. tracks.push( track );
  14524. }
  14525. clip.tracks = tracks;
  14526. // find minimum .times value across all tracks in the trimmed clip
  14527. let minStartTime = Infinity;
  14528. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14529. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14530. minStartTime = clip.tracks[ i ].times[ 0 ];
  14531. }
  14532. }
  14533. // shift all tracks such that clip begins at t=0
  14534. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14535. clip.tracks[ i ].shift( - 1 * minStartTime );
  14536. }
  14537. clip.resetDuration();
  14538. return clip;
  14539. }
  14540. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14541. if ( fps <= 0 ) fps = 30;
  14542. const numTracks = referenceClip.tracks.length;
  14543. const referenceTime = referenceFrame / fps;
  14544. // Make each track's values relative to the values at the reference frame
  14545. for ( let i = 0; i < numTracks; ++ i ) {
  14546. const referenceTrack = referenceClip.tracks[ i ];
  14547. const referenceTrackType = referenceTrack.ValueTypeName;
  14548. // Skip this track if it's non-numeric
  14549. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14550. // Find the track in the target clip whose name and type matches the reference track
  14551. const targetTrack = targetClip.tracks.find( function ( track ) {
  14552. return track.name === referenceTrack.name
  14553. && track.ValueTypeName === referenceTrackType;
  14554. } );
  14555. if ( targetTrack === undefined ) continue;
  14556. let referenceOffset = 0;
  14557. const referenceValueSize = referenceTrack.getValueSize();
  14558. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14559. referenceOffset = referenceValueSize / 3;
  14560. }
  14561. let targetOffset = 0;
  14562. const targetValueSize = targetTrack.getValueSize();
  14563. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14564. targetOffset = targetValueSize / 3;
  14565. }
  14566. const lastIndex = referenceTrack.times.length - 1;
  14567. let referenceValue;
  14568. // Find the value to subtract out of the track
  14569. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14570. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14571. const startIndex = referenceOffset;
  14572. const endIndex = referenceValueSize - referenceOffset;
  14573. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14574. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14575. // Reference frame is after the last keyframe, so just use the last keyframe
  14576. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14577. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14578. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14579. } else {
  14580. // Interpolate to the reference value
  14581. const interpolant = referenceTrack.createInterpolant();
  14582. const startIndex = referenceOffset;
  14583. const endIndex = referenceValueSize - referenceOffset;
  14584. interpolant.evaluate( referenceTime );
  14585. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14586. }
  14587. // Conjugate the quaternion
  14588. if ( referenceTrackType === 'quaternion' ) {
  14589. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14590. referenceQuat.toArray( referenceValue );
  14591. }
  14592. // Subtract the reference value from all of the track values
  14593. const numTimes = targetTrack.times.length;
  14594. for ( let j = 0; j < numTimes; ++ j ) {
  14595. const valueStart = j * targetValueSize + targetOffset;
  14596. if ( referenceTrackType === 'quaternion' ) {
  14597. // Multiply the conjugate for quaternion track types
  14598. Quaternion.multiplyQuaternionsFlat(
  14599. targetTrack.values,
  14600. valueStart,
  14601. referenceValue,
  14602. 0,
  14603. targetTrack.values,
  14604. valueStart
  14605. );
  14606. } else {
  14607. const valueEnd = targetValueSize - targetOffset * 2;
  14608. // Subtract each value for all other numeric track types
  14609. for ( let k = 0; k < valueEnd; ++ k ) {
  14610. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14611. }
  14612. }
  14613. }
  14614. }
  14615. targetClip.blendMode = AdditiveAnimationBlendMode;
  14616. return targetClip;
  14617. }
  14618. const AnimationUtils = {
  14619. convertArray: convertArray,
  14620. isTypedArray: isTypedArray,
  14621. getKeyframeOrder: getKeyframeOrder,
  14622. sortedArray: sortedArray,
  14623. flattenJSON: flattenJSON,
  14624. subclip: subclip,
  14625. makeClipAdditive: makeClipAdditive
  14626. };
  14627. /**
  14628. * Abstract base class of interpolants over parametric samples.
  14629. *
  14630. * The parameter domain is one dimensional, typically the time or a path
  14631. * along a curve defined by the data.
  14632. *
  14633. * The sample values can have any dimensionality and derived classes may
  14634. * apply special interpretations to the data.
  14635. *
  14636. * This class provides the interval seek in a Template Method, deferring
  14637. * the actual interpolation to derived classes.
  14638. *
  14639. * Time complexity is O(1) for linear access crossing at most two points
  14640. * and O(log N) for random access, where N is the number of positions.
  14641. *
  14642. * References:
  14643. *
  14644. * http://www.oodesign.com/template-method-pattern.html
  14645. *
  14646. */
  14647. class Interpolant {
  14648. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14649. this.parameterPositions = parameterPositions;
  14650. this._cachedIndex = 0;
  14651. this.resultBuffer = resultBuffer !== undefined ?
  14652. resultBuffer : new sampleValues.constructor( sampleSize );
  14653. this.sampleValues = sampleValues;
  14654. this.valueSize = sampleSize;
  14655. this.settings = null;
  14656. this.DefaultSettings_ = {};
  14657. }
  14658. evaluate( t ) {
  14659. const pp = this.parameterPositions;
  14660. let i1 = this._cachedIndex,
  14661. t1 = pp[ i1 ],
  14662. t0 = pp[ i1 - 1 ];
  14663. validate_interval: {
  14664. seek: {
  14665. let right;
  14666. linear_scan: {
  14667. //- See http://jsperf.com/comparison-to-undefined/3
  14668. //- slower code:
  14669. //-
  14670. //- if ( t >= t1 || t1 === undefined ) {
  14671. forward_scan: if ( ! ( t < t1 ) ) {
  14672. for ( let giveUpAt = i1 + 2; ; ) {
  14673. if ( t1 === undefined ) {
  14674. if ( t < t0 ) break forward_scan;
  14675. // after end
  14676. i1 = pp.length;
  14677. this._cachedIndex = i1;
  14678. return this.copySampleValue_( i1 - 1 );
  14679. }
  14680. if ( i1 === giveUpAt ) break; // this loop
  14681. t0 = t1;
  14682. t1 = pp[ ++ i1 ];
  14683. if ( t < t1 ) {
  14684. // we have arrived at the sought interval
  14685. break seek;
  14686. }
  14687. }
  14688. // prepare binary search on the right side of the index
  14689. right = pp.length;
  14690. break linear_scan;
  14691. }
  14692. //- slower code:
  14693. //- if ( t < t0 || t0 === undefined ) {
  14694. if ( ! ( t >= t0 ) ) {
  14695. // looping?
  14696. const t1global = pp[ 1 ];
  14697. if ( t < t1global ) {
  14698. i1 = 2; // + 1, using the scan for the details
  14699. t0 = t1global;
  14700. }
  14701. // linear reverse scan
  14702. for ( let giveUpAt = i1 - 2; ; ) {
  14703. if ( t0 === undefined ) {
  14704. // before start
  14705. this._cachedIndex = 0;
  14706. return this.copySampleValue_( 0 );
  14707. }
  14708. if ( i1 === giveUpAt ) break; // this loop
  14709. t1 = t0;
  14710. t0 = pp[ -- i1 - 1 ];
  14711. if ( t >= t0 ) {
  14712. // we have arrived at the sought interval
  14713. break seek;
  14714. }
  14715. }
  14716. // prepare binary search on the left side of the index
  14717. right = i1;
  14718. i1 = 0;
  14719. break linear_scan;
  14720. }
  14721. // the interval is valid
  14722. break validate_interval;
  14723. } // linear scan
  14724. // binary search
  14725. while ( i1 < right ) {
  14726. const mid = ( i1 + right ) >>> 1;
  14727. if ( t < pp[ mid ] ) {
  14728. right = mid;
  14729. } else {
  14730. i1 = mid + 1;
  14731. }
  14732. }
  14733. t1 = pp[ i1 ];
  14734. t0 = pp[ i1 - 1 ];
  14735. // check boundary cases, again
  14736. if ( t0 === undefined ) {
  14737. this._cachedIndex = 0;
  14738. return this.copySampleValue_( 0 );
  14739. }
  14740. if ( t1 === undefined ) {
  14741. i1 = pp.length;
  14742. this._cachedIndex = i1;
  14743. return this.copySampleValue_( i1 - 1 );
  14744. }
  14745. } // seek
  14746. this._cachedIndex = i1;
  14747. this.intervalChanged_( i1, t0, t1 );
  14748. } // validate_interval
  14749. return this.interpolate_( i1, t0, t, t1 );
  14750. }
  14751. getSettings_() {
  14752. return this.settings || this.DefaultSettings_;
  14753. }
  14754. copySampleValue_( index ) {
  14755. // copies a sample value to the result buffer
  14756. const result = this.resultBuffer,
  14757. values = this.sampleValues,
  14758. stride = this.valueSize,
  14759. offset = index * stride;
  14760. for ( let i = 0; i !== stride; ++ i ) {
  14761. result[ i ] = values[ offset + i ];
  14762. }
  14763. return result;
  14764. }
  14765. // Template methods for derived classes:
  14766. interpolate_( /* i1, t0, t, t1 */ ) {
  14767. throw new Error( 'call to abstract method' );
  14768. // implementations shall return this.resultBuffer
  14769. }
  14770. intervalChanged_( /* i1, t0, t1 */ ) {
  14771. // empty
  14772. }
  14773. }
  14774. /**
  14775. * Fast and simple cubic spline interpolant.
  14776. *
  14777. * It was derived from a Hermitian construction setting the first derivative
  14778. * at each sample position to the linear slope between neighboring positions
  14779. * over their parameter interval.
  14780. */
  14781. class CubicInterpolant extends Interpolant {
  14782. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14783. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14784. this._weightPrev = - 0;
  14785. this._offsetPrev = - 0;
  14786. this._weightNext = - 0;
  14787. this._offsetNext = - 0;
  14788. this.DefaultSettings_ = {
  14789. endingStart: ZeroCurvatureEnding,
  14790. endingEnd: ZeroCurvatureEnding
  14791. };
  14792. }
  14793. intervalChanged_( i1, t0, t1 ) {
  14794. const pp = this.parameterPositions;
  14795. let iPrev = i1 - 2,
  14796. iNext = i1 + 1,
  14797. tPrev = pp[ iPrev ],
  14798. tNext = pp[ iNext ];
  14799. if ( tPrev === undefined ) {
  14800. switch ( this.getSettings_().endingStart ) {
  14801. case ZeroSlopeEnding:
  14802. // f'(t0) = 0
  14803. iPrev = i1;
  14804. tPrev = 2 * t0 - t1;
  14805. break;
  14806. case WrapAroundEnding:
  14807. // use the other end of the curve
  14808. iPrev = pp.length - 2;
  14809. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  14810. break;
  14811. default: // ZeroCurvatureEnding
  14812. // f''(t0) = 0 a.k.a. Natural Spline
  14813. iPrev = i1;
  14814. tPrev = t1;
  14815. }
  14816. }
  14817. if ( tNext === undefined ) {
  14818. switch ( this.getSettings_().endingEnd ) {
  14819. case ZeroSlopeEnding:
  14820. // f'(tN) = 0
  14821. iNext = i1;
  14822. tNext = 2 * t1 - t0;
  14823. break;
  14824. case WrapAroundEnding:
  14825. // use the other end of the curve
  14826. iNext = 1;
  14827. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  14828. break;
  14829. default: // ZeroCurvatureEnding
  14830. // f''(tN) = 0, a.k.a. Natural Spline
  14831. iNext = i1 - 1;
  14832. tNext = t0;
  14833. }
  14834. }
  14835. const halfDt = ( t1 - t0 ) * 0.5,
  14836. stride = this.valueSize;
  14837. this._weightPrev = halfDt / ( t0 - tPrev );
  14838. this._weightNext = halfDt / ( tNext - t1 );
  14839. this._offsetPrev = iPrev * stride;
  14840. this._offsetNext = iNext * stride;
  14841. }
  14842. interpolate_( i1, t0, t, t1 ) {
  14843. const result = this.resultBuffer,
  14844. values = this.sampleValues,
  14845. stride = this.valueSize,
  14846. o1 = i1 * stride, o0 = o1 - stride,
  14847. oP = this._offsetPrev, oN = this._offsetNext,
  14848. wP = this._weightPrev, wN = this._weightNext,
  14849. p = ( t - t0 ) / ( t1 - t0 ),
  14850. pp = p * p,
  14851. ppp = pp * p;
  14852. // evaluate polynomials
  14853. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  14854. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  14855. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  14856. const sN = wN * ppp - wN * pp;
  14857. // combine data linearly
  14858. for ( let i = 0; i !== stride; ++ i ) {
  14859. result[ i ] =
  14860. sP * values[ oP + i ] +
  14861. s0 * values[ o0 + i ] +
  14862. s1 * values[ o1 + i ] +
  14863. sN * values[ oN + i ];
  14864. }
  14865. return result;
  14866. }
  14867. }
  14868. class LinearInterpolant extends Interpolant {
  14869. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14870. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14871. }
  14872. interpolate_( i1, t0, t, t1 ) {
  14873. const result = this.resultBuffer,
  14874. values = this.sampleValues,
  14875. stride = this.valueSize,
  14876. offset1 = i1 * stride,
  14877. offset0 = offset1 - stride,
  14878. weight1 = ( t - t0 ) / ( t1 - t0 ),
  14879. weight0 = 1 - weight1;
  14880. for ( let i = 0; i !== stride; ++ i ) {
  14881. result[ i ] =
  14882. values[ offset0 + i ] * weight0 +
  14883. values[ offset1 + i ] * weight1;
  14884. }
  14885. return result;
  14886. }
  14887. }
  14888. /**
  14889. *
  14890. * Interpolant that evaluates to the sample value at the position preceding
  14891. * the parameter.
  14892. */
  14893. class DiscreteInterpolant extends Interpolant {
  14894. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14895. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14896. }
  14897. interpolate_( i1 /*, t0, t, t1 */ ) {
  14898. return this.copySampleValue_( i1 - 1 );
  14899. }
  14900. }
  14901. class KeyframeTrack {
  14902. constructor( name, times, values, interpolation ) {
  14903. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  14904. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  14905. this.name = name;
  14906. this.times = convertArray( times, this.TimeBufferType );
  14907. this.values = convertArray( values, this.ValueBufferType );
  14908. this.setInterpolation( interpolation || this.DefaultInterpolation );
  14909. }
  14910. // Serialization (in static context, because of constructor invocation
  14911. // and automatic invocation of .toJSON):
  14912. static toJSON( track ) {
  14913. const trackType = track.constructor;
  14914. let json;
  14915. // derived classes can define a static toJSON method
  14916. if ( trackType.toJSON !== this.toJSON ) {
  14917. json = trackType.toJSON( track );
  14918. } else {
  14919. // by default, we assume the data can be serialized as-is
  14920. json = {
  14921. 'name': track.name,
  14922. 'times': convertArray( track.times, Array ),
  14923. 'values': convertArray( track.values, Array )
  14924. };
  14925. const interpolation = track.getInterpolation();
  14926. if ( interpolation !== track.DefaultInterpolation ) {
  14927. json.interpolation = interpolation;
  14928. }
  14929. }
  14930. json.type = track.ValueTypeName; // mandatory
  14931. return json;
  14932. }
  14933. InterpolantFactoryMethodDiscrete( result ) {
  14934. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  14935. }
  14936. InterpolantFactoryMethodLinear( result ) {
  14937. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  14938. }
  14939. InterpolantFactoryMethodSmooth( result ) {
  14940. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  14941. }
  14942. setInterpolation( interpolation ) {
  14943. let factoryMethod;
  14944. switch ( interpolation ) {
  14945. case InterpolateDiscrete:
  14946. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  14947. break;
  14948. case InterpolateLinear:
  14949. factoryMethod = this.InterpolantFactoryMethodLinear;
  14950. break;
  14951. case InterpolateSmooth:
  14952. factoryMethod = this.InterpolantFactoryMethodSmooth;
  14953. break;
  14954. }
  14955. if ( factoryMethod === undefined ) {
  14956. const message = 'unsupported interpolation for ' +
  14957. this.ValueTypeName + ' keyframe track named ' + this.name;
  14958. if ( this.createInterpolant === undefined ) {
  14959. // fall back to default, unless the default itself is messed up
  14960. if ( interpolation !== this.DefaultInterpolation ) {
  14961. this.setInterpolation( this.DefaultInterpolation );
  14962. } else {
  14963. throw new Error( message ); // fatal, in this case
  14964. }
  14965. }
  14966. console.warn( 'THREE.KeyframeTrack:', message );
  14967. return this;
  14968. }
  14969. this.createInterpolant = factoryMethod;
  14970. return this;
  14971. }
  14972. getInterpolation() {
  14973. switch ( this.createInterpolant ) {
  14974. case this.InterpolantFactoryMethodDiscrete:
  14975. return InterpolateDiscrete;
  14976. case this.InterpolantFactoryMethodLinear:
  14977. return InterpolateLinear;
  14978. case this.InterpolantFactoryMethodSmooth:
  14979. return InterpolateSmooth;
  14980. }
  14981. }
  14982. getValueSize() {
  14983. return this.values.length / this.times.length;
  14984. }
  14985. // move all keyframes either forwards or backwards in time
  14986. shift( timeOffset ) {
  14987. if ( timeOffset !== 0.0 ) {
  14988. const times = this.times;
  14989. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  14990. times[ i ] += timeOffset;
  14991. }
  14992. }
  14993. return this;
  14994. }
  14995. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  14996. scale( timeScale ) {
  14997. if ( timeScale !== 1.0 ) {
  14998. const times = this.times;
  14999. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15000. times[ i ] *= timeScale;
  15001. }
  15002. }
  15003. return this;
  15004. }
  15005. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  15006. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  15007. trim( startTime, endTime ) {
  15008. const times = this.times,
  15009. nKeys = times.length;
  15010. let from = 0,
  15011. to = nKeys - 1;
  15012. while ( from !== nKeys && times[ from ] < startTime ) {
  15013. ++ from;
  15014. }
  15015. while ( to !== - 1 && times[ to ] > endTime ) {
  15016. -- to;
  15017. }
  15018. ++ to; // inclusive -> exclusive bound
  15019. if ( from !== 0 || to !== nKeys ) {
  15020. // empty tracks are forbidden, so keep at least one keyframe
  15021. if ( from >= to ) {
  15022. to = Math.max( to, 1 );
  15023. from = to - 1;
  15024. }
  15025. const stride = this.getValueSize();
  15026. this.times = times.slice( from, to );
  15027. this.values = this.values.slice( from * stride, to * stride );
  15028. }
  15029. return this;
  15030. }
  15031. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  15032. validate() {
  15033. let valid = true;
  15034. const valueSize = this.getValueSize();
  15035. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  15036. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  15037. valid = false;
  15038. }
  15039. const times = this.times,
  15040. values = this.values,
  15041. nKeys = times.length;
  15042. if ( nKeys === 0 ) {
  15043. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  15044. valid = false;
  15045. }
  15046. let prevTime = null;
  15047. for ( let i = 0; i !== nKeys; i ++ ) {
  15048. const currTime = times[ i ];
  15049. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15050. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15051. valid = false;
  15052. break;
  15053. }
  15054. if ( prevTime !== null && prevTime > currTime ) {
  15055. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15056. valid = false;
  15057. break;
  15058. }
  15059. prevTime = currTime;
  15060. }
  15061. if ( values !== undefined ) {
  15062. if ( isTypedArray( values ) ) {
  15063. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15064. const value = values[ i ];
  15065. if ( isNaN( value ) ) {
  15066. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15067. valid = false;
  15068. break;
  15069. }
  15070. }
  15071. }
  15072. }
  15073. return valid;
  15074. }
  15075. // removes equivalent sequential keys as common in morph target sequences
  15076. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15077. optimize() {
  15078. // times or values may be shared with other tracks, so overwriting is unsafe
  15079. const times = this.times.slice(),
  15080. values = this.values.slice(),
  15081. stride = this.getValueSize(),
  15082. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15083. lastIndex = times.length - 1;
  15084. let writeIndex = 1;
  15085. for ( let i = 1; i < lastIndex; ++ i ) {
  15086. let keep = false;
  15087. const time = times[ i ];
  15088. const timeNext = times[ i + 1 ];
  15089. // remove adjacent keyframes scheduled at the same time
  15090. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15091. if ( ! smoothInterpolation ) {
  15092. // remove unnecessary keyframes same as their neighbors
  15093. const offset = i * stride,
  15094. offsetP = offset - stride,
  15095. offsetN = offset + stride;
  15096. for ( let j = 0; j !== stride; ++ j ) {
  15097. const value = values[ offset + j ];
  15098. if ( value !== values[ offsetP + j ] ||
  15099. value !== values[ offsetN + j ] ) {
  15100. keep = true;
  15101. break;
  15102. }
  15103. }
  15104. } else {
  15105. keep = true;
  15106. }
  15107. }
  15108. // in-place compaction
  15109. if ( keep ) {
  15110. if ( i !== writeIndex ) {
  15111. times[ writeIndex ] = times[ i ];
  15112. const readOffset = i * stride,
  15113. writeOffset = writeIndex * stride;
  15114. for ( let j = 0; j !== stride; ++ j ) {
  15115. values[ writeOffset + j ] = values[ readOffset + j ];
  15116. }
  15117. }
  15118. ++ writeIndex;
  15119. }
  15120. }
  15121. // flush last keyframe (compaction looks ahead)
  15122. if ( lastIndex > 0 ) {
  15123. times[ writeIndex ] = times[ lastIndex ];
  15124. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15125. values[ writeOffset + j ] = values[ readOffset + j ];
  15126. }
  15127. ++ writeIndex;
  15128. }
  15129. if ( writeIndex !== times.length ) {
  15130. this.times = times.slice( 0, writeIndex );
  15131. this.values = values.slice( 0, writeIndex * stride );
  15132. } else {
  15133. this.times = times;
  15134. this.values = values;
  15135. }
  15136. return this;
  15137. }
  15138. clone() {
  15139. const times = this.times.slice();
  15140. const values = this.values.slice();
  15141. const TypedKeyframeTrack = this.constructor;
  15142. const track = new TypedKeyframeTrack( this.name, times, values );
  15143. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15144. track.createInterpolant = this.createInterpolant;
  15145. return track;
  15146. }
  15147. }
  15148. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15149. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15150. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15151. /**
  15152. * A Track of Boolean keyframe values.
  15153. */
  15154. class BooleanKeyframeTrack extends KeyframeTrack {
  15155. // No interpolation parameter because only InterpolateDiscrete is valid.
  15156. constructor( name, times, values ) {
  15157. super( name, times, values );
  15158. }
  15159. }
  15160. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15161. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15162. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15163. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15164. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15165. /**
  15166. * A Track of keyframe values that represent color.
  15167. */
  15168. class ColorKeyframeTrack extends KeyframeTrack {}
  15169. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15170. /**
  15171. * A Track of numeric keyframe values.
  15172. */
  15173. class NumberKeyframeTrack extends KeyframeTrack {}
  15174. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15175. /**
  15176. * Spherical linear unit quaternion interpolant.
  15177. */
  15178. class QuaternionLinearInterpolant extends Interpolant {
  15179. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15180. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15181. }
  15182. interpolate_( i1, t0, t, t1 ) {
  15183. const result = this.resultBuffer,
  15184. values = this.sampleValues,
  15185. stride = this.valueSize,
  15186. alpha = ( t - t0 ) / ( t1 - t0 );
  15187. let offset = i1 * stride;
  15188. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15189. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15190. }
  15191. return result;
  15192. }
  15193. }
  15194. /**
  15195. * A Track of quaternion keyframe values.
  15196. */
  15197. class QuaternionKeyframeTrack extends KeyframeTrack {
  15198. InterpolantFactoryMethodLinear( result ) {
  15199. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15200. }
  15201. }
  15202. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15203. // ValueBufferType is inherited
  15204. // DefaultInterpolation is inherited;
  15205. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15206. /**
  15207. * A Track that interpolates Strings
  15208. */
  15209. class StringKeyframeTrack extends KeyframeTrack {
  15210. // No interpolation parameter because only InterpolateDiscrete is valid.
  15211. constructor( name, times, values ) {
  15212. super( name, times, values );
  15213. }
  15214. }
  15215. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15216. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15217. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15218. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15219. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15220. /**
  15221. * A Track of vectored keyframe values.
  15222. */
  15223. class VectorKeyframeTrack extends KeyframeTrack {}
  15224. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15225. class AnimationClip {
  15226. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15227. this.name = name;
  15228. this.tracks = tracks;
  15229. this.duration = duration;
  15230. this.blendMode = blendMode;
  15231. this.uuid = generateUUID();
  15232. // this means it should figure out its duration by scanning the tracks
  15233. if ( this.duration < 0 ) {
  15234. this.resetDuration();
  15235. }
  15236. }
  15237. static parse( json ) {
  15238. const tracks = [],
  15239. jsonTracks = json.tracks,
  15240. frameTime = 1.0 / ( json.fps || 1.0 );
  15241. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15242. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15243. }
  15244. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15245. clip.uuid = json.uuid;
  15246. return clip;
  15247. }
  15248. static toJSON( clip ) {
  15249. const tracks = [],
  15250. clipTracks = clip.tracks;
  15251. const json = {
  15252. 'name': clip.name,
  15253. 'duration': clip.duration,
  15254. 'tracks': tracks,
  15255. 'uuid': clip.uuid,
  15256. 'blendMode': clip.blendMode
  15257. };
  15258. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15259. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15260. }
  15261. return json;
  15262. }
  15263. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15264. const numMorphTargets = morphTargetSequence.length;
  15265. const tracks = [];
  15266. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15267. let times = [];
  15268. let values = [];
  15269. times.push(
  15270. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15271. i,
  15272. ( i + 1 ) % numMorphTargets );
  15273. values.push( 0, 1, 0 );
  15274. const order = getKeyframeOrder( times );
  15275. times = sortedArray( times, 1, order );
  15276. values = sortedArray( values, 1, order );
  15277. // if there is a key at the first frame, duplicate it as the
  15278. // last frame as well for perfect loop.
  15279. if ( ! noLoop && times[ 0 ] === 0 ) {
  15280. times.push( numMorphTargets );
  15281. values.push( values[ 0 ] );
  15282. }
  15283. tracks.push(
  15284. new NumberKeyframeTrack(
  15285. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15286. times, values
  15287. ).scale( 1.0 / fps ) );
  15288. }
  15289. return new this( name, - 1, tracks );
  15290. }
  15291. static findByName( objectOrClipArray, name ) {
  15292. let clipArray = objectOrClipArray;
  15293. if ( ! Array.isArray( objectOrClipArray ) ) {
  15294. const o = objectOrClipArray;
  15295. clipArray = o.geometry && o.geometry.animations || o.animations;
  15296. }
  15297. for ( let i = 0; i < clipArray.length; i ++ ) {
  15298. if ( clipArray[ i ].name === name ) {
  15299. return clipArray[ i ];
  15300. }
  15301. }
  15302. return null;
  15303. }
  15304. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15305. const animationToMorphTargets = {};
  15306. // tested with https://regex101.com/ on trick sequences
  15307. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15308. const pattern = /^([\w-]*?)([\d]+)$/;
  15309. // sort morph target names into animation groups based
  15310. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15311. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15312. const morphTarget = morphTargets[ i ];
  15313. const parts = morphTarget.name.match( pattern );
  15314. if ( parts && parts.length > 1 ) {
  15315. const name = parts[ 1 ];
  15316. let animationMorphTargets = animationToMorphTargets[ name ];
  15317. if ( ! animationMorphTargets ) {
  15318. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15319. }
  15320. animationMorphTargets.push( morphTarget );
  15321. }
  15322. }
  15323. const clips = [];
  15324. for ( const name in animationToMorphTargets ) {
  15325. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15326. }
  15327. return clips;
  15328. }
  15329. // parse the animation.hierarchy format
  15330. static parseAnimation( animation, bones ) {
  15331. if ( ! animation ) {
  15332. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15333. return null;
  15334. }
  15335. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15336. // only return track if there are actually keys.
  15337. if ( animationKeys.length !== 0 ) {
  15338. const times = [];
  15339. const values = [];
  15340. flattenJSON( animationKeys, times, values, propertyName );
  15341. // empty keys are filtered out, so check again
  15342. if ( times.length !== 0 ) {
  15343. destTracks.push( new trackType( trackName, times, values ) );
  15344. }
  15345. }
  15346. };
  15347. const tracks = [];
  15348. const clipName = animation.name || 'default';
  15349. const fps = animation.fps || 30;
  15350. const blendMode = animation.blendMode;
  15351. // automatic length determination in AnimationClip.
  15352. let duration = animation.length || - 1;
  15353. const hierarchyTracks = animation.hierarchy || [];
  15354. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15355. const animationKeys = hierarchyTracks[ h ].keys;
  15356. // skip empty tracks
  15357. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15358. // process morph targets
  15359. if ( animationKeys[ 0 ].morphTargets ) {
  15360. // figure out all morph targets used in this track
  15361. const morphTargetNames = {};
  15362. let k;
  15363. for ( k = 0; k < animationKeys.length; k ++ ) {
  15364. if ( animationKeys[ k ].morphTargets ) {
  15365. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15366. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15367. }
  15368. }
  15369. }
  15370. // create a track for each morph target with all zero
  15371. // morphTargetInfluences except for the keys in which
  15372. // the morphTarget is named.
  15373. for ( const morphTargetName in morphTargetNames ) {
  15374. const times = [];
  15375. const values = [];
  15376. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15377. const animationKey = animationKeys[ k ];
  15378. times.push( animationKey.time );
  15379. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15380. }
  15381. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15382. }
  15383. duration = morphTargetNames.length * fps;
  15384. } else {
  15385. // ...assume skeletal animation
  15386. const boneName = '.bones[' + bones[ h ].name + ']';
  15387. addNonemptyTrack(
  15388. VectorKeyframeTrack, boneName + '.position',
  15389. animationKeys, 'pos', tracks );
  15390. addNonemptyTrack(
  15391. QuaternionKeyframeTrack, boneName + '.quaternion',
  15392. animationKeys, 'rot', tracks );
  15393. addNonemptyTrack(
  15394. VectorKeyframeTrack, boneName + '.scale',
  15395. animationKeys, 'scl', tracks );
  15396. }
  15397. }
  15398. if ( tracks.length === 0 ) {
  15399. return null;
  15400. }
  15401. const clip = new this( clipName, duration, tracks, blendMode );
  15402. return clip;
  15403. }
  15404. resetDuration() {
  15405. const tracks = this.tracks;
  15406. let duration = 0;
  15407. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15408. const track = this.tracks[ i ];
  15409. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15410. }
  15411. this.duration = duration;
  15412. return this;
  15413. }
  15414. trim() {
  15415. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15416. this.tracks[ i ].trim( 0, this.duration );
  15417. }
  15418. return this;
  15419. }
  15420. validate() {
  15421. let valid = true;
  15422. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15423. valid = valid && this.tracks[ i ].validate();
  15424. }
  15425. return valid;
  15426. }
  15427. optimize() {
  15428. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15429. this.tracks[ i ].optimize();
  15430. }
  15431. return this;
  15432. }
  15433. clone() {
  15434. const tracks = [];
  15435. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15436. tracks.push( this.tracks[ i ].clone() );
  15437. }
  15438. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15439. }
  15440. toJSON() {
  15441. return this.constructor.toJSON( this );
  15442. }
  15443. }
  15444. function getTrackTypeForValueTypeName( typeName ) {
  15445. switch ( typeName.toLowerCase() ) {
  15446. case 'scalar':
  15447. case 'double':
  15448. case 'float':
  15449. case 'number':
  15450. case 'integer':
  15451. return NumberKeyframeTrack;
  15452. case 'vector':
  15453. case 'vector2':
  15454. case 'vector3':
  15455. case 'vector4':
  15456. return VectorKeyframeTrack;
  15457. case 'color':
  15458. return ColorKeyframeTrack;
  15459. case 'quaternion':
  15460. return QuaternionKeyframeTrack;
  15461. case 'bool':
  15462. case 'boolean':
  15463. return BooleanKeyframeTrack;
  15464. case 'string':
  15465. return StringKeyframeTrack;
  15466. }
  15467. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15468. }
  15469. function parseKeyframeTrack( json ) {
  15470. if ( json.type === undefined ) {
  15471. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15472. }
  15473. const trackType = getTrackTypeForValueTypeName( json.type );
  15474. if ( json.times === undefined ) {
  15475. const times = [], values = [];
  15476. flattenJSON( json.keys, times, values, 'value' );
  15477. json.times = times;
  15478. json.values = values;
  15479. }
  15480. // derived classes can define a static parse method
  15481. if ( trackType.parse !== undefined ) {
  15482. return trackType.parse( json );
  15483. } else {
  15484. // by default, we assume a constructor compatible with the base
  15485. return new trackType( json.name, json.times, json.values, json.interpolation );
  15486. }
  15487. }
  15488. const Cache = {
  15489. enabled: false,
  15490. files: {},
  15491. add: function ( key, file ) {
  15492. if ( this.enabled === false ) return;
  15493. // console.log( 'THREE.Cache', 'Adding key:', key );
  15494. this.files[ key ] = file;
  15495. },
  15496. get: function ( key ) {
  15497. if ( this.enabled === false ) return;
  15498. // console.log( 'THREE.Cache', 'Checking key:', key );
  15499. return this.files[ key ];
  15500. },
  15501. remove: function ( key ) {
  15502. delete this.files[ key ];
  15503. },
  15504. clear: function () {
  15505. this.files = {};
  15506. }
  15507. };
  15508. class LoadingManager {
  15509. constructor( onLoad, onProgress, onError ) {
  15510. const scope = this;
  15511. let isLoading = false;
  15512. let itemsLoaded = 0;
  15513. let itemsTotal = 0;
  15514. let urlModifier = undefined;
  15515. const handlers = [];
  15516. // Refer to #5689 for the reason why we don't set .onStart
  15517. // in the constructor
  15518. this.onStart = undefined;
  15519. this.onLoad = onLoad;
  15520. this.onProgress = onProgress;
  15521. this.onError = onError;
  15522. this.itemStart = function ( url ) {
  15523. itemsTotal ++;
  15524. if ( isLoading === false ) {
  15525. if ( scope.onStart !== undefined ) {
  15526. scope.onStart( url, itemsLoaded, itemsTotal );
  15527. }
  15528. }
  15529. isLoading = true;
  15530. };
  15531. this.itemEnd = function ( url ) {
  15532. itemsLoaded ++;
  15533. if ( scope.onProgress !== undefined ) {
  15534. scope.onProgress( url, itemsLoaded, itemsTotal );
  15535. }
  15536. if ( itemsLoaded === itemsTotal ) {
  15537. isLoading = false;
  15538. if ( scope.onLoad !== undefined ) {
  15539. scope.onLoad();
  15540. }
  15541. }
  15542. };
  15543. this.itemError = function ( url ) {
  15544. if ( scope.onError !== undefined ) {
  15545. scope.onError( url );
  15546. }
  15547. };
  15548. this.resolveURL = function ( url ) {
  15549. if ( urlModifier ) {
  15550. return urlModifier( url );
  15551. }
  15552. return url;
  15553. };
  15554. this.setURLModifier = function ( transform ) {
  15555. urlModifier = transform;
  15556. return this;
  15557. };
  15558. this.addHandler = function ( regex, loader ) {
  15559. handlers.push( regex, loader );
  15560. return this;
  15561. };
  15562. this.removeHandler = function ( regex ) {
  15563. const index = handlers.indexOf( regex );
  15564. if ( index !== - 1 ) {
  15565. handlers.splice( index, 2 );
  15566. }
  15567. return this;
  15568. };
  15569. this.getHandler = function ( file ) {
  15570. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15571. const regex = handlers[ i ];
  15572. const loader = handlers[ i + 1 ];
  15573. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15574. if ( regex.test( file ) ) {
  15575. return loader;
  15576. }
  15577. }
  15578. return null;
  15579. };
  15580. }
  15581. }
  15582. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15583. class Loader {
  15584. constructor( manager ) {
  15585. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15586. this.crossOrigin = 'anonymous';
  15587. this.withCredentials = false;
  15588. this.path = '';
  15589. this.resourcePath = '';
  15590. this.requestHeader = {};
  15591. }
  15592. load( /* url, onLoad, onProgress, onError */ ) {}
  15593. loadAsync( url, onProgress ) {
  15594. const scope = this;
  15595. return new Promise( function ( resolve, reject ) {
  15596. scope.load( url, resolve, onProgress, reject );
  15597. } );
  15598. }
  15599. parse( /* data */ ) {}
  15600. setCrossOrigin( crossOrigin ) {
  15601. this.crossOrigin = crossOrigin;
  15602. return this;
  15603. }
  15604. setWithCredentials( value ) {
  15605. this.withCredentials = value;
  15606. return this;
  15607. }
  15608. setPath( path ) {
  15609. this.path = path;
  15610. return this;
  15611. }
  15612. setResourcePath( resourcePath ) {
  15613. this.resourcePath = resourcePath;
  15614. return this;
  15615. }
  15616. setRequestHeader( requestHeader ) {
  15617. this.requestHeader = requestHeader;
  15618. return this;
  15619. }
  15620. }
  15621. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15622. const loading = {};
  15623. class HttpError extends Error {
  15624. constructor( message, response ) {
  15625. super( message );
  15626. this.response = response;
  15627. }
  15628. }
  15629. class FileLoader extends Loader {
  15630. constructor( manager ) {
  15631. super( manager );
  15632. }
  15633. load( url, onLoad, onProgress, onError ) {
  15634. if ( url === undefined ) url = '';
  15635. if ( this.path !== undefined ) url = this.path + url;
  15636. url = this.manager.resolveURL( url );
  15637. const cached = Cache.get( url );
  15638. if ( cached !== undefined ) {
  15639. this.manager.itemStart( url );
  15640. setTimeout( () => {
  15641. if ( onLoad ) onLoad( cached );
  15642. this.manager.itemEnd( url );
  15643. }, 0 );
  15644. return cached;
  15645. }
  15646. // Check if request is duplicate
  15647. if ( loading[ url ] !== undefined ) {
  15648. loading[ url ].push( {
  15649. onLoad: onLoad,
  15650. onProgress: onProgress,
  15651. onError: onError
  15652. } );
  15653. return;
  15654. }
  15655. // Initialise array for duplicate requests
  15656. loading[ url ] = [];
  15657. loading[ url ].push( {
  15658. onLoad: onLoad,
  15659. onProgress: onProgress,
  15660. onError: onError,
  15661. } );
  15662. // create request
  15663. const req = new Request( url, {
  15664. headers: new Headers( this.requestHeader ),
  15665. credentials: this.withCredentials ? 'include' : 'same-origin',
  15666. // An abort controller could be added within a future PR
  15667. } );
  15668. // record states ( avoid data race )
  15669. const mimeType = this.mimeType;
  15670. const responseType = this.responseType;
  15671. // start the fetch
  15672. fetch( req )
  15673. .then( response => {
  15674. if ( response.status === 200 || response.status === 0 ) {
  15675. // Some browsers return HTTP Status 0 when using non-http protocol
  15676. // e.g. 'file://' or 'data://'. Handle as success.
  15677. if ( response.status === 0 ) {
  15678. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15679. }
  15680. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15681. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15682. return response;
  15683. }
  15684. const callbacks = loading[ url ];
  15685. const reader = response.body.getReader();
  15686. // Nginx needs X-File-Size check
  15687. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15688. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15689. const total = contentLength ? parseInt( contentLength ) : 0;
  15690. const lengthComputable = total !== 0;
  15691. let loaded = 0;
  15692. // periodically read data into the new stream tracking while download progress
  15693. const stream = new ReadableStream( {
  15694. start( controller ) {
  15695. readData();
  15696. function readData() {
  15697. reader.read().then( ( { done, value } ) => {
  15698. if ( done ) {
  15699. controller.close();
  15700. } else {
  15701. loaded += value.byteLength;
  15702. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15703. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15704. const callback = callbacks[ i ];
  15705. if ( callback.onProgress ) callback.onProgress( event );
  15706. }
  15707. controller.enqueue( value );
  15708. readData();
  15709. }
  15710. }, ( e ) => {
  15711. controller.error( e );
  15712. } );
  15713. }
  15714. }
  15715. } );
  15716. return new Response( stream );
  15717. } else {
  15718. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15719. }
  15720. } )
  15721. .then( response => {
  15722. switch ( responseType ) {
  15723. case 'arraybuffer':
  15724. return response.arrayBuffer();
  15725. case 'blob':
  15726. return response.blob();
  15727. case 'document':
  15728. return response.text()
  15729. .then( text => {
  15730. const parser = new DOMParser();
  15731. return parser.parseFromString( text, mimeType );
  15732. } );
  15733. case 'json':
  15734. return response.json();
  15735. default:
  15736. if ( mimeType === undefined ) {
  15737. return response.text();
  15738. } else {
  15739. // sniff encoding
  15740. const re = /charset="?([^;"\s]*)"?/i;
  15741. const exec = re.exec( mimeType );
  15742. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15743. const decoder = new TextDecoder( label );
  15744. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15745. }
  15746. }
  15747. } )
  15748. .then( data => {
  15749. // Add to cache only on HTTP success, so that we do not cache
  15750. // error response bodies as proper responses to requests.
  15751. Cache.add( url, data );
  15752. const callbacks = loading[ url ];
  15753. delete loading[ url ];
  15754. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15755. const callback = callbacks[ i ];
  15756. if ( callback.onLoad ) callback.onLoad( data );
  15757. }
  15758. } )
  15759. .catch( err => {
  15760. // Abort errors and other errors are handled the same
  15761. const callbacks = loading[ url ];
  15762. if ( callbacks === undefined ) {
  15763. // When onLoad was called and url was deleted in `loading`
  15764. this.manager.itemError( url );
  15765. throw err;
  15766. }
  15767. delete loading[ url ];
  15768. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15769. const callback = callbacks[ i ];
  15770. if ( callback.onError ) callback.onError( err );
  15771. }
  15772. this.manager.itemError( url );
  15773. } )
  15774. .finally( () => {
  15775. this.manager.itemEnd( url );
  15776. } );
  15777. this.manager.itemStart( url );
  15778. }
  15779. setResponseType( value ) {
  15780. this.responseType = value;
  15781. return this;
  15782. }
  15783. setMimeType( value ) {
  15784. this.mimeType = value;
  15785. return this;
  15786. }
  15787. }
  15788. class AnimationLoader extends Loader {
  15789. constructor( manager ) {
  15790. super( manager );
  15791. }
  15792. load( url, onLoad, onProgress, onError ) {
  15793. const scope = this;
  15794. const loader = new FileLoader( this.manager );
  15795. loader.setPath( this.path );
  15796. loader.setRequestHeader( this.requestHeader );
  15797. loader.setWithCredentials( this.withCredentials );
  15798. loader.load( url, function ( text ) {
  15799. try {
  15800. onLoad( scope.parse( JSON.parse( text ) ) );
  15801. } catch ( e ) {
  15802. if ( onError ) {
  15803. onError( e );
  15804. } else {
  15805. console.error( e );
  15806. }
  15807. scope.manager.itemError( url );
  15808. }
  15809. }, onProgress, onError );
  15810. }
  15811. parse( json ) {
  15812. const animations = [];
  15813. for ( let i = 0; i < json.length; i ++ ) {
  15814. const clip = AnimationClip.parse( json[ i ] );
  15815. animations.push( clip );
  15816. }
  15817. return animations;
  15818. }
  15819. }
  15820. /**
  15821. * Abstract Base class to block based textures loader (dds, pvr, ...)
  15822. *
  15823. * Sub classes have to implement the parse() method which will be used in load().
  15824. */
  15825. class CompressedTextureLoader extends Loader {
  15826. constructor( manager ) {
  15827. super( manager );
  15828. }
  15829. load( url, onLoad, onProgress, onError ) {
  15830. const scope = this;
  15831. const images = [];
  15832. const texture = new CompressedTexture();
  15833. const loader = new FileLoader( this.manager );
  15834. loader.setPath( this.path );
  15835. loader.setResponseType( 'arraybuffer' );
  15836. loader.setRequestHeader( this.requestHeader );
  15837. loader.setWithCredentials( scope.withCredentials );
  15838. let loaded = 0;
  15839. function loadTexture( i ) {
  15840. loader.load( url[ i ], function ( buffer ) {
  15841. const texDatas = scope.parse( buffer, true );
  15842. images[ i ] = {
  15843. width: texDatas.width,
  15844. height: texDatas.height,
  15845. format: texDatas.format,
  15846. mipmaps: texDatas.mipmaps
  15847. };
  15848. loaded += 1;
  15849. if ( loaded === 6 ) {
  15850. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  15851. texture.image = images;
  15852. texture.format = texDatas.format;
  15853. texture.needsUpdate = true;
  15854. if ( onLoad ) onLoad( texture );
  15855. }
  15856. }, onProgress, onError );
  15857. }
  15858. if ( Array.isArray( url ) ) {
  15859. for ( let i = 0, il = url.length; i < il; ++ i ) {
  15860. loadTexture( i );
  15861. }
  15862. } else {
  15863. // compressed cubemap texture stored in a single DDS file
  15864. loader.load( url, function ( buffer ) {
  15865. const texDatas = scope.parse( buffer, true );
  15866. if ( texDatas.isCubemap ) {
  15867. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  15868. for ( let f = 0; f < faces; f ++ ) {
  15869. images[ f ] = { mipmaps: [] };
  15870. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  15871. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  15872. images[ f ].format = texDatas.format;
  15873. images[ f ].width = texDatas.width;
  15874. images[ f ].height = texDatas.height;
  15875. }
  15876. }
  15877. texture.image = images;
  15878. } else {
  15879. texture.image.width = texDatas.width;
  15880. texture.image.height = texDatas.height;
  15881. texture.mipmaps = texDatas.mipmaps;
  15882. }
  15883. if ( texDatas.mipmapCount === 1 ) {
  15884. texture.minFilter = LinearFilter;
  15885. }
  15886. texture.format = texDatas.format;
  15887. texture.needsUpdate = true;
  15888. if ( onLoad ) onLoad( texture );
  15889. }, onProgress, onError );
  15890. }
  15891. return texture;
  15892. }
  15893. }
  15894. class ImageLoader extends Loader {
  15895. constructor( manager ) {
  15896. super( manager );
  15897. }
  15898. load( url, onLoad, onProgress, onError ) {
  15899. if ( this.path !== undefined ) url = this.path + url;
  15900. url = this.manager.resolveURL( url );
  15901. const scope = this;
  15902. const cached = Cache.get( url );
  15903. if ( cached !== undefined ) {
  15904. scope.manager.itemStart( url );
  15905. setTimeout( function () {
  15906. if ( onLoad ) onLoad( cached );
  15907. scope.manager.itemEnd( url );
  15908. }, 0 );
  15909. return cached;
  15910. }
  15911. const image = createElementNS( 'img' );
  15912. function onImageLoad() {
  15913. removeEventListeners();
  15914. Cache.add( url, this );
  15915. if ( onLoad ) onLoad( this );
  15916. scope.manager.itemEnd( url );
  15917. }
  15918. function onImageError( event ) {
  15919. removeEventListeners();
  15920. if ( onError ) onError( event );
  15921. scope.manager.itemError( url );
  15922. scope.manager.itemEnd( url );
  15923. }
  15924. function removeEventListeners() {
  15925. image.removeEventListener( 'load', onImageLoad, false );
  15926. image.removeEventListener( 'error', onImageError, false );
  15927. }
  15928. image.addEventListener( 'load', onImageLoad, false );
  15929. image.addEventListener( 'error', onImageError, false );
  15930. if ( url.slice( 0, 5 ) !== 'data:' ) {
  15931. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  15932. }
  15933. scope.manager.itemStart( url );
  15934. image.src = url;
  15935. return image;
  15936. }
  15937. }
  15938. class CubeTextureLoader extends Loader {
  15939. constructor( manager ) {
  15940. super( manager );
  15941. }
  15942. load( urls, onLoad, onProgress, onError ) {
  15943. const texture = new CubeTexture();
  15944. texture.colorSpace = SRGBColorSpace;
  15945. const loader = new ImageLoader( this.manager );
  15946. loader.setCrossOrigin( this.crossOrigin );
  15947. loader.setPath( this.path );
  15948. let loaded = 0;
  15949. function loadTexture( i ) {
  15950. loader.load( urls[ i ], function ( image ) {
  15951. texture.images[ i ] = image;
  15952. loaded ++;
  15953. if ( loaded === 6 ) {
  15954. texture.needsUpdate = true;
  15955. if ( onLoad ) onLoad( texture );
  15956. }
  15957. }, undefined, onError );
  15958. }
  15959. for ( let i = 0; i < urls.length; ++ i ) {
  15960. loadTexture( i );
  15961. }
  15962. return texture;
  15963. }
  15964. }
  15965. /**
  15966. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  15967. *
  15968. * Sub classes have to implement the parse() method which will be used in load().
  15969. */
  15970. class DataTextureLoader extends Loader {
  15971. constructor( manager ) {
  15972. super( manager );
  15973. }
  15974. load( url, onLoad, onProgress, onError ) {
  15975. const scope = this;
  15976. const texture = new DataTexture();
  15977. const loader = new FileLoader( this.manager );
  15978. loader.setResponseType( 'arraybuffer' );
  15979. loader.setRequestHeader( this.requestHeader );
  15980. loader.setPath( this.path );
  15981. loader.setWithCredentials( scope.withCredentials );
  15982. loader.load( url, function ( buffer ) {
  15983. let texData;
  15984. try {
  15985. texData = scope.parse( buffer );
  15986. } catch ( error ) {
  15987. if ( onError !== undefined ) {
  15988. onError( error );
  15989. } else {
  15990. console.error( error );
  15991. return;
  15992. }
  15993. }
  15994. if ( texData.image !== undefined ) {
  15995. texture.image = texData.image;
  15996. } else if ( texData.data !== undefined ) {
  15997. texture.image.width = texData.width;
  15998. texture.image.height = texData.height;
  15999. texture.image.data = texData.data;
  16000. }
  16001. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  16002. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  16003. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  16004. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  16005. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  16006. if ( texData.colorSpace !== undefined ) {
  16007. texture.colorSpace = texData.colorSpace;
  16008. }
  16009. if ( texData.flipY !== undefined ) {
  16010. texture.flipY = texData.flipY;
  16011. }
  16012. if ( texData.format !== undefined ) {
  16013. texture.format = texData.format;
  16014. }
  16015. if ( texData.type !== undefined ) {
  16016. texture.type = texData.type;
  16017. }
  16018. if ( texData.mipmaps !== undefined ) {
  16019. texture.mipmaps = texData.mipmaps;
  16020. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  16021. }
  16022. if ( texData.mipmapCount === 1 ) {
  16023. texture.minFilter = LinearFilter;
  16024. }
  16025. if ( texData.generateMipmaps !== undefined ) {
  16026. texture.generateMipmaps = texData.generateMipmaps;
  16027. }
  16028. texture.needsUpdate = true;
  16029. if ( onLoad ) onLoad( texture, texData );
  16030. }, onProgress, onError );
  16031. return texture;
  16032. }
  16033. }
  16034. class TextureLoader extends Loader {
  16035. constructor( manager ) {
  16036. super( manager );
  16037. }
  16038. load( url, onLoad, onProgress, onError ) {
  16039. const texture = new Texture();
  16040. const loader = new ImageLoader( this.manager );
  16041. loader.setCrossOrigin( this.crossOrigin );
  16042. loader.setPath( this.path );
  16043. loader.load( url, function ( image ) {
  16044. texture.image = image;
  16045. texture.needsUpdate = true;
  16046. if ( onLoad !== undefined ) {
  16047. onLoad( texture );
  16048. }
  16049. }, onProgress, onError );
  16050. return texture;
  16051. }
  16052. }
  16053. class Light extends Object3D {
  16054. constructor( color, intensity = 1 ) {
  16055. super();
  16056. this.isLight = true;
  16057. this.type = 'Light';
  16058. this.color = new Color( color );
  16059. this.intensity = intensity;
  16060. }
  16061. dispose() {
  16062. // Empty here in base class; some subclasses override.
  16063. }
  16064. copy( source, recursive ) {
  16065. super.copy( source, recursive );
  16066. this.color.copy( source.color );
  16067. this.intensity = source.intensity;
  16068. return this;
  16069. }
  16070. toJSON( meta ) {
  16071. const data = super.toJSON( meta );
  16072. data.object.color = this.color.getHex();
  16073. data.object.intensity = this.intensity;
  16074. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16075. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16076. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16077. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16078. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16079. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16080. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16081. return data;
  16082. }
  16083. }
  16084. class HemisphereLight extends Light {
  16085. constructor( skyColor, groundColor, intensity ) {
  16086. super( skyColor, intensity );
  16087. this.isHemisphereLight = true;
  16088. this.type = 'HemisphereLight';
  16089. this.position.copy( Object3D.DEFAULT_UP );
  16090. this.updateMatrix();
  16091. this.groundColor = new Color( groundColor );
  16092. }
  16093. copy( source, recursive ) {
  16094. super.copy( source, recursive );
  16095. this.groundColor.copy( source.groundColor );
  16096. return this;
  16097. }
  16098. }
  16099. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16100. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16101. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16102. class LightShadow {
  16103. constructor( camera ) {
  16104. this.camera = camera;
  16105. this.intensity = 1;
  16106. this.bias = 0;
  16107. this.normalBias = 0;
  16108. this.radius = 1;
  16109. this.blurSamples = 8;
  16110. this.mapSize = new Vector2( 512, 512 );
  16111. this.map = null;
  16112. this.mapPass = null;
  16113. this.matrix = new Matrix4();
  16114. this.autoUpdate = true;
  16115. this.needsUpdate = false;
  16116. this._frustum = new Frustum();
  16117. this._frameExtents = new Vector2( 1, 1 );
  16118. this._viewportCount = 1;
  16119. this._viewports = [
  16120. new Vector4( 0, 0, 1, 1 )
  16121. ];
  16122. }
  16123. getViewportCount() {
  16124. return this._viewportCount;
  16125. }
  16126. getFrustum() {
  16127. return this._frustum;
  16128. }
  16129. updateMatrices( light ) {
  16130. const shadowCamera = this.camera;
  16131. const shadowMatrix = this.matrix;
  16132. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16133. shadowCamera.position.copy( _lightPositionWorld$1 );
  16134. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16135. shadowCamera.lookAt( _lookTarget$1 );
  16136. shadowCamera.updateMatrixWorld();
  16137. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16138. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16139. shadowMatrix.set(
  16140. 0.5, 0.0, 0.0, 0.5,
  16141. 0.0, 0.5, 0.0, 0.5,
  16142. 0.0, 0.0, 0.5, 0.5,
  16143. 0.0, 0.0, 0.0, 1.0
  16144. );
  16145. shadowMatrix.multiply( _projScreenMatrix$2 );
  16146. }
  16147. getViewport( viewportIndex ) {
  16148. return this._viewports[ viewportIndex ];
  16149. }
  16150. getFrameExtents() {
  16151. return this._frameExtents;
  16152. }
  16153. dispose() {
  16154. if ( this.map ) {
  16155. this.map.dispose();
  16156. }
  16157. if ( this.mapPass ) {
  16158. this.mapPass.dispose();
  16159. }
  16160. }
  16161. copy( source ) {
  16162. this.camera = source.camera.clone();
  16163. this.intensity = source.intensity;
  16164. this.bias = source.bias;
  16165. this.radius = source.radius;
  16166. this.mapSize.copy( source.mapSize );
  16167. return this;
  16168. }
  16169. clone() {
  16170. return new this.constructor().copy( this );
  16171. }
  16172. toJSON() {
  16173. const object = {};
  16174. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16175. if ( this.bias !== 0 ) object.bias = this.bias;
  16176. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16177. if ( this.radius !== 1 ) object.radius = this.radius;
  16178. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16179. object.camera = this.camera.toJSON( false ).object;
  16180. delete object.camera.matrix;
  16181. return object;
  16182. }
  16183. }
  16184. class SpotLightShadow extends LightShadow {
  16185. constructor() {
  16186. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16187. this.isSpotLightShadow = true;
  16188. this.focus = 1;
  16189. }
  16190. updateMatrices( light ) {
  16191. const camera = this.camera;
  16192. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16193. const aspect = this.mapSize.width / this.mapSize.height;
  16194. const far = light.distance || camera.far;
  16195. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16196. camera.fov = fov;
  16197. camera.aspect = aspect;
  16198. camera.far = far;
  16199. camera.updateProjectionMatrix();
  16200. }
  16201. super.updateMatrices( light );
  16202. }
  16203. copy( source ) {
  16204. super.copy( source );
  16205. this.focus = source.focus;
  16206. return this;
  16207. }
  16208. }
  16209. class SpotLight extends Light {
  16210. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16211. super( color, intensity );
  16212. this.isSpotLight = true;
  16213. this.type = 'SpotLight';
  16214. this.position.copy( Object3D.DEFAULT_UP );
  16215. this.updateMatrix();
  16216. this.target = new Object3D();
  16217. this.distance = distance;
  16218. this.angle = angle;
  16219. this.penumbra = penumbra;
  16220. this.decay = decay;
  16221. this.map = null;
  16222. this.shadow = new SpotLightShadow();
  16223. }
  16224. get power() {
  16225. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16226. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16227. return this.intensity * Math.PI;
  16228. }
  16229. set power( power ) {
  16230. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16231. this.intensity = power / Math.PI;
  16232. }
  16233. dispose() {
  16234. this.shadow.dispose();
  16235. }
  16236. copy( source, recursive ) {
  16237. super.copy( source, recursive );
  16238. this.distance = source.distance;
  16239. this.angle = source.angle;
  16240. this.penumbra = source.penumbra;
  16241. this.decay = source.decay;
  16242. this.target = source.target.clone();
  16243. this.shadow = source.shadow.clone();
  16244. return this;
  16245. }
  16246. }
  16247. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16248. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16249. const _lookTarget = /*@__PURE__*/ new Vector3();
  16250. class PointLightShadow extends LightShadow {
  16251. constructor() {
  16252. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16253. this.isPointLightShadow = true;
  16254. this._frameExtents = new Vector2( 4, 2 );
  16255. this._viewportCount = 6;
  16256. this._viewports = [
  16257. // These viewports map a cube-map onto a 2D texture with the
  16258. // following orientation:
  16259. //
  16260. // xzXZ
  16261. // y Y
  16262. //
  16263. // X - Positive x direction
  16264. // x - Negative x direction
  16265. // Y - Positive y direction
  16266. // y - Negative y direction
  16267. // Z - Positive z direction
  16268. // z - Negative z direction
  16269. // positive X
  16270. new Vector4( 2, 1, 1, 1 ),
  16271. // negative X
  16272. new Vector4( 0, 1, 1, 1 ),
  16273. // positive Z
  16274. new Vector4( 3, 1, 1, 1 ),
  16275. // negative Z
  16276. new Vector4( 1, 1, 1, 1 ),
  16277. // positive Y
  16278. new Vector4( 3, 0, 1, 1 ),
  16279. // negative Y
  16280. new Vector4( 1, 0, 1, 1 )
  16281. ];
  16282. this._cubeDirections = [
  16283. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16284. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16285. ];
  16286. this._cubeUps = [
  16287. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16288. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16289. ];
  16290. }
  16291. updateMatrices( light, viewportIndex = 0 ) {
  16292. const camera = this.camera;
  16293. const shadowMatrix = this.matrix;
  16294. const far = light.distance || camera.far;
  16295. if ( far !== camera.far ) {
  16296. camera.far = far;
  16297. camera.updateProjectionMatrix();
  16298. }
  16299. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16300. camera.position.copy( _lightPositionWorld );
  16301. _lookTarget.copy( camera.position );
  16302. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16303. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16304. camera.lookAt( _lookTarget );
  16305. camera.updateMatrixWorld();
  16306. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16307. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16308. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16309. }
  16310. }
  16311. class PointLight extends Light {
  16312. constructor( color, intensity, distance = 0, decay = 2 ) {
  16313. super( color, intensity );
  16314. this.isPointLight = true;
  16315. this.type = 'PointLight';
  16316. this.distance = distance;
  16317. this.decay = decay;
  16318. this.shadow = new PointLightShadow();
  16319. }
  16320. get power() {
  16321. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16322. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16323. return this.intensity * 4 * Math.PI;
  16324. }
  16325. set power( power ) {
  16326. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16327. this.intensity = power / ( 4 * Math.PI );
  16328. }
  16329. dispose() {
  16330. this.shadow.dispose();
  16331. }
  16332. copy( source, recursive ) {
  16333. super.copy( source, recursive );
  16334. this.distance = source.distance;
  16335. this.decay = source.decay;
  16336. this.shadow = source.shadow.clone();
  16337. return this;
  16338. }
  16339. }
  16340. class OrthographicCamera extends Camera {
  16341. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16342. super();
  16343. this.isOrthographicCamera = true;
  16344. this.type = 'OrthographicCamera';
  16345. this.zoom = 1;
  16346. this.view = null;
  16347. this.left = left;
  16348. this.right = right;
  16349. this.top = top;
  16350. this.bottom = bottom;
  16351. this.near = near;
  16352. this.far = far;
  16353. this.updateProjectionMatrix();
  16354. }
  16355. copy( source, recursive ) {
  16356. super.copy( source, recursive );
  16357. this.left = source.left;
  16358. this.right = source.right;
  16359. this.top = source.top;
  16360. this.bottom = source.bottom;
  16361. this.near = source.near;
  16362. this.far = source.far;
  16363. this.zoom = source.zoom;
  16364. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16365. return this;
  16366. }
  16367. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16368. if ( this.view === null ) {
  16369. this.view = {
  16370. enabled: true,
  16371. fullWidth: 1,
  16372. fullHeight: 1,
  16373. offsetX: 0,
  16374. offsetY: 0,
  16375. width: 1,
  16376. height: 1
  16377. };
  16378. }
  16379. this.view.enabled = true;
  16380. this.view.fullWidth = fullWidth;
  16381. this.view.fullHeight = fullHeight;
  16382. this.view.offsetX = x;
  16383. this.view.offsetY = y;
  16384. this.view.width = width;
  16385. this.view.height = height;
  16386. this.updateProjectionMatrix();
  16387. }
  16388. clearViewOffset() {
  16389. if ( this.view !== null ) {
  16390. this.view.enabled = false;
  16391. }
  16392. this.updateProjectionMatrix();
  16393. }
  16394. updateProjectionMatrix() {
  16395. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16396. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16397. const cx = ( this.right + this.left ) / 2;
  16398. const cy = ( this.top + this.bottom ) / 2;
  16399. let left = cx - dx;
  16400. let right = cx + dx;
  16401. let top = cy + dy;
  16402. let bottom = cy - dy;
  16403. if ( this.view !== null && this.view.enabled ) {
  16404. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16405. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16406. left += scaleW * this.view.offsetX;
  16407. right = left + scaleW * this.view.width;
  16408. top -= scaleH * this.view.offsetY;
  16409. bottom = top - scaleH * this.view.height;
  16410. }
  16411. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16412. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16413. }
  16414. toJSON( meta ) {
  16415. const data = super.toJSON( meta );
  16416. data.object.zoom = this.zoom;
  16417. data.object.left = this.left;
  16418. data.object.right = this.right;
  16419. data.object.top = this.top;
  16420. data.object.bottom = this.bottom;
  16421. data.object.near = this.near;
  16422. data.object.far = this.far;
  16423. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16424. return data;
  16425. }
  16426. }
  16427. class DirectionalLightShadow extends LightShadow {
  16428. constructor() {
  16429. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16430. this.isDirectionalLightShadow = true;
  16431. }
  16432. }
  16433. class DirectionalLight extends Light {
  16434. constructor( color, intensity ) {
  16435. super( color, intensity );
  16436. this.isDirectionalLight = true;
  16437. this.type = 'DirectionalLight';
  16438. this.position.copy( Object3D.DEFAULT_UP );
  16439. this.updateMatrix();
  16440. this.target = new Object3D();
  16441. this.shadow = new DirectionalLightShadow();
  16442. }
  16443. dispose() {
  16444. this.shadow.dispose();
  16445. }
  16446. copy( source ) {
  16447. super.copy( source );
  16448. this.target = source.target.clone();
  16449. this.shadow = source.shadow.clone();
  16450. return this;
  16451. }
  16452. }
  16453. class AmbientLight extends Light {
  16454. constructor( color, intensity ) {
  16455. super( color, intensity );
  16456. this.isAmbientLight = true;
  16457. this.type = 'AmbientLight';
  16458. }
  16459. }
  16460. class RectAreaLight extends Light {
  16461. constructor( color, intensity, width = 10, height = 10 ) {
  16462. super( color, intensity );
  16463. this.isRectAreaLight = true;
  16464. this.type = 'RectAreaLight';
  16465. this.width = width;
  16466. this.height = height;
  16467. }
  16468. get power() {
  16469. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16470. return this.intensity * this.width * this.height * Math.PI;
  16471. }
  16472. set power( power ) {
  16473. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16474. this.intensity = power / ( this.width * this.height * Math.PI );
  16475. }
  16476. copy( source ) {
  16477. super.copy( source );
  16478. this.width = source.width;
  16479. this.height = source.height;
  16480. return this;
  16481. }
  16482. toJSON( meta ) {
  16483. const data = super.toJSON( meta );
  16484. data.object.width = this.width;
  16485. data.object.height = this.height;
  16486. return data;
  16487. }
  16488. }
  16489. /**
  16490. * Primary reference:
  16491. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16492. *
  16493. * Secondary reference:
  16494. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16495. */
  16496. // 3-band SH defined by 9 coefficients
  16497. class SphericalHarmonics3 {
  16498. constructor() {
  16499. this.isSphericalHarmonics3 = true;
  16500. this.coefficients = [];
  16501. for ( let i = 0; i < 9; i ++ ) {
  16502. this.coefficients.push( new Vector3() );
  16503. }
  16504. }
  16505. set( coefficients ) {
  16506. for ( let i = 0; i < 9; i ++ ) {
  16507. this.coefficients[ i ].copy( coefficients[ i ] );
  16508. }
  16509. return this;
  16510. }
  16511. zero() {
  16512. for ( let i = 0; i < 9; i ++ ) {
  16513. this.coefficients[ i ].set( 0, 0, 0 );
  16514. }
  16515. return this;
  16516. }
  16517. // get the radiance in the direction of the normal
  16518. // target is a Vector3
  16519. getAt( normal, target ) {
  16520. // normal is assumed to be unit length
  16521. const x = normal.x, y = normal.y, z = normal.z;
  16522. const coeff = this.coefficients;
  16523. // band 0
  16524. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16525. // band 1
  16526. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16527. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16528. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16529. // band 2
  16530. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16531. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16532. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16533. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16534. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16535. return target;
  16536. }
  16537. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16538. // target is a Vector3
  16539. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16540. getIrradianceAt( normal, target ) {
  16541. // normal is assumed to be unit length
  16542. const x = normal.x, y = normal.y, z = normal.z;
  16543. const coeff = this.coefficients;
  16544. // band 0
  16545. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16546. // band 1
  16547. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16548. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16549. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16550. // band 2
  16551. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16552. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16553. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16554. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16555. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16556. return target;
  16557. }
  16558. add( sh ) {
  16559. for ( let i = 0; i < 9; i ++ ) {
  16560. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16561. }
  16562. return this;
  16563. }
  16564. addScaledSH( sh, s ) {
  16565. for ( let i = 0; i < 9; i ++ ) {
  16566. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16567. }
  16568. return this;
  16569. }
  16570. scale( s ) {
  16571. for ( let i = 0; i < 9; i ++ ) {
  16572. this.coefficients[ i ].multiplyScalar( s );
  16573. }
  16574. return this;
  16575. }
  16576. lerp( sh, alpha ) {
  16577. for ( let i = 0; i < 9; i ++ ) {
  16578. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16579. }
  16580. return this;
  16581. }
  16582. equals( sh ) {
  16583. for ( let i = 0; i < 9; i ++ ) {
  16584. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16585. return false;
  16586. }
  16587. }
  16588. return true;
  16589. }
  16590. copy( sh ) {
  16591. return this.set( sh.coefficients );
  16592. }
  16593. clone() {
  16594. return new this.constructor().copy( this );
  16595. }
  16596. fromArray( array, offset = 0 ) {
  16597. const coefficients = this.coefficients;
  16598. for ( let i = 0; i < 9; i ++ ) {
  16599. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16600. }
  16601. return this;
  16602. }
  16603. toArray( array = [], offset = 0 ) {
  16604. const coefficients = this.coefficients;
  16605. for ( let i = 0; i < 9; i ++ ) {
  16606. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16607. }
  16608. return array;
  16609. }
  16610. // evaluate the basis functions
  16611. // shBasis is an Array[ 9 ]
  16612. static getBasisAt( normal, shBasis ) {
  16613. // normal is assumed to be unit length
  16614. const x = normal.x, y = normal.y, z = normal.z;
  16615. // band 0
  16616. shBasis[ 0 ] = 0.282095;
  16617. // band 1
  16618. shBasis[ 1 ] = 0.488603 * y;
  16619. shBasis[ 2 ] = 0.488603 * z;
  16620. shBasis[ 3 ] = 0.488603 * x;
  16621. // band 2
  16622. shBasis[ 4 ] = 1.092548 * x * y;
  16623. shBasis[ 5 ] = 1.092548 * y * z;
  16624. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16625. shBasis[ 7 ] = 1.092548 * x * z;
  16626. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16627. }
  16628. }
  16629. class LightProbe extends Light {
  16630. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16631. super( undefined, intensity );
  16632. this.isLightProbe = true;
  16633. this.sh = sh;
  16634. }
  16635. copy( source ) {
  16636. super.copy( source );
  16637. this.sh.copy( source.sh );
  16638. return this;
  16639. }
  16640. fromJSON( json ) {
  16641. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16642. this.sh.fromArray( json.sh );
  16643. return this;
  16644. }
  16645. toJSON( meta ) {
  16646. const data = super.toJSON( meta );
  16647. data.object.sh = this.sh.toArray();
  16648. return data;
  16649. }
  16650. }
  16651. class MaterialLoader extends Loader {
  16652. constructor( manager ) {
  16653. super( manager );
  16654. this.textures = {};
  16655. }
  16656. load( url, onLoad, onProgress, onError ) {
  16657. const scope = this;
  16658. const loader = new FileLoader( scope.manager );
  16659. loader.setPath( scope.path );
  16660. loader.setRequestHeader( scope.requestHeader );
  16661. loader.setWithCredentials( scope.withCredentials );
  16662. loader.load( url, function ( text ) {
  16663. try {
  16664. onLoad( scope.parse( JSON.parse( text ) ) );
  16665. } catch ( e ) {
  16666. if ( onError ) {
  16667. onError( e );
  16668. } else {
  16669. console.error( e );
  16670. }
  16671. scope.manager.itemError( url );
  16672. }
  16673. }, onProgress, onError );
  16674. }
  16675. parse( json ) {
  16676. const textures = this.textures;
  16677. function getTexture( name ) {
  16678. if ( textures[ name ] === undefined ) {
  16679. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16680. }
  16681. return textures[ name ];
  16682. }
  16683. const material = this.createMaterialFromType( json.type );
  16684. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16685. if ( json.name !== undefined ) material.name = json.name;
  16686. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16687. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16688. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16689. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16690. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16691. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16692. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16693. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16694. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16695. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16696. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16697. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16698. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16699. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16700. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16701. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16702. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16703. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16704. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16705. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16706. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16707. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16708. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16709. if ( json.fog !== undefined ) material.fog = json.fog;
  16710. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16711. if ( json.blending !== undefined ) material.blending = json.blending;
  16712. if ( json.combine !== undefined ) material.combine = json.combine;
  16713. if ( json.side !== undefined ) material.side = json.side;
  16714. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16715. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16716. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16717. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16718. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16719. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16720. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16721. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16722. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16723. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16724. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16725. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16726. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16727. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16728. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16729. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16730. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16731. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16732. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16733. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16734. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16735. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16736. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16737. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16738. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16739. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16740. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16741. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16742. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16743. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16744. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16745. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16746. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16747. if ( json.scale !== undefined ) material.scale = json.scale;
  16748. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16749. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16750. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16751. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16752. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16753. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16754. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16755. if ( json.visible !== undefined ) material.visible = json.visible;
  16756. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16757. if ( json.userData !== undefined ) material.userData = json.userData;
  16758. if ( json.vertexColors !== undefined ) {
  16759. if ( typeof json.vertexColors === 'number' ) {
  16760. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16761. } else {
  16762. material.vertexColors = json.vertexColors;
  16763. }
  16764. }
  16765. // Shader Material
  16766. if ( json.uniforms !== undefined ) {
  16767. for ( const name in json.uniforms ) {
  16768. const uniform = json.uniforms[ name ];
  16769. material.uniforms[ name ] = {};
  16770. switch ( uniform.type ) {
  16771. case 't':
  16772. material.uniforms[ name ].value = getTexture( uniform.value );
  16773. break;
  16774. case 'c':
  16775. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  16776. break;
  16777. case 'v2':
  16778. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  16779. break;
  16780. case 'v3':
  16781. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  16782. break;
  16783. case 'v4':
  16784. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  16785. break;
  16786. case 'm3':
  16787. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  16788. break;
  16789. case 'm4':
  16790. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  16791. break;
  16792. default:
  16793. material.uniforms[ name ].value = uniform.value;
  16794. }
  16795. }
  16796. }
  16797. if ( json.defines !== undefined ) material.defines = json.defines;
  16798. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16799. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16800. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  16801. if ( json.extensions !== undefined ) {
  16802. for ( const key in json.extensions ) {
  16803. material.extensions[ key ] = json.extensions[ key ];
  16804. }
  16805. }
  16806. if ( json.lights !== undefined ) material.lights = json.lights;
  16807. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  16808. // for PointsMaterial
  16809. if ( json.size !== undefined ) material.size = json.size;
  16810. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16811. // maps
  16812. if ( json.map !== undefined ) material.map = getTexture( json.map );
  16813. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  16814. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  16815. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  16816. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16817. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  16818. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  16819. if ( json.normalScale !== undefined ) {
  16820. let normalScale = json.normalScale;
  16821. if ( Array.isArray( normalScale ) === false ) {
  16822. // Blender exporter used to export a scalar. See #7459
  16823. normalScale = [ normalScale, normalScale ];
  16824. }
  16825. material.normalScale = new Vector2().fromArray( normalScale );
  16826. }
  16827. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  16828. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16829. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16830. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  16831. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  16832. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  16833. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16834. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  16835. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  16836. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  16837. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  16838. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  16839. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  16840. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  16841. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  16842. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  16843. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  16844. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  16845. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  16846. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  16847. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  16848. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  16849. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  16850. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  16851. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  16852. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  16853. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  16854. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  16855. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  16856. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  16857. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  16858. return material;
  16859. }
  16860. setTextures( value ) {
  16861. this.textures = value;
  16862. return this;
  16863. }
  16864. createMaterialFromType( type ) {
  16865. return MaterialLoader.createMaterialFromType( type );
  16866. }
  16867. static createMaterialFromType( type ) {
  16868. const materialLib = {
  16869. ShadowMaterial,
  16870. SpriteMaterial,
  16871. RawShaderMaterial,
  16872. ShaderMaterial,
  16873. PointsMaterial,
  16874. MeshPhysicalMaterial,
  16875. MeshStandardMaterial,
  16876. MeshPhongMaterial,
  16877. MeshToonMaterial,
  16878. MeshNormalMaterial,
  16879. MeshLambertMaterial,
  16880. MeshDepthMaterial,
  16881. MeshDistanceMaterial,
  16882. MeshBasicMaterial,
  16883. MeshMatcapMaterial,
  16884. LineDashedMaterial,
  16885. LineBasicMaterial,
  16886. Material
  16887. };
  16888. return new materialLib[ type ]();
  16889. }
  16890. }
  16891. class LoaderUtils {
  16892. static decodeText( array ) { // @deprecated, r165
  16893. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  16894. if ( typeof TextDecoder !== 'undefined' ) {
  16895. return new TextDecoder().decode( array );
  16896. }
  16897. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  16898. // throws a "maximum call stack size exceeded" error for large arrays.
  16899. let s = '';
  16900. for ( let i = 0, il = array.length; i < il; i ++ ) {
  16901. // Implicitly assumes little-endian.
  16902. s += String.fromCharCode( array[ i ] );
  16903. }
  16904. try {
  16905. // merges multi-byte utf-8 characters.
  16906. return decodeURIComponent( escape( s ) );
  16907. } catch ( e ) { // see #16358
  16908. return s;
  16909. }
  16910. }
  16911. static extractUrlBase( url ) {
  16912. const index = url.lastIndexOf( '/' );
  16913. if ( index === - 1 ) return './';
  16914. return url.slice( 0, index + 1 );
  16915. }
  16916. static resolveURL( url, path ) {
  16917. // Invalid URL
  16918. if ( typeof url !== 'string' || url === '' ) return '';
  16919. // Host Relative URL
  16920. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  16921. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  16922. }
  16923. // Absolute URL http://,https://,//
  16924. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  16925. // Data URI
  16926. if ( /^data:.*,.*$/i.test( url ) ) return url;
  16927. // Blob URL
  16928. if ( /^blob:.*$/i.test( url ) ) return url;
  16929. // Relative URL
  16930. return path + url;
  16931. }
  16932. }
  16933. class InstancedBufferGeometry extends BufferGeometry {
  16934. constructor() {
  16935. super();
  16936. this.isInstancedBufferGeometry = true;
  16937. this.type = 'InstancedBufferGeometry';
  16938. this.instanceCount = Infinity;
  16939. }
  16940. copy( source ) {
  16941. super.copy( source );
  16942. this.instanceCount = source.instanceCount;
  16943. return this;
  16944. }
  16945. toJSON() {
  16946. const data = super.toJSON();
  16947. data.instanceCount = this.instanceCount;
  16948. data.isInstancedBufferGeometry = true;
  16949. return data;
  16950. }
  16951. }
  16952. class BufferGeometryLoader extends Loader {
  16953. constructor( manager ) {
  16954. super( manager );
  16955. }
  16956. load( url, onLoad, onProgress, onError ) {
  16957. const scope = this;
  16958. const loader = new FileLoader( scope.manager );
  16959. loader.setPath( scope.path );
  16960. loader.setRequestHeader( scope.requestHeader );
  16961. loader.setWithCredentials( scope.withCredentials );
  16962. loader.load( url, function ( text ) {
  16963. try {
  16964. onLoad( scope.parse( JSON.parse( text ) ) );
  16965. } catch ( e ) {
  16966. if ( onError ) {
  16967. onError( e );
  16968. } else {
  16969. console.error( e );
  16970. }
  16971. scope.manager.itemError( url );
  16972. }
  16973. }, onProgress, onError );
  16974. }
  16975. parse( json ) {
  16976. const interleavedBufferMap = {};
  16977. const arrayBufferMap = {};
  16978. function getInterleavedBuffer( json, uuid ) {
  16979. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  16980. const interleavedBuffers = json.interleavedBuffers;
  16981. const interleavedBuffer = interleavedBuffers[ uuid ];
  16982. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  16983. const array = getTypedArray( interleavedBuffer.type, buffer );
  16984. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  16985. ib.uuid = interleavedBuffer.uuid;
  16986. interleavedBufferMap[ uuid ] = ib;
  16987. return ib;
  16988. }
  16989. function getArrayBuffer( json, uuid ) {
  16990. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  16991. const arrayBuffers = json.arrayBuffers;
  16992. const arrayBuffer = arrayBuffers[ uuid ];
  16993. const ab = new Uint32Array( arrayBuffer ).buffer;
  16994. arrayBufferMap[ uuid ] = ab;
  16995. return ab;
  16996. }
  16997. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  16998. const index = json.data.index;
  16999. if ( index !== undefined ) {
  17000. const typedArray = getTypedArray( index.type, index.array );
  17001. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  17002. }
  17003. const attributes = json.data.attributes;
  17004. for ( const key in attributes ) {
  17005. const attribute = attributes[ key ];
  17006. let bufferAttribute;
  17007. if ( attribute.isInterleavedBufferAttribute ) {
  17008. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17009. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17010. } else {
  17011. const typedArray = getTypedArray( attribute.type, attribute.array );
  17012. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  17013. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  17014. }
  17015. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17016. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  17017. geometry.setAttribute( key, bufferAttribute );
  17018. }
  17019. const morphAttributes = json.data.morphAttributes;
  17020. if ( morphAttributes ) {
  17021. for ( const key in morphAttributes ) {
  17022. const attributeArray = morphAttributes[ key ];
  17023. const array = [];
  17024. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  17025. const attribute = attributeArray[ i ];
  17026. let bufferAttribute;
  17027. if ( attribute.isInterleavedBufferAttribute ) {
  17028. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17029. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17030. } else {
  17031. const typedArray = getTypedArray( attribute.type, attribute.array );
  17032. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  17033. }
  17034. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17035. array.push( bufferAttribute );
  17036. }
  17037. geometry.morphAttributes[ key ] = array;
  17038. }
  17039. }
  17040. const morphTargetsRelative = json.data.morphTargetsRelative;
  17041. if ( morphTargetsRelative ) {
  17042. geometry.morphTargetsRelative = true;
  17043. }
  17044. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  17045. if ( groups !== undefined ) {
  17046. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  17047. const group = groups[ i ];
  17048. geometry.addGroup( group.start, group.count, group.materialIndex );
  17049. }
  17050. }
  17051. const boundingSphere = json.data.boundingSphere;
  17052. if ( boundingSphere !== undefined ) {
  17053. const center = new Vector3();
  17054. if ( boundingSphere.center !== undefined ) {
  17055. center.fromArray( boundingSphere.center );
  17056. }
  17057. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17058. }
  17059. if ( json.name ) geometry.name = json.name;
  17060. if ( json.userData ) geometry.userData = json.userData;
  17061. return geometry;
  17062. }
  17063. }
  17064. class ObjectLoader extends Loader {
  17065. constructor( manager ) {
  17066. super( manager );
  17067. }
  17068. load( url, onLoad, onProgress, onError ) {
  17069. const scope = this;
  17070. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17071. this.resourcePath = this.resourcePath || path;
  17072. const loader = new FileLoader( this.manager );
  17073. loader.setPath( this.path );
  17074. loader.setRequestHeader( this.requestHeader );
  17075. loader.setWithCredentials( this.withCredentials );
  17076. loader.load( url, function ( text ) {
  17077. let json = null;
  17078. try {
  17079. json = JSON.parse( text );
  17080. } catch ( error ) {
  17081. if ( onError !== undefined ) onError( error );
  17082. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17083. return;
  17084. }
  17085. const metadata = json.metadata;
  17086. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17087. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17088. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17089. return;
  17090. }
  17091. scope.parse( json, onLoad );
  17092. }, onProgress, onError );
  17093. }
  17094. async loadAsync( url, onProgress ) {
  17095. const scope = this;
  17096. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17097. this.resourcePath = this.resourcePath || path;
  17098. const loader = new FileLoader( this.manager );
  17099. loader.setPath( this.path );
  17100. loader.setRequestHeader( this.requestHeader );
  17101. loader.setWithCredentials( this.withCredentials );
  17102. const text = await loader.loadAsync( url, onProgress );
  17103. const json = JSON.parse( text );
  17104. const metadata = json.metadata;
  17105. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17106. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17107. }
  17108. return await scope.parseAsync( json );
  17109. }
  17110. parse( json, onLoad ) {
  17111. const animations = this.parseAnimations( json.animations );
  17112. const shapes = this.parseShapes( json.shapes );
  17113. const geometries = this.parseGeometries( json.geometries, shapes );
  17114. const images = this.parseImages( json.images, function () {
  17115. if ( onLoad !== undefined ) onLoad( object );
  17116. } );
  17117. const textures = this.parseTextures( json.textures, images );
  17118. const materials = this.parseMaterials( json.materials, textures );
  17119. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17120. const skeletons = this.parseSkeletons( json.skeletons, object );
  17121. this.bindSkeletons( object, skeletons );
  17122. this.bindLightTargets( object );
  17123. //
  17124. if ( onLoad !== undefined ) {
  17125. let hasImages = false;
  17126. for ( const uuid in images ) {
  17127. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17128. hasImages = true;
  17129. break;
  17130. }
  17131. }
  17132. if ( hasImages === false ) onLoad( object );
  17133. }
  17134. return object;
  17135. }
  17136. async parseAsync( json ) {
  17137. const animations = this.parseAnimations( json.animations );
  17138. const shapes = this.parseShapes( json.shapes );
  17139. const geometries = this.parseGeometries( json.geometries, shapes );
  17140. const images = await this.parseImagesAsync( json.images );
  17141. const textures = this.parseTextures( json.textures, images );
  17142. const materials = this.parseMaterials( json.materials, textures );
  17143. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17144. const skeletons = this.parseSkeletons( json.skeletons, object );
  17145. this.bindSkeletons( object, skeletons );
  17146. this.bindLightTargets( object );
  17147. return object;
  17148. }
  17149. parseShapes( json ) {
  17150. const shapes = {};
  17151. if ( json !== undefined ) {
  17152. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17153. const shape = new Shape().fromJSON( json[ i ] );
  17154. shapes[ shape.uuid ] = shape;
  17155. }
  17156. }
  17157. return shapes;
  17158. }
  17159. parseSkeletons( json, object ) {
  17160. const skeletons = {};
  17161. const bones = {};
  17162. // generate bone lookup table
  17163. object.traverse( function ( child ) {
  17164. if ( child.isBone ) bones[ child.uuid ] = child;
  17165. } );
  17166. // create skeletons
  17167. if ( json !== undefined ) {
  17168. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17169. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17170. skeletons[ skeleton.uuid ] = skeleton;
  17171. }
  17172. }
  17173. return skeletons;
  17174. }
  17175. parseGeometries( json, shapes ) {
  17176. const geometries = {};
  17177. if ( json !== undefined ) {
  17178. const bufferGeometryLoader = new BufferGeometryLoader();
  17179. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17180. let geometry;
  17181. const data = json[ i ];
  17182. switch ( data.type ) {
  17183. case 'BufferGeometry':
  17184. case 'InstancedBufferGeometry':
  17185. geometry = bufferGeometryLoader.parse( data );
  17186. break;
  17187. default:
  17188. if ( data.type in Geometries$1 ) {
  17189. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17190. } else {
  17191. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17192. }
  17193. }
  17194. geometry.uuid = data.uuid;
  17195. if ( data.name !== undefined ) geometry.name = data.name;
  17196. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17197. geometries[ data.uuid ] = geometry;
  17198. }
  17199. }
  17200. return geometries;
  17201. }
  17202. parseMaterials( json, textures ) {
  17203. const cache = {}; // MultiMaterial
  17204. const materials = {};
  17205. if ( json !== undefined ) {
  17206. const loader = new MaterialLoader();
  17207. loader.setTextures( textures );
  17208. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17209. const data = json[ i ];
  17210. if ( cache[ data.uuid ] === undefined ) {
  17211. cache[ data.uuid ] = loader.parse( data );
  17212. }
  17213. materials[ data.uuid ] = cache[ data.uuid ];
  17214. }
  17215. }
  17216. return materials;
  17217. }
  17218. parseAnimations( json ) {
  17219. const animations = {};
  17220. if ( json !== undefined ) {
  17221. for ( let i = 0; i < json.length; i ++ ) {
  17222. const data = json[ i ];
  17223. const clip = AnimationClip.parse( data );
  17224. animations[ clip.uuid ] = clip;
  17225. }
  17226. }
  17227. return animations;
  17228. }
  17229. parseImages( json, onLoad ) {
  17230. const scope = this;
  17231. const images = {};
  17232. let loader;
  17233. function loadImage( url ) {
  17234. scope.manager.itemStart( url );
  17235. return loader.load( url, function () {
  17236. scope.manager.itemEnd( url );
  17237. }, undefined, function () {
  17238. scope.manager.itemError( url );
  17239. scope.manager.itemEnd( url );
  17240. } );
  17241. }
  17242. function deserializeImage( image ) {
  17243. if ( typeof image === 'string' ) {
  17244. const url = image;
  17245. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17246. return loadImage( path );
  17247. } else {
  17248. if ( image.data ) {
  17249. return {
  17250. data: getTypedArray( image.type, image.data ),
  17251. width: image.width,
  17252. height: image.height
  17253. };
  17254. } else {
  17255. return null;
  17256. }
  17257. }
  17258. }
  17259. if ( json !== undefined && json.length > 0 ) {
  17260. const manager = new LoadingManager( onLoad );
  17261. loader = new ImageLoader( manager );
  17262. loader.setCrossOrigin( this.crossOrigin );
  17263. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17264. const image = json[ i ];
  17265. const url = image.url;
  17266. if ( Array.isArray( url ) ) {
  17267. // load array of images e.g CubeTexture
  17268. const imageArray = [];
  17269. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17270. const currentUrl = url[ j ];
  17271. const deserializedImage = deserializeImage( currentUrl );
  17272. if ( deserializedImage !== null ) {
  17273. if ( deserializedImage instanceof HTMLImageElement ) {
  17274. imageArray.push( deserializedImage );
  17275. } else {
  17276. // special case: handle array of data textures for cube textures
  17277. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17278. }
  17279. }
  17280. }
  17281. images[ image.uuid ] = new Source( imageArray );
  17282. } else {
  17283. // load single image
  17284. const deserializedImage = deserializeImage( image.url );
  17285. images[ image.uuid ] = new Source( deserializedImage );
  17286. }
  17287. }
  17288. }
  17289. return images;
  17290. }
  17291. async parseImagesAsync( json ) {
  17292. const scope = this;
  17293. const images = {};
  17294. let loader;
  17295. async function deserializeImage( image ) {
  17296. if ( typeof image === 'string' ) {
  17297. const url = image;
  17298. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17299. return await loader.loadAsync( path );
  17300. } else {
  17301. if ( image.data ) {
  17302. return {
  17303. data: getTypedArray( image.type, image.data ),
  17304. width: image.width,
  17305. height: image.height
  17306. };
  17307. } else {
  17308. return null;
  17309. }
  17310. }
  17311. }
  17312. if ( json !== undefined && json.length > 0 ) {
  17313. loader = new ImageLoader( this.manager );
  17314. loader.setCrossOrigin( this.crossOrigin );
  17315. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17316. const image = json[ i ];
  17317. const url = image.url;
  17318. if ( Array.isArray( url ) ) {
  17319. // load array of images e.g CubeTexture
  17320. const imageArray = [];
  17321. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17322. const currentUrl = url[ j ];
  17323. const deserializedImage = await deserializeImage( currentUrl );
  17324. if ( deserializedImage !== null ) {
  17325. if ( deserializedImage instanceof HTMLImageElement ) {
  17326. imageArray.push( deserializedImage );
  17327. } else {
  17328. // special case: handle array of data textures for cube textures
  17329. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17330. }
  17331. }
  17332. }
  17333. images[ image.uuid ] = new Source( imageArray );
  17334. } else {
  17335. // load single image
  17336. const deserializedImage = await deserializeImage( image.url );
  17337. images[ image.uuid ] = new Source( deserializedImage );
  17338. }
  17339. }
  17340. }
  17341. return images;
  17342. }
  17343. parseTextures( json, images ) {
  17344. function parseConstant( value, type ) {
  17345. if ( typeof value === 'number' ) return value;
  17346. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17347. return type[ value ];
  17348. }
  17349. const textures = {};
  17350. if ( json !== undefined ) {
  17351. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17352. const data = json[ i ];
  17353. if ( data.image === undefined ) {
  17354. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17355. }
  17356. if ( images[ data.image ] === undefined ) {
  17357. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17358. }
  17359. const source = images[ data.image ];
  17360. const image = source.data;
  17361. let texture;
  17362. if ( Array.isArray( image ) ) {
  17363. texture = new CubeTexture();
  17364. if ( image.length === 6 ) texture.needsUpdate = true;
  17365. } else {
  17366. if ( image && image.data ) {
  17367. texture = new DataTexture();
  17368. } else {
  17369. texture = new Texture();
  17370. }
  17371. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17372. }
  17373. texture.source = source;
  17374. texture.uuid = data.uuid;
  17375. if ( data.name !== undefined ) texture.name = data.name;
  17376. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17377. if ( data.channel !== undefined ) texture.channel = data.channel;
  17378. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17379. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17380. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17381. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17382. if ( data.wrap !== undefined ) {
  17383. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17384. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17385. }
  17386. if ( data.format !== undefined ) texture.format = data.format;
  17387. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17388. if ( data.type !== undefined ) texture.type = data.type;
  17389. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17390. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17391. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17392. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17393. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17394. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17395. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17396. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17397. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17398. if ( data.userData !== undefined ) texture.userData = data.userData;
  17399. textures[ data.uuid ] = texture;
  17400. }
  17401. }
  17402. return textures;
  17403. }
  17404. parseObject( data, geometries, materials, textures, animations ) {
  17405. let object;
  17406. function getGeometry( name ) {
  17407. if ( geometries[ name ] === undefined ) {
  17408. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17409. }
  17410. return geometries[ name ];
  17411. }
  17412. function getMaterial( name ) {
  17413. if ( name === undefined ) return undefined;
  17414. if ( Array.isArray( name ) ) {
  17415. const array = [];
  17416. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17417. const uuid = name[ i ];
  17418. if ( materials[ uuid ] === undefined ) {
  17419. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17420. }
  17421. array.push( materials[ uuid ] );
  17422. }
  17423. return array;
  17424. }
  17425. if ( materials[ name ] === undefined ) {
  17426. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17427. }
  17428. return materials[ name ];
  17429. }
  17430. function getTexture( uuid ) {
  17431. if ( textures[ uuid ] === undefined ) {
  17432. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17433. }
  17434. return textures[ uuid ];
  17435. }
  17436. let geometry, material;
  17437. switch ( data.type ) {
  17438. case 'Scene':
  17439. object = new Scene();
  17440. if ( data.background !== undefined ) {
  17441. if ( Number.isInteger( data.background ) ) {
  17442. object.background = new Color( data.background );
  17443. } else {
  17444. object.background = getTexture( data.background );
  17445. }
  17446. }
  17447. if ( data.environment !== undefined ) {
  17448. object.environment = getTexture( data.environment );
  17449. }
  17450. if ( data.fog !== undefined ) {
  17451. if ( data.fog.type === 'Fog' ) {
  17452. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17453. } else if ( data.fog.type === 'FogExp2' ) {
  17454. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17455. }
  17456. if ( data.fog.name !== '' ) {
  17457. object.fog.name = data.fog.name;
  17458. }
  17459. }
  17460. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17461. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17462. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17463. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17464. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17465. break;
  17466. case 'PerspectiveCamera':
  17467. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17468. if ( data.focus !== undefined ) object.focus = data.focus;
  17469. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17470. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17471. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17472. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17473. break;
  17474. case 'OrthographicCamera':
  17475. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17476. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17477. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17478. break;
  17479. case 'AmbientLight':
  17480. object = new AmbientLight( data.color, data.intensity );
  17481. break;
  17482. case 'DirectionalLight':
  17483. object = new DirectionalLight( data.color, data.intensity );
  17484. object.target = data.target || '';
  17485. break;
  17486. case 'PointLight':
  17487. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17488. break;
  17489. case 'RectAreaLight':
  17490. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17491. break;
  17492. case 'SpotLight':
  17493. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17494. object.target = data.target || '';
  17495. break;
  17496. case 'HemisphereLight':
  17497. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17498. break;
  17499. case 'LightProbe':
  17500. object = new LightProbe().fromJSON( data );
  17501. break;
  17502. case 'SkinnedMesh':
  17503. geometry = getGeometry( data.geometry );
  17504. material = getMaterial( data.material );
  17505. object = new SkinnedMesh( geometry, material );
  17506. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17507. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17508. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17509. break;
  17510. case 'Mesh':
  17511. geometry = getGeometry( data.geometry );
  17512. material = getMaterial( data.material );
  17513. object = new Mesh( geometry, material );
  17514. break;
  17515. case 'InstancedMesh':
  17516. geometry = getGeometry( data.geometry );
  17517. material = getMaterial( data.material );
  17518. const count = data.count;
  17519. const instanceMatrix = data.instanceMatrix;
  17520. const instanceColor = data.instanceColor;
  17521. object = new InstancedMesh( geometry, material, count );
  17522. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17523. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17524. break;
  17525. case 'BatchedMesh':
  17526. geometry = getGeometry( data.geometry );
  17527. material = getMaterial( data.material );
  17528. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17529. object.geometry = geometry;
  17530. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17531. object.sortObjects = data.sortObjects;
  17532. object._drawRanges = data.drawRanges;
  17533. object._reservedRanges = data.reservedRanges;
  17534. object._visibility = data.visibility;
  17535. object._active = data.active;
  17536. object._bounds = data.bounds.map( bound => {
  17537. const box = new Box3();
  17538. box.min.fromArray( bound.boxMin );
  17539. box.max.fromArray( bound.boxMax );
  17540. const sphere = new Sphere();
  17541. sphere.radius = bound.sphereRadius;
  17542. sphere.center.fromArray( bound.sphereCenter );
  17543. return {
  17544. boxInitialized: bound.boxInitialized,
  17545. box: box,
  17546. sphereInitialized: bound.sphereInitialized,
  17547. sphere: sphere
  17548. };
  17549. } );
  17550. object._maxInstanceCount = data.maxInstanceCount;
  17551. object._maxVertexCount = data.maxVertexCount;
  17552. object._maxIndexCount = data.maxIndexCount;
  17553. object._geometryInitialized = data.geometryInitialized;
  17554. object._geometryCount = data.geometryCount;
  17555. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17556. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17557. break;
  17558. case 'LOD':
  17559. object = new LOD();
  17560. break;
  17561. case 'Line':
  17562. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17563. break;
  17564. case 'LineLoop':
  17565. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17566. break;
  17567. case 'LineSegments':
  17568. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17569. break;
  17570. case 'PointCloud':
  17571. case 'Points':
  17572. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17573. break;
  17574. case 'Sprite':
  17575. object = new Sprite( getMaterial( data.material ) );
  17576. break;
  17577. case 'Group':
  17578. object = new Group();
  17579. break;
  17580. case 'Bone':
  17581. object = new Bone();
  17582. break;
  17583. default:
  17584. object = new Object3D();
  17585. }
  17586. object.uuid = data.uuid;
  17587. if ( data.name !== undefined ) object.name = data.name;
  17588. if ( data.matrix !== undefined ) {
  17589. object.matrix.fromArray( data.matrix );
  17590. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17591. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17592. } else {
  17593. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17594. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17595. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17596. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17597. }
  17598. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17599. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17600. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17601. if ( data.shadow ) {
  17602. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17603. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17604. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17605. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17606. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17607. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17608. }
  17609. if ( data.visible !== undefined ) object.visible = data.visible;
  17610. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17611. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17612. if ( data.userData !== undefined ) object.userData = data.userData;
  17613. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17614. if ( data.children !== undefined ) {
  17615. const children = data.children;
  17616. for ( let i = 0; i < children.length; i ++ ) {
  17617. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17618. }
  17619. }
  17620. if ( data.animations !== undefined ) {
  17621. const objectAnimations = data.animations;
  17622. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17623. const uuid = objectAnimations[ i ];
  17624. object.animations.push( animations[ uuid ] );
  17625. }
  17626. }
  17627. if ( data.type === 'LOD' ) {
  17628. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17629. const levels = data.levels;
  17630. for ( let l = 0; l < levels.length; l ++ ) {
  17631. const level = levels[ l ];
  17632. const child = object.getObjectByProperty( 'uuid', level.object );
  17633. if ( child !== undefined ) {
  17634. object.addLevel( child, level.distance, level.hysteresis );
  17635. }
  17636. }
  17637. }
  17638. return object;
  17639. }
  17640. bindSkeletons( object, skeletons ) {
  17641. if ( Object.keys( skeletons ).length === 0 ) return;
  17642. object.traverse( function ( child ) {
  17643. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17644. const skeleton = skeletons[ child.skeleton ];
  17645. if ( skeleton === undefined ) {
  17646. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17647. } else {
  17648. child.bind( skeleton, child.bindMatrix );
  17649. }
  17650. }
  17651. } );
  17652. }
  17653. bindLightTargets( object ) {
  17654. object.traverse( function ( child ) {
  17655. if ( child.isDirectionalLight || child.isSpotLight ) {
  17656. const uuid = child.target;
  17657. const target = object.getObjectByProperty( 'uuid', uuid );
  17658. if ( target !== undefined ) {
  17659. child.target = target;
  17660. } else {
  17661. child.target = new Object3D();
  17662. }
  17663. }
  17664. } );
  17665. }
  17666. }
  17667. const TEXTURE_MAPPING = {
  17668. UVMapping: UVMapping,
  17669. CubeReflectionMapping: CubeReflectionMapping,
  17670. CubeRefractionMapping: CubeRefractionMapping,
  17671. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17672. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17673. CubeUVReflectionMapping: CubeUVReflectionMapping
  17674. };
  17675. const TEXTURE_WRAPPING = {
  17676. RepeatWrapping: RepeatWrapping,
  17677. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17678. MirroredRepeatWrapping: MirroredRepeatWrapping
  17679. };
  17680. const TEXTURE_FILTER = {
  17681. NearestFilter: NearestFilter,
  17682. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17683. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17684. LinearFilter: LinearFilter,
  17685. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17686. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17687. };
  17688. class ImageBitmapLoader extends Loader {
  17689. constructor( manager ) {
  17690. super( manager );
  17691. this.isImageBitmapLoader = true;
  17692. if ( typeof createImageBitmap === 'undefined' ) {
  17693. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17694. }
  17695. if ( typeof fetch === 'undefined' ) {
  17696. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17697. }
  17698. this.options = { premultiplyAlpha: 'none' };
  17699. }
  17700. setOptions( options ) {
  17701. this.options = options;
  17702. return this;
  17703. }
  17704. load( url, onLoad, onProgress, onError ) {
  17705. if ( url === undefined ) url = '';
  17706. if ( this.path !== undefined ) url = this.path + url;
  17707. url = this.manager.resolveURL( url );
  17708. const scope = this;
  17709. const cached = Cache.get( url );
  17710. if ( cached !== undefined ) {
  17711. scope.manager.itemStart( url );
  17712. // If cached is a promise, wait for it to resolve
  17713. if ( cached.then ) {
  17714. cached.then( imageBitmap => {
  17715. if ( onLoad ) onLoad( imageBitmap );
  17716. scope.manager.itemEnd( url );
  17717. } ).catch( e => {
  17718. if ( onError ) onError( e );
  17719. } );
  17720. return;
  17721. }
  17722. // If cached is not a promise (i.e., it's already an imageBitmap)
  17723. setTimeout( function () {
  17724. if ( onLoad ) onLoad( cached );
  17725. scope.manager.itemEnd( url );
  17726. }, 0 );
  17727. return cached;
  17728. }
  17729. const fetchOptions = {};
  17730. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17731. fetchOptions.headers = this.requestHeader;
  17732. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17733. return res.blob();
  17734. } ).then( function ( blob ) {
  17735. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17736. } ).then( function ( imageBitmap ) {
  17737. Cache.add( url, imageBitmap );
  17738. if ( onLoad ) onLoad( imageBitmap );
  17739. scope.manager.itemEnd( url );
  17740. return imageBitmap;
  17741. } ).catch( function ( e ) {
  17742. if ( onError ) onError( e );
  17743. Cache.remove( url );
  17744. scope.manager.itemError( url );
  17745. scope.manager.itemEnd( url );
  17746. } );
  17747. Cache.add( url, promise );
  17748. scope.manager.itemStart( url );
  17749. }
  17750. }
  17751. let _context;
  17752. class AudioContext {
  17753. static getContext() {
  17754. if ( _context === undefined ) {
  17755. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17756. }
  17757. return _context;
  17758. }
  17759. static setContext( value ) {
  17760. _context = value;
  17761. }
  17762. }
  17763. class AudioLoader extends Loader {
  17764. constructor( manager ) {
  17765. super( manager );
  17766. }
  17767. load( url, onLoad, onProgress, onError ) {
  17768. const scope = this;
  17769. const loader = new FileLoader( this.manager );
  17770. loader.setResponseType( 'arraybuffer' );
  17771. loader.setPath( this.path );
  17772. loader.setRequestHeader( this.requestHeader );
  17773. loader.setWithCredentials( this.withCredentials );
  17774. loader.load( url, function ( buffer ) {
  17775. try {
  17776. // Create a copy of the buffer. The `decodeAudioData` method
  17777. // detaches the buffer when complete, preventing reuse.
  17778. const bufferCopy = buffer.slice( 0 );
  17779. const context = AudioContext.getContext();
  17780. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  17781. onLoad( audioBuffer );
  17782. } ).catch( handleError );
  17783. } catch ( e ) {
  17784. handleError( e );
  17785. }
  17786. }, onProgress, onError );
  17787. function handleError( e ) {
  17788. if ( onError ) {
  17789. onError( e );
  17790. } else {
  17791. console.error( e );
  17792. }
  17793. scope.manager.itemError( url );
  17794. }
  17795. }
  17796. }
  17797. const _eyeRight = /*@__PURE__*/ new Matrix4();
  17798. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  17799. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  17800. class StereoCamera {
  17801. constructor() {
  17802. this.type = 'StereoCamera';
  17803. this.aspect = 1;
  17804. this.eyeSep = 0.064;
  17805. this.cameraL = new PerspectiveCamera();
  17806. this.cameraL.layers.enable( 1 );
  17807. this.cameraL.matrixAutoUpdate = false;
  17808. this.cameraR = new PerspectiveCamera();
  17809. this.cameraR.layers.enable( 2 );
  17810. this.cameraR.matrixAutoUpdate = false;
  17811. this._cache = {
  17812. focus: null,
  17813. fov: null,
  17814. aspect: null,
  17815. near: null,
  17816. far: null,
  17817. zoom: null,
  17818. eyeSep: null
  17819. };
  17820. }
  17821. update( camera ) {
  17822. const cache = this._cache;
  17823. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  17824. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  17825. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  17826. if ( needsUpdate ) {
  17827. cache.focus = camera.focus;
  17828. cache.fov = camera.fov;
  17829. cache.aspect = camera.aspect * this.aspect;
  17830. cache.near = camera.near;
  17831. cache.far = camera.far;
  17832. cache.zoom = camera.zoom;
  17833. cache.eyeSep = this.eyeSep;
  17834. // Off-axis stereoscopic effect based on
  17835. // http://paulbourke.net/stereographics/stereorender/
  17836. _projectionMatrix.copy( camera.projectionMatrix );
  17837. const eyeSepHalf = cache.eyeSep / 2;
  17838. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  17839. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  17840. let xmin, xmax;
  17841. // translate xOffset
  17842. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  17843. _eyeRight.elements[ 12 ] = eyeSepHalf;
  17844. // for left eye
  17845. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  17846. xmax = ymax * cache.aspect + eyeSepOnProjection;
  17847. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17848. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17849. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  17850. // for right eye
  17851. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  17852. xmax = ymax * cache.aspect - eyeSepOnProjection;
  17853. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  17854. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  17855. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  17856. }
  17857. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  17858. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  17859. }
  17860. }
  17861. class ArrayCamera extends PerspectiveCamera {
  17862. constructor( array = [] ) {
  17863. super();
  17864. this.isArrayCamera = true;
  17865. this.cameras = array;
  17866. }
  17867. }
  17868. class Clock {
  17869. constructor( autoStart = true ) {
  17870. this.autoStart = autoStart;
  17871. this.startTime = 0;
  17872. this.oldTime = 0;
  17873. this.elapsedTime = 0;
  17874. this.running = false;
  17875. }
  17876. start() {
  17877. this.startTime = now();
  17878. this.oldTime = this.startTime;
  17879. this.elapsedTime = 0;
  17880. this.running = true;
  17881. }
  17882. stop() {
  17883. this.getElapsedTime();
  17884. this.running = false;
  17885. this.autoStart = false;
  17886. }
  17887. getElapsedTime() {
  17888. this.getDelta();
  17889. return this.elapsedTime;
  17890. }
  17891. getDelta() {
  17892. let diff = 0;
  17893. if ( this.autoStart && ! this.running ) {
  17894. this.start();
  17895. return 0;
  17896. }
  17897. if ( this.running ) {
  17898. const newTime = now();
  17899. diff = ( newTime - this.oldTime ) / 1000;
  17900. this.oldTime = newTime;
  17901. this.elapsedTime += diff;
  17902. }
  17903. return diff;
  17904. }
  17905. }
  17906. function now() {
  17907. return performance.now();
  17908. }
  17909. const _position$1 = /*@__PURE__*/ new Vector3();
  17910. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  17911. const _scale$1 = /*@__PURE__*/ new Vector3();
  17912. const _orientation$1 = /*@__PURE__*/ new Vector3();
  17913. class AudioListener extends Object3D {
  17914. constructor() {
  17915. super();
  17916. this.type = 'AudioListener';
  17917. this.context = AudioContext.getContext();
  17918. this.gain = this.context.createGain();
  17919. this.gain.connect( this.context.destination );
  17920. this.filter = null;
  17921. this.timeDelta = 0;
  17922. // private
  17923. this._clock = new Clock();
  17924. }
  17925. getInput() {
  17926. return this.gain;
  17927. }
  17928. removeFilter() {
  17929. if ( this.filter !== null ) {
  17930. this.gain.disconnect( this.filter );
  17931. this.filter.disconnect( this.context.destination );
  17932. this.gain.connect( this.context.destination );
  17933. this.filter = null;
  17934. }
  17935. return this;
  17936. }
  17937. getFilter() {
  17938. return this.filter;
  17939. }
  17940. setFilter( value ) {
  17941. if ( this.filter !== null ) {
  17942. this.gain.disconnect( this.filter );
  17943. this.filter.disconnect( this.context.destination );
  17944. } else {
  17945. this.gain.disconnect( this.context.destination );
  17946. }
  17947. this.filter = value;
  17948. this.gain.connect( this.filter );
  17949. this.filter.connect( this.context.destination );
  17950. return this;
  17951. }
  17952. getMasterVolume() {
  17953. return this.gain.gain.value;
  17954. }
  17955. setMasterVolume( value ) {
  17956. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  17957. return this;
  17958. }
  17959. updateMatrixWorld( force ) {
  17960. super.updateMatrixWorld( force );
  17961. const listener = this.context.listener;
  17962. const up = this.up;
  17963. this.timeDelta = this._clock.getDelta();
  17964. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  17965. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  17966. if ( listener.positionX ) {
  17967. // code path for Chrome (see #14393)
  17968. const endTime = this.context.currentTime + this.timeDelta;
  17969. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  17970. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  17971. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  17972. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  17973. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  17974. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  17975. listener.upX.linearRampToValueAtTime( up.x, endTime );
  17976. listener.upY.linearRampToValueAtTime( up.y, endTime );
  17977. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  17978. } else {
  17979. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  17980. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  17981. }
  17982. }
  17983. }
  17984. class Audio extends Object3D {
  17985. constructor( listener ) {
  17986. super();
  17987. this.type = 'Audio';
  17988. this.listener = listener;
  17989. this.context = listener.context;
  17990. this.gain = this.context.createGain();
  17991. this.gain.connect( listener.getInput() );
  17992. this.autoplay = false;
  17993. this.buffer = null;
  17994. this.detune = 0;
  17995. this.loop = false;
  17996. this.loopStart = 0;
  17997. this.loopEnd = 0;
  17998. this.offset = 0;
  17999. this.duration = undefined;
  18000. this.playbackRate = 1;
  18001. this.isPlaying = false;
  18002. this.hasPlaybackControl = true;
  18003. this.source = null;
  18004. this.sourceType = 'empty';
  18005. this._startedAt = 0;
  18006. this._progress = 0;
  18007. this._connected = false;
  18008. this.filters = [];
  18009. }
  18010. getOutput() {
  18011. return this.gain;
  18012. }
  18013. setNodeSource( audioNode ) {
  18014. this.hasPlaybackControl = false;
  18015. this.sourceType = 'audioNode';
  18016. this.source = audioNode;
  18017. this.connect();
  18018. return this;
  18019. }
  18020. setMediaElementSource( mediaElement ) {
  18021. this.hasPlaybackControl = false;
  18022. this.sourceType = 'mediaNode';
  18023. this.source = this.context.createMediaElementSource( mediaElement );
  18024. this.connect();
  18025. return this;
  18026. }
  18027. setMediaStreamSource( mediaStream ) {
  18028. this.hasPlaybackControl = false;
  18029. this.sourceType = 'mediaStreamNode';
  18030. this.source = this.context.createMediaStreamSource( mediaStream );
  18031. this.connect();
  18032. return this;
  18033. }
  18034. setBuffer( audioBuffer ) {
  18035. this.buffer = audioBuffer;
  18036. this.sourceType = 'buffer';
  18037. if ( this.autoplay ) this.play();
  18038. return this;
  18039. }
  18040. play( delay = 0 ) {
  18041. if ( this.isPlaying === true ) {
  18042. console.warn( 'THREE.Audio: Audio is already playing.' );
  18043. return;
  18044. }
  18045. if ( this.hasPlaybackControl === false ) {
  18046. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18047. return;
  18048. }
  18049. this._startedAt = this.context.currentTime + delay;
  18050. const source = this.context.createBufferSource();
  18051. source.buffer = this.buffer;
  18052. source.loop = this.loop;
  18053. source.loopStart = this.loopStart;
  18054. source.loopEnd = this.loopEnd;
  18055. source.onended = this.onEnded.bind( this );
  18056. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18057. this.isPlaying = true;
  18058. this.source = source;
  18059. this.setDetune( this.detune );
  18060. this.setPlaybackRate( this.playbackRate );
  18061. return this.connect();
  18062. }
  18063. pause() {
  18064. if ( this.hasPlaybackControl === false ) {
  18065. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18066. return;
  18067. }
  18068. if ( this.isPlaying === true ) {
  18069. // update current progress
  18070. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18071. if ( this.loop === true ) {
  18072. // ensure _progress does not exceed duration with looped audios
  18073. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18074. }
  18075. this.source.stop();
  18076. this.source.onended = null;
  18077. this.isPlaying = false;
  18078. }
  18079. return this;
  18080. }
  18081. stop( delay = 0 ) {
  18082. if ( this.hasPlaybackControl === false ) {
  18083. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18084. return;
  18085. }
  18086. this._progress = 0;
  18087. if ( this.source !== null ) {
  18088. this.source.stop( this.context.currentTime + delay );
  18089. this.source.onended = null;
  18090. }
  18091. this.isPlaying = false;
  18092. return this;
  18093. }
  18094. connect() {
  18095. if ( this.filters.length > 0 ) {
  18096. this.source.connect( this.filters[ 0 ] );
  18097. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18098. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18099. }
  18100. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18101. } else {
  18102. this.source.connect( this.getOutput() );
  18103. }
  18104. this._connected = true;
  18105. return this;
  18106. }
  18107. disconnect() {
  18108. if ( this._connected === false ) {
  18109. return;
  18110. }
  18111. if ( this.filters.length > 0 ) {
  18112. this.source.disconnect( this.filters[ 0 ] );
  18113. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18114. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18115. }
  18116. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18117. } else {
  18118. this.source.disconnect( this.getOutput() );
  18119. }
  18120. this._connected = false;
  18121. return this;
  18122. }
  18123. getFilters() {
  18124. return this.filters;
  18125. }
  18126. setFilters( value ) {
  18127. if ( ! value ) value = [];
  18128. if ( this._connected === true ) {
  18129. this.disconnect();
  18130. this.filters = value.slice();
  18131. this.connect();
  18132. } else {
  18133. this.filters = value.slice();
  18134. }
  18135. return this;
  18136. }
  18137. setDetune( value ) {
  18138. this.detune = value;
  18139. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18140. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18141. }
  18142. return this;
  18143. }
  18144. getDetune() {
  18145. return this.detune;
  18146. }
  18147. getFilter() {
  18148. return this.getFilters()[ 0 ];
  18149. }
  18150. setFilter( filter ) {
  18151. return this.setFilters( filter ? [ filter ] : [] );
  18152. }
  18153. setPlaybackRate( value ) {
  18154. if ( this.hasPlaybackControl === false ) {
  18155. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18156. return;
  18157. }
  18158. this.playbackRate = value;
  18159. if ( this.isPlaying === true ) {
  18160. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18161. }
  18162. return this;
  18163. }
  18164. getPlaybackRate() {
  18165. return this.playbackRate;
  18166. }
  18167. onEnded() {
  18168. this.isPlaying = false;
  18169. }
  18170. getLoop() {
  18171. if ( this.hasPlaybackControl === false ) {
  18172. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18173. return false;
  18174. }
  18175. return this.loop;
  18176. }
  18177. setLoop( value ) {
  18178. if ( this.hasPlaybackControl === false ) {
  18179. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18180. return;
  18181. }
  18182. this.loop = value;
  18183. if ( this.isPlaying === true ) {
  18184. this.source.loop = this.loop;
  18185. }
  18186. return this;
  18187. }
  18188. setLoopStart( value ) {
  18189. this.loopStart = value;
  18190. return this;
  18191. }
  18192. setLoopEnd( value ) {
  18193. this.loopEnd = value;
  18194. return this;
  18195. }
  18196. getVolume() {
  18197. return this.gain.gain.value;
  18198. }
  18199. setVolume( value ) {
  18200. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18201. return this;
  18202. }
  18203. }
  18204. const _position = /*@__PURE__*/ new Vector3();
  18205. const _quaternion = /*@__PURE__*/ new Quaternion();
  18206. const _scale = /*@__PURE__*/ new Vector3();
  18207. const _orientation = /*@__PURE__*/ new Vector3();
  18208. class PositionalAudio extends Audio {
  18209. constructor( listener ) {
  18210. super( listener );
  18211. this.panner = this.context.createPanner();
  18212. this.panner.panningModel = 'HRTF';
  18213. this.panner.connect( this.gain );
  18214. }
  18215. connect() {
  18216. super.connect();
  18217. this.panner.connect( this.gain );
  18218. }
  18219. disconnect() {
  18220. super.disconnect();
  18221. this.panner.disconnect( this.gain );
  18222. }
  18223. getOutput() {
  18224. return this.panner;
  18225. }
  18226. getRefDistance() {
  18227. return this.panner.refDistance;
  18228. }
  18229. setRefDistance( value ) {
  18230. this.panner.refDistance = value;
  18231. return this;
  18232. }
  18233. getRolloffFactor() {
  18234. return this.panner.rolloffFactor;
  18235. }
  18236. setRolloffFactor( value ) {
  18237. this.panner.rolloffFactor = value;
  18238. return this;
  18239. }
  18240. getDistanceModel() {
  18241. return this.panner.distanceModel;
  18242. }
  18243. setDistanceModel( value ) {
  18244. this.panner.distanceModel = value;
  18245. return this;
  18246. }
  18247. getMaxDistance() {
  18248. return this.panner.maxDistance;
  18249. }
  18250. setMaxDistance( value ) {
  18251. this.panner.maxDistance = value;
  18252. return this;
  18253. }
  18254. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18255. this.panner.coneInnerAngle = coneInnerAngle;
  18256. this.panner.coneOuterAngle = coneOuterAngle;
  18257. this.panner.coneOuterGain = coneOuterGain;
  18258. return this;
  18259. }
  18260. updateMatrixWorld( force ) {
  18261. super.updateMatrixWorld( force );
  18262. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18263. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18264. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18265. const panner = this.panner;
  18266. if ( panner.positionX ) {
  18267. // code path for Chrome and Firefox (see #14393)
  18268. const endTime = this.context.currentTime + this.listener.timeDelta;
  18269. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18270. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18271. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18272. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18273. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18274. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18275. } else {
  18276. panner.setPosition( _position.x, _position.y, _position.z );
  18277. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18278. }
  18279. }
  18280. }
  18281. class AudioAnalyser {
  18282. constructor( audio, fftSize = 2048 ) {
  18283. this.analyser = audio.context.createAnalyser();
  18284. this.analyser.fftSize = fftSize;
  18285. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18286. audio.getOutput().connect( this.analyser );
  18287. }
  18288. getFrequencyData() {
  18289. this.analyser.getByteFrequencyData( this.data );
  18290. return this.data;
  18291. }
  18292. getAverageFrequency() {
  18293. let value = 0;
  18294. const data = this.getFrequencyData();
  18295. for ( let i = 0; i < data.length; i ++ ) {
  18296. value += data[ i ];
  18297. }
  18298. return value / data.length;
  18299. }
  18300. }
  18301. class PropertyMixer {
  18302. constructor( binding, typeName, valueSize ) {
  18303. this.binding = binding;
  18304. this.valueSize = valueSize;
  18305. let mixFunction,
  18306. mixFunctionAdditive,
  18307. setIdentity;
  18308. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18309. //
  18310. // interpolators can use .buffer as their .result
  18311. // the data then goes to 'incoming'
  18312. //
  18313. // 'accu0' and 'accu1' are used frame-interleaved for
  18314. // the cumulative result and are compared to detect
  18315. // changes
  18316. //
  18317. // 'orig' stores the original state of the property
  18318. //
  18319. // 'add' is used for additive cumulative results
  18320. //
  18321. // 'work' is optional and is only present for quaternion types. It is used
  18322. // to store intermediate quaternion multiplication results
  18323. switch ( typeName ) {
  18324. case 'quaternion':
  18325. mixFunction = this._slerp;
  18326. mixFunctionAdditive = this._slerpAdditive;
  18327. setIdentity = this._setAdditiveIdentityQuaternion;
  18328. this.buffer = new Float64Array( valueSize * 6 );
  18329. this._workIndex = 5;
  18330. break;
  18331. case 'string':
  18332. case 'bool':
  18333. mixFunction = this._select;
  18334. // Use the regular mix function and for additive on these types,
  18335. // additive is not relevant for non-numeric types
  18336. mixFunctionAdditive = this._select;
  18337. setIdentity = this._setAdditiveIdentityOther;
  18338. this.buffer = new Array( valueSize * 5 );
  18339. break;
  18340. default:
  18341. mixFunction = this._lerp;
  18342. mixFunctionAdditive = this._lerpAdditive;
  18343. setIdentity = this._setAdditiveIdentityNumeric;
  18344. this.buffer = new Float64Array( valueSize * 5 );
  18345. }
  18346. this._mixBufferRegion = mixFunction;
  18347. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18348. this._setIdentity = setIdentity;
  18349. this._origIndex = 3;
  18350. this._addIndex = 4;
  18351. this.cumulativeWeight = 0;
  18352. this.cumulativeWeightAdditive = 0;
  18353. this.useCount = 0;
  18354. this.referenceCount = 0;
  18355. }
  18356. // accumulate data in the 'incoming' region into 'accu<i>'
  18357. accumulate( accuIndex, weight ) {
  18358. // note: happily accumulating nothing when weight = 0, the caller knows
  18359. // the weight and shouldn't have made the call in the first place
  18360. const buffer = this.buffer,
  18361. stride = this.valueSize,
  18362. offset = accuIndex * stride + stride;
  18363. let currentWeight = this.cumulativeWeight;
  18364. if ( currentWeight === 0 ) {
  18365. // accuN := incoming * weight
  18366. for ( let i = 0; i !== stride; ++ i ) {
  18367. buffer[ offset + i ] = buffer[ i ];
  18368. }
  18369. currentWeight = weight;
  18370. } else {
  18371. // accuN := accuN + incoming * weight
  18372. currentWeight += weight;
  18373. const mix = weight / currentWeight;
  18374. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18375. }
  18376. this.cumulativeWeight = currentWeight;
  18377. }
  18378. // accumulate data in the 'incoming' region into 'add'
  18379. accumulateAdditive( weight ) {
  18380. const buffer = this.buffer,
  18381. stride = this.valueSize,
  18382. offset = stride * this._addIndex;
  18383. if ( this.cumulativeWeightAdditive === 0 ) {
  18384. // add = identity
  18385. this._setIdentity();
  18386. }
  18387. // add := add + incoming * weight
  18388. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18389. this.cumulativeWeightAdditive += weight;
  18390. }
  18391. // apply the state of 'accu<i>' to the binding when accus differ
  18392. apply( accuIndex ) {
  18393. const stride = this.valueSize,
  18394. buffer = this.buffer,
  18395. offset = accuIndex * stride + stride,
  18396. weight = this.cumulativeWeight,
  18397. weightAdditive = this.cumulativeWeightAdditive,
  18398. binding = this.binding;
  18399. this.cumulativeWeight = 0;
  18400. this.cumulativeWeightAdditive = 0;
  18401. if ( weight < 1 ) {
  18402. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18403. const originalValueOffset = stride * this._origIndex;
  18404. this._mixBufferRegion(
  18405. buffer, offset, originalValueOffset, 1 - weight, stride );
  18406. }
  18407. if ( weightAdditive > 0 ) {
  18408. // accuN := accuN + additive accuN
  18409. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18410. }
  18411. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18412. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18413. // value has changed -> update scene graph
  18414. binding.setValue( buffer, offset );
  18415. break;
  18416. }
  18417. }
  18418. }
  18419. // remember the state of the bound property and copy it to both accus
  18420. saveOriginalState() {
  18421. const binding = this.binding;
  18422. const buffer = this.buffer,
  18423. stride = this.valueSize,
  18424. originalValueOffset = stride * this._origIndex;
  18425. binding.getValue( buffer, originalValueOffset );
  18426. // accu[0..1] := orig -- initially detect changes against the original
  18427. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18428. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18429. }
  18430. // Add to identity for additive
  18431. this._setIdentity();
  18432. this.cumulativeWeight = 0;
  18433. this.cumulativeWeightAdditive = 0;
  18434. }
  18435. // apply the state previously taken via 'saveOriginalState' to the binding
  18436. restoreOriginalState() {
  18437. const originalValueOffset = this.valueSize * 3;
  18438. this.binding.setValue( this.buffer, originalValueOffset );
  18439. }
  18440. _setAdditiveIdentityNumeric() {
  18441. const startIndex = this._addIndex * this.valueSize;
  18442. const endIndex = startIndex + this.valueSize;
  18443. for ( let i = startIndex; i < endIndex; i ++ ) {
  18444. this.buffer[ i ] = 0;
  18445. }
  18446. }
  18447. _setAdditiveIdentityQuaternion() {
  18448. this._setAdditiveIdentityNumeric();
  18449. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18450. }
  18451. _setAdditiveIdentityOther() {
  18452. const startIndex = this._origIndex * this.valueSize;
  18453. const targetIndex = this._addIndex * this.valueSize;
  18454. for ( let i = 0; i < this.valueSize; i ++ ) {
  18455. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18456. }
  18457. }
  18458. // mix functions
  18459. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18460. if ( t >= 0.5 ) {
  18461. for ( let i = 0; i !== stride; ++ i ) {
  18462. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18463. }
  18464. }
  18465. }
  18466. _slerp( buffer, dstOffset, srcOffset, t ) {
  18467. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18468. }
  18469. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18470. const workOffset = this._workIndex * stride;
  18471. // Store result in intermediate buffer offset
  18472. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18473. // Slerp to the intermediate result
  18474. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18475. }
  18476. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18477. const s = 1 - t;
  18478. for ( let i = 0; i !== stride; ++ i ) {
  18479. const j = dstOffset + i;
  18480. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18481. }
  18482. }
  18483. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18484. for ( let i = 0; i !== stride; ++ i ) {
  18485. const j = dstOffset + i;
  18486. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18487. }
  18488. }
  18489. }
  18490. // Characters [].:/ are reserved for track binding syntax.
  18491. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18492. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18493. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18494. // only latin characters, and the unicode \p{L} is not yet supported. So
  18495. // instead, we exclude reserved characters and match everything else.
  18496. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18497. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18498. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18499. // be matched to parse the rest of the track name.
  18500. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18501. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18502. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18503. // Object on target node, and accessor. May not contain reserved
  18504. // characters. Accessor may contain any character except closing bracket.
  18505. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18506. // Property and accessor. May not contain reserved characters. Accessor may
  18507. // contain any non-bracket characters.
  18508. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18509. const _trackRe = new RegExp( ''
  18510. + '^'
  18511. + _directoryRe
  18512. + _nodeRe
  18513. + _objectRe
  18514. + _propertyRe
  18515. + '$'
  18516. );
  18517. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18518. class Composite {
  18519. constructor( targetGroup, path, optionalParsedPath ) {
  18520. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18521. this._targetGroup = targetGroup;
  18522. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18523. }
  18524. getValue( array, offset ) {
  18525. this.bind(); // bind all binding
  18526. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18527. binding = this._bindings[ firstValidIndex ];
  18528. // and only call .getValue on the first
  18529. if ( binding !== undefined ) binding.getValue( array, offset );
  18530. }
  18531. setValue( array, offset ) {
  18532. const bindings = this._bindings;
  18533. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18534. bindings[ i ].setValue( array, offset );
  18535. }
  18536. }
  18537. bind() {
  18538. const bindings = this._bindings;
  18539. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18540. bindings[ i ].bind();
  18541. }
  18542. }
  18543. unbind() {
  18544. const bindings = this._bindings;
  18545. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18546. bindings[ i ].unbind();
  18547. }
  18548. }
  18549. }
  18550. // Note: This class uses a State pattern on a per-method basis:
  18551. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18552. // prototype version of these methods with one that represents
  18553. // the bound state. When the property is not found, the methods
  18554. // become no-ops.
  18555. class PropertyBinding {
  18556. constructor( rootNode, path, parsedPath ) {
  18557. this.path = path;
  18558. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18559. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18560. this.rootNode = rootNode;
  18561. // initial state of these methods that calls 'bind'
  18562. this.getValue = this._getValue_unbound;
  18563. this.setValue = this._setValue_unbound;
  18564. }
  18565. static create( root, path, parsedPath ) {
  18566. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18567. return new PropertyBinding( root, path, parsedPath );
  18568. } else {
  18569. return new PropertyBinding.Composite( root, path, parsedPath );
  18570. }
  18571. }
  18572. /**
  18573. * Replaces spaces with underscores and removes unsupported characters from
  18574. * node names, to ensure compatibility with parseTrackName().
  18575. *
  18576. * @param {string} name Node name to be sanitized.
  18577. * @return {string}
  18578. */
  18579. static sanitizeNodeName( name ) {
  18580. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18581. }
  18582. static parseTrackName( trackName ) {
  18583. const matches = _trackRe.exec( trackName );
  18584. if ( matches === null ) {
  18585. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18586. }
  18587. const results = {
  18588. // directoryName: matches[ 1 ], // (tschw) currently unused
  18589. nodeName: matches[ 2 ],
  18590. objectName: matches[ 3 ],
  18591. objectIndex: matches[ 4 ],
  18592. propertyName: matches[ 5 ], // required
  18593. propertyIndex: matches[ 6 ]
  18594. };
  18595. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18596. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18597. const objectName = results.nodeName.substring( lastDot + 1 );
  18598. // Object names must be checked against an allowlist. Otherwise, there
  18599. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18600. // 'bar' could be the objectName, or part of a nodeName (which can
  18601. // include '.' characters).
  18602. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18603. results.nodeName = results.nodeName.substring( 0, lastDot );
  18604. results.objectName = objectName;
  18605. }
  18606. }
  18607. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18608. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18609. }
  18610. return results;
  18611. }
  18612. static findNode( root, nodeName ) {
  18613. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18614. return root;
  18615. }
  18616. // search into skeleton bones.
  18617. if ( root.skeleton ) {
  18618. const bone = root.skeleton.getBoneByName( nodeName );
  18619. if ( bone !== undefined ) {
  18620. return bone;
  18621. }
  18622. }
  18623. // search into node subtree.
  18624. if ( root.children ) {
  18625. const searchNodeSubtree = function ( children ) {
  18626. for ( let i = 0; i < children.length; i ++ ) {
  18627. const childNode = children[ i ];
  18628. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18629. return childNode;
  18630. }
  18631. const result = searchNodeSubtree( childNode.children );
  18632. if ( result ) return result;
  18633. }
  18634. return null;
  18635. };
  18636. const subTreeNode = searchNodeSubtree( root.children );
  18637. if ( subTreeNode ) {
  18638. return subTreeNode;
  18639. }
  18640. }
  18641. return null;
  18642. }
  18643. // these are used to "bind" a nonexistent property
  18644. _getValue_unavailable() {}
  18645. _setValue_unavailable() {}
  18646. // Getters
  18647. _getValue_direct( buffer, offset ) {
  18648. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18649. }
  18650. _getValue_array( buffer, offset ) {
  18651. const source = this.resolvedProperty;
  18652. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18653. buffer[ offset ++ ] = source[ i ];
  18654. }
  18655. }
  18656. _getValue_arrayElement( buffer, offset ) {
  18657. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18658. }
  18659. _getValue_toArray( buffer, offset ) {
  18660. this.resolvedProperty.toArray( buffer, offset );
  18661. }
  18662. // Direct
  18663. _setValue_direct( buffer, offset ) {
  18664. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18665. }
  18666. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18667. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18668. this.targetObject.needsUpdate = true;
  18669. }
  18670. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18671. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18672. this.targetObject.matrixWorldNeedsUpdate = true;
  18673. }
  18674. // EntireArray
  18675. _setValue_array( buffer, offset ) {
  18676. const dest = this.resolvedProperty;
  18677. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18678. dest[ i ] = buffer[ offset ++ ];
  18679. }
  18680. }
  18681. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18682. const dest = this.resolvedProperty;
  18683. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18684. dest[ i ] = buffer[ offset ++ ];
  18685. }
  18686. this.targetObject.needsUpdate = true;
  18687. }
  18688. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18689. const dest = this.resolvedProperty;
  18690. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18691. dest[ i ] = buffer[ offset ++ ];
  18692. }
  18693. this.targetObject.matrixWorldNeedsUpdate = true;
  18694. }
  18695. // ArrayElement
  18696. _setValue_arrayElement( buffer, offset ) {
  18697. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18698. }
  18699. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18700. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18701. this.targetObject.needsUpdate = true;
  18702. }
  18703. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18704. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18705. this.targetObject.matrixWorldNeedsUpdate = true;
  18706. }
  18707. // HasToFromArray
  18708. _setValue_fromArray( buffer, offset ) {
  18709. this.resolvedProperty.fromArray( buffer, offset );
  18710. }
  18711. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18712. this.resolvedProperty.fromArray( buffer, offset );
  18713. this.targetObject.needsUpdate = true;
  18714. }
  18715. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18716. this.resolvedProperty.fromArray( buffer, offset );
  18717. this.targetObject.matrixWorldNeedsUpdate = true;
  18718. }
  18719. _getValue_unbound( targetArray, offset ) {
  18720. this.bind();
  18721. this.getValue( targetArray, offset );
  18722. }
  18723. _setValue_unbound( sourceArray, offset ) {
  18724. this.bind();
  18725. this.setValue( sourceArray, offset );
  18726. }
  18727. // create getter / setter pair for a property in the scene graph
  18728. bind() {
  18729. let targetObject = this.node;
  18730. const parsedPath = this.parsedPath;
  18731. const objectName = parsedPath.objectName;
  18732. const propertyName = parsedPath.propertyName;
  18733. let propertyIndex = parsedPath.propertyIndex;
  18734. if ( ! targetObject ) {
  18735. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18736. this.node = targetObject;
  18737. }
  18738. // set fail state so we can just 'return' on error
  18739. this.getValue = this._getValue_unavailable;
  18740. this.setValue = this._setValue_unavailable;
  18741. // ensure there is a value node
  18742. if ( ! targetObject ) {
  18743. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18744. return;
  18745. }
  18746. if ( objectName ) {
  18747. let objectIndex = parsedPath.objectIndex;
  18748. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18749. switch ( objectName ) {
  18750. case 'materials':
  18751. if ( ! targetObject.material ) {
  18752. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18753. return;
  18754. }
  18755. if ( ! targetObject.material.materials ) {
  18756. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18757. return;
  18758. }
  18759. targetObject = targetObject.material.materials;
  18760. break;
  18761. case 'bones':
  18762. if ( ! targetObject.skeleton ) {
  18763. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18764. return;
  18765. }
  18766. // potential future optimization: skip this if propertyIndex is already an integer
  18767. // and convert the integer string to a true integer.
  18768. targetObject = targetObject.skeleton.bones;
  18769. // support resolving morphTarget names into indices.
  18770. for ( let i = 0; i < targetObject.length; i ++ ) {
  18771. if ( targetObject[ i ].name === objectIndex ) {
  18772. objectIndex = i;
  18773. break;
  18774. }
  18775. }
  18776. break;
  18777. case 'map':
  18778. if ( 'map' in targetObject ) {
  18779. targetObject = targetObject.map;
  18780. break;
  18781. }
  18782. if ( ! targetObject.material ) {
  18783. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18784. return;
  18785. }
  18786. if ( ! targetObject.material.map ) {
  18787. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  18788. return;
  18789. }
  18790. targetObject = targetObject.material.map;
  18791. break;
  18792. default:
  18793. if ( targetObject[ objectName ] === undefined ) {
  18794. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  18795. return;
  18796. }
  18797. targetObject = targetObject[ objectName ];
  18798. }
  18799. if ( objectIndex !== undefined ) {
  18800. if ( targetObject[ objectIndex ] === undefined ) {
  18801. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  18802. return;
  18803. }
  18804. targetObject = targetObject[ objectIndex ];
  18805. }
  18806. }
  18807. // resolve property
  18808. const nodeProperty = targetObject[ propertyName ];
  18809. if ( nodeProperty === undefined ) {
  18810. const nodeName = parsedPath.nodeName;
  18811. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  18812. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  18813. return;
  18814. }
  18815. // determine versioning scheme
  18816. let versioning = this.Versioning.None;
  18817. this.targetObject = targetObject;
  18818. if ( targetObject.needsUpdate !== undefined ) { // material
  18819. versioning = this.Versioning.NeedsUpdate;
  18820. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  18821. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  18822. }
  18823. // determine how the property gets bound
  18824. let bindingType = this.BindingType.Direct;
  18825. if ( propertyIndex !== undefined ) {
  18826. // access a sub element of the property array (only primitives are supported right now)
  18827. if ( propertyName === 'morphTargetInfluences' ) {
  18828. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  18829. // support resolving morphTarget names into indices.
  18830. if ( ! targetObject.geometry ) {
  18831. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  18832. return;
  18833. }
  18834. if ( ! targetObject.geometry.morphAttributes ) {
  18835. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  18836. return;
  18837. }
  18838. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  18839. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  18840. }
  18841. }
  18842. bindingType = this.BindingType.ArrayElement;
  18843. this.resolvedProperty = nodeProperty;
  18844. this.propertyIndex = propertyIndex;
  18845. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  18846. // must use copy for Object3D.Euler/Quaternion
  18847. bindingType = this.BindingType.HasFromToArray;
  18848. this.resolvedProperty = nodeProperty;
  18849. } else if ( Array.isArray( nodeProperty ) ) {
  18850. bindingType = this.BindingType.EntireArray;
  18851. this.resolvedProperty = nodeProperty;
  18852. } else {
  18853. this.propertyName = propertyName;
  18854. }
  18855. // select getter / setter
  18856. this.getValue = this.GetterByBindingType[ bindingType ];
  18857. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  18858. }
  18859. unbind() {
  18860. this.node = null;
  18861. // back to the prototype version of getValue / setValue
  18862. // note: avoiding to mutate the shape of 'this' via 'delete'
  18863. this.getValue = this._getValue_unbound;
  18864. this.setValue = this._setValue_unbound;
  18865. }
  18866. }
  18867. PropertyBinding.Composite = Composite;
  18868. PropertyBinding.prototype.BindingType = {
  18869. Direct: 0,
  18870. EntireArray: 1,
  18871. ArrayElement: 2,
  18872. HasFromToArray: 3
  18873. };
  18874. PropertyBinding.prototype.Versioning = {
  18875. None: 0,
  18876. NeedsUpdate: 1,
  18877. MatrixWorldNeedsUpdate: 2
  18878. };
  18879. PropertyBinding.prototype.GetterByBindingType = [
  18880. PropertyBinding.prototype._getValue_direct,
  18881. PropertyBinding.prototype._getValue_array,
  18882. PropertyBinding.prototype._getValue_arrayElement,
  18883. PropertyBinding.prototype._getValue_toArray,
  18884. ];
  18885. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  18886. [
  18887. // Direct
  18888. PropertyBinding.prototype._setValue_direct,
  18889. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  18890. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  18891. ], [
  18892. // EntireArray
  18893. PropertyBinding.prototype._setValue_array,
  18894. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  18895. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  18896. ], [
  18897. // ArrayElement
  18898. PropertyBinding.prototype._setValue_arrayElement,
  18899. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  18900. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  18901. ], [
  18902. // HasToFromArray
  18903. PropertyBinding.prototype._setValue_fromArray,
  18904. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  18905. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  18906. ]
  18907. ];
  18908. /**
  18909. *
  18910. * A group of objects that receives a shared animation state.
  18911. *
  18912. * Usage:
  18913. *
  18914. * - Add objects you would otherwise pass as 'root' to the
  18915. * constructor or the .clipAction method of AnimationMixer.
  18916. *
  18917. * - Instead pass this object as 'root'.
  18918. *
  18919. * - You can also add and remove objects later when the mixer
  18920. * is running.
  18921. *
  18922. * Note:
  18923. *
  18924. * Objects of this class appear as one object to the mixer,
  18925. * so cache control of the individual objects must be done
  18926. * on the group.
  18927. *
  18928. * Limitation:
  18929. *
  18930. * - The animated properties must be compatible among the
  18931. * all objects in the group.
  18932. *
  18933. * - A single property can either be controlled through a
  18934. * target group or directly, but not both.
  18935. */
  18936. class AnimationObjectGroup {
  18937. constructor() {
  18938. this.isAnimationObjectGroup = true;
  18939. this.uuid = generateUUID();
  18940. // cached objects followed by the active ones
  18941. this._objects = Array.prototype.slice.call( arguments );
  18942. this.nCachedObjects_ = 0; // threshold
  18943. // note: read by PropertyBinding.Composite
  18944. const indices = {};
  18945. this._indicesByUUID = indices; // for bookkeeping
  18946. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18947. indices[ arguments[ i ].uuid ] = i;
  18948. }
  18949. this._paths = []; // inside: string
  18950. this._parsedPaths = []; // inside: { we don't care, here }
  18951. this._bindings = []; // inside: Array< PropertyBinding >
  18952. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  18953. const scope = this;
  18954. this.stats = {
  18955. objects: {
  18956. get total() {
  18957. return scope._objects.length;
  18958. },
  18959. get inUse() {
  18960. return this.total - scope.nCachedObjects_;
  18961. }
  18962. },
  18963. get bindingsPerObject() {
  18964. return scope._bindings.length;
  18965. }
  18966. };
  18967. }
  18968. add() {
  18969. const objects = this._objects,
  18970. indicesByUUID = this._indicesByUUID,
  18971. paths = this._paths,
  18972. parsedPaths = this._parsedPaths,
  18973. bindings = this._bindings,
  18974. nBindings = bindings.length;
  18975. let knownObject = undefined,
  18976. nObjects = objects.length,
  18977. nCachedObjects = this.nCachedObjects_;
  18978. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  18979. const object = arguments[ i ],
  18980. uuid = object.uuid;
  18981. let index = indicesByUUID[ uuid ];
  18982. if ( index === undefined ) {
  18983. // unknown object -> add it to the ACTIVE region
  18984. index = nObjects ++;
  18985. indicesByUUID[ uuid ] = index;
  18986. objects.push( object );
  18987. // accounting is done, now do the same for all bindings
  18988. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  18989. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  18990. }
  18991. } else if ( index < nCachedObjects ) {
  18992. knownObject = objects[ index ];
  18993. // move existing object to the ACTIVE region
  18994. const firstActiveIndex = -- nCachedObjects,
  18995. lastCachedObject = objects[ firstActiveIndex ];
  18996. indicesByUUID[ lastCachedObject.uuid ] = index;
  18997. objects[ index ] = lastCachedObject;
  18998. indicesByUUID[ uuid ] = firstActiveIndex;
  18999. objects[ firstActiveIndex ] = object;
  19000. // accounting is done, now do the same for all bindings
  19001. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19002. const bindingsForPath = bindings[ j ],
  19003. lastCached = bindingsForPath[ firstActiveIndex ];
  19004. let binding = bindingsForPath[ index ];
  19005. bindingsForPath[ index ] = lastCached;
  19006. if ( binding === undefined ) {
  19007. // since we do not bother to create new bindings
  19008. // for objects that are cached, the binding may
  19009. // or may not exist
  19010. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  19011. }
  19012. bindingsForPath[ firstActiveIndex ] = binding;
  19013. }
  19014. } else if ( objects[ index ] !== knownObject ) {
  19015. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  19016. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  19017. } // else the object is already where we want it to be
  19018. } // for arguments
  19019. this.nCachedObjects_ = nCachedObjects;
  19020. }
  19021. remove() {
  19022. const objects = this._objects,
  19023. indicesByUUID = this._indicesByUUID,
  19024. bindings = this._bindings,
  19025. nBindings = bindings.length;
  19026. let nCachedObjects = this.nCachedObjects_;
  19027. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19028. const object = arguments[ i ],
  19029. uuid = object.uuid,
  19030. index = indicesByUUID[ uuid ];
  19031. if ( index !== undefined && index >= nCachedObjects ) {
  19032. // move existing object into the CACHED region
  19033. const lastCachedIndex = nCachedObjects ++,
  19034. firstActiveObject = objects[ lastCachedIndex ];
  19035. indicesByUUID[ firstActiveObject.uuid ] = index;
  19036. objects[ index ] = firstActiveObject;
  19037. indicesByUUID[ uuid ] = lastCachedIndex;
  19038. objects[ lastCachedIndex ] = object;
  19039. // accounting is done, now do the same for all bindings
  19040. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19041. const bindingsForPath = bindings[ j ],
  19042. firstActive = bindingsForPath[ lastCachedIndex ],
  19043. binding = bindingsForPath[ index ];
  19044. bindingsForPath[ index ] = firstActive;
  19045. bindingsForPath[ lastCachedIndex ] = binding;
  19046. }
  19047. }
  19048. } // for arguments
  19049. this.nCachedObjects_ = nCachedObjects;
  19050. }
  19051. // remove & forget
  19052. uncache() {
  19053. const objects = this._objects,
  19054. indicesByUUID = this._indicesByUUID,
  19055. bindings = this._bindings,
  19056. nBindings = bindings.length;
  19057. let nCachedObjects = this.nCachedObjects_,
  19058. nObjects = objects.length;
  19059. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19060. const object = arguments[ i ],
  19061. uuid = object.uuid,
  19062. index = indicesByUUID[ uuid ];
  19063. if ( index !== undefined ) {
  19064. delete indicesByUUID[ uuid ];
  19065. if ( index < nCachedObjects ) {
  19066. // object is cached, shrink the CACHED region
  19067. const firstActiveIndex = -- nCachedObjects,
  19068. lastCachedObject = objects[ firstActiveIndex ],
  19069. lastIndex = -- nObjects,
  19070. lastObject = objects[ lastIndex ];
  19071. // last cached object takes this object's place
  19072. indicesByUUID[ lastCachedObject.uuid ] = index;
  19073. objects[ index ] = lastCachedObject;
  19074. // last object goes to the activated slot and pop
  19075. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19076. objects[ firstActiveIndex ] = lastObject;
  19077. objects.pop();
  19078. // accounting is done, now do the same for all bindings
  19079. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19080. const bindingsForPath = bindings[ j ],
  19081. lastCached = bindingsForPath[ firstActiveIndex ],
  19082. last = bindingsForPath[ lastIndex ];
  19083. bindingsForPath[ index ] = lastCached;
  19084. bindingsForPath[ firstActiveIndex ] = last;
  19085. bindingsForPath.pop();
  19086. }
  19087. } else {
  19088. // object is active, just swap with the last and pop
  19089. const lastIndex = -- nObjects,
  19090. lastObject = objects[ lastIndex ];
  19091. if ( lastIndex > 0 ) {
  19092. indicesByUUID[ lastObject.uuid ] = index;
  19093. }
  19094. objects[ index ] = lastObject;
  19095. objects.pop();
  19096. // accounting is done, now do the same for all bindings
  19097. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19098. const bindingsForPath = bindings[ j ];
  19099. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19100. bindingsForPath.pop();
  19101. }
  19102. } // cached or active
  19103. } // if object is known
  19104. } // for arguments
  19105. this.nCachedObjects_ = nCachedObjects;
  19106. }
  19107. // Internal interface used by befriended PropertyBinding.Composite:
  19108. subscribe_( path, parsedPath ) {
  19109. // returns an array of bindings for the given path that is changed
  19110. // according to the contained objects in the group
  19111. const indicesByPath = this._bindingsIndicesByPath;
  19112. let index = indicesByPath[ path ];
  19113. const bindings = this._bindings;
  19114. if ( index !== undefined ) return bindings[ index ];
  19115. const paths = this._paths,
  19116. parsedPaths = this._parsedPaths,
  19117. objects = this._objects,
  19118. nObjects = objects.length,
  19119. nCachedObjects = this.nCachedObjects_,
  19120. bindingsForPath = new Array( nObjects );
  19121. index = bindings.length;
  19122. indicesByPath[ path ] = index;
  19123. paths.push( path );
  19124. parsedPaths.push( parsedPath );
  19125. bindings.push( bindingsForPath );
  19126. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19127. const object = objects[ i ];
  19128. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19129. }
  19130. return bindingsForPath;
  19131. }
  19132. unsubscribe_( path ) {
  19133. // tells the group to forget about a property path and no longer
  19134. // update the array previously obtained with 'subscribe_'
  19135. const indicesByPath = this._bindingsIndicesByPath,
  19136. index = indicesByPath[ path ];
  19137. if ( index !== undefined ) {
  19138. const paths = this._paths,
  19139. parsedPaths = this._parsedPaths,
  19140. bindings = this._bindings,
  19141. lastBindingsIndex = bindings.length - 1,
  19142. lastBindings = bindings[ lastBindingsIndex ],
  19143. lastBindingsPath = path[ lastBindingsIndex ];
  19144. indicesByPath[ lastBindingsPath ] = index;
  19145. bindings[ index ] = lastBindings;
  19146. bindings.pop();
  19147. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19148. parsedPaths.pop();
  19149. paths[ index ] = paths[ lastBindingsIndex ];
  19150. paths.pop();
  19151. }
  19152. }
  19153. }
  19154. class AnimationAction {
  19155. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19156. this._mixer = mixer;
  19157. this._clip = clip;
  19158. this._localRoot = localRoot;
  19159. this.blendMode = blendMode;
  19160. const tracks = clip.tracks,
  19161. nTracks = tracks.length,
  19162. interpolants = new Array( nTracks );
  19163. const interpolantSettings = {
  19164. endingStart: ZeroCurvatureEnding,
  19165. endingEnd: ZeroCurvatureEnding
  19166. };
  19167. for ( let i = 0; i !== nTracks; ++ i ) {
  19168. const interpolant = tracks[ i ].createInterpolant( null );
  19169. interpolants[ i ] = interpolant;
  19170. interpolant.settings = interpolantSettings;
  19171. }
  19172. this._interpolantSettings = interpolantSettings;
  19173. this._interpolants = interpolants; // bound by the mixer
  19174. // inside: PropertyMixer (managed by the mixer)
  19175. this._propertyBindings = new Array( nTracks );
  19176. this._cacheIndex = null; // for the memory manager
  19177. this._byClipCacheIndex = null; // for the memory manager
  19178. this._timeScaleInterpolant = null;
  19179. this._weightInterpolant = null;
  19180. this.loop = LoopRepeat;
  19181. this._loopCount = - 1;
  19182. // global mixer time when the action is to be started
  19183. // it's set back to 'null' upon start of the action
  19184. this._startTime = null;
  19185. // scaled local time of the action
  19186. // gets clamped or wrapped to 0..clip.duration according to loop
  19187. this.time = 0;
  19188. this.timeScale = 1;
  19189. this._effectiveTimeScale = 1;
  19190. this.weight = 1;
  19191. this._effectiveWeight = 1;
  19192. this.repetitions = Infinity; // no. of repetitions when looping
  19193. this.paused = false; // true -> zero effective time scale
  19194. this.enabled = true; // false -> zero effective weight
  19195. this.clampWhenFinished = false;// keep feeding the last frame?
  19196. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19197. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19198. }
  19199. // State & Scheduling
  19200. play() {
  19201. this._mixer._activateAction( this );
  19202. return this;
  19203. }
  19204. stop() {
  19205. this._mixer._deactivateAction( this );
  19206. return this.reset();
  19207. }
  19208. reset() {
  19209. this.paused = false;
  19210. this.enabled = true;
  19211. this.time = 0; // restart clip
  19212. this._loopCount = - 1;// forget previous loops
  19213. this._startTime = null;// forget scheduling
  19214. return this.stopFading().stopWarping();
  19215. }
  19216. isRunning() {
  19217. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19218. this._startTime === null && this._mixer._isActiveAction( this );
  19219. }
  19220. // return true when play has been called
  19221. isScheduled() {
  19222. return this._mixer._isActiveAction( this );
  19223. }
  19224. startAt( time ) {
  19225. this._startTime = time;
  19226. return this;
  19227. }
  19228. setLoop( mode, repetitions ) {
  19229. this.loop = mode;
  19230. this.repetitions = repetitions;
  19231. return this;
  19232. }
  19233. // Weight
  19234. // set the weight stopping any scheduled fading
  19235. // although .enabled = false yields an effective weight of zero, this
  19236. // method does *not* change .enabled, because it would be confusing
  19237. setEffectiveWeight( weight ) {
  19238. this.weight = weight;
  19239. // note: same logic as when updated at runtime
  19240. this._effectiveWeight = this.enabled ? weight : 0;
  19241. return this.stopFading();
  19242. }
  19243. // return the weight considering fading and .enabled
  19244. getEffectiveWeight() {
  19245. return this._effectiveWeight;
  19246. }
  19247. fadeIn( duration ) {
  19248. return this._scheduleFading( duration, 0, 1 );
  19249. }
  19250. fadeOut( duration ) {
  19251. return this._scheduleFading( duration, 1, 0 );
  19252. }
  19253. crossFadeFrom( fadeOutAction, duration, warp ) {
  19254. fadeOutAction.fadeOut( duration );
  19255. this.fadeIn( duration );
  19256. if ( warp ) {
  19257. const fadeInDuration = this._clip.duration,
  19258. fadeOutDuration = fadeOutAction._clip.duration,
  19259. startEndRatio = fadeOutDuration / fadeInDuration,
  19260. endStartRatio = fadeInDuration / fadeOutDuration;
  19261. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19262. this.warp( endStartRatio, 1.0, duration );
  19263. }
  19264. return this;
  19265. }
  19266. crossFadeTo( fadeInAction, duration, warp ) {
  19267. return fadeInAction.crossFadeFrom( this, duration, warp );
  19268. }
  19269. stopFading() {
  19270. const weightInterpolant = this._weightInterpolant;
  19271. if ( weightInterpolant !== null ) {
  19272. this._weightInterpolant = null;
  19273. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19274. }
  19275. return this;
  19276. }
  19277. // Time Scale Control
  19278. // set the time scale stopping any scheduled warping
  19279. // although .paused = true yields an effective time scale of zero, this
  19280. // method does *not* change .paused, because it would be confusing
  19281. setEffectiveTimeScale( timeScale ) {
  19282. this.timeScale = timeScale;
  19283. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19284. return this.stopWarping();
  19285. }
  19286. // return the time scale considering warping and .paused
  19287. getEffectiveTimeScale() {
  19288. return this._effectiveTimeScale;
  19289. }
  19290. setDuration( duration ) {
  19291. this.timeScale = this._clip.duration / duration;
  19292. return this.stopWarping();
  19293. }
  19294. syncWith( action ) {
  19295. this.time = action.time;
  19296. this.timeScale = action.timeScale;
  19297. return this.stopWarping();
  19298. }
  19299. halt( duration ) {
  19300. return this.warp( this._effectiveTimeScale, 0, duration );
  19301. }
  19302. warp( startTimeScale, endTimeScale, duration ) {
  19303. const mixer = this._mixer,
  19304. now = mixer.time,
  19305. timeScale = this.timeScale;
  19306. let interpolant = this._timeScaleInterpolant;
  19307. if ( interpolant === null ) {
  19308. interpolant = mixer._lendControlInterpolant();
  19309. this._timeScaleInterpolant = interpolant;
  19310. }
  19311. const times = interpolant.parameterPositions,
  19312. values = interpolant.sampleValues;
  19313. times[ 0 ] = now;
  19314. times[ 1 ] = now + duration;
  19315. values[ 0 ] = startTimeScale / timeScale;
  19316. values[ 1 ] = endTimeScale / timeScale;
  19317. return this;
  19318. }
  19319. stopWarping() {
  19320. const timeScaleInterpolant = this._timeScaleInterpolant;
  19321. if ( timeScaleInterpolant !== null ) {
  19322. this._timeScaleInterpolant = null;
  19323. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19324. }
  19325. return this;
  19326. }
  19327. // Object Accessors
  19328. getMixer() {
  19329. return this._mixer;
  19330. }
  19331. getClip() {
  19332. return this._clip;
  19333. }
  19334. getRoot() {
  19335. return this._localRoot || this._mixer._root;
  19336. }
  19337. // Interna
  19338. _update( time, deltaTime, timeDirection, accuIndex ) {
  19339. // called by the mixer
  19340. if ( ! this.enabled ) {
  19341. // call ._updateWeight() to update ._effectiveWeight
  19342. this._updateWeight( time );
  19343. return;
  19344. }
  19345. const startTime = this._startTime;
  19346. if ( startTime !== null ) {
  19347. // check for scheduled start of action
  19348. const timeRunning = ( time - startTime ) * timeDirection;
  19349. if ( timeRunning < 0 || timeDirection === 0 ) {
  19350. deltaTime = 0;
  19351. } else {
  19352. this._startTime = null; // unschedule
  19353. deltaTime = timeDirection * timeRunning;
  19354. }
  19355. }
  19356. // apply time scale and advance time
  19357. deltaTime *= this._updateTimeScale( time );
  19358. const clipTime = this._updateTime( deltaTime );
  19359. // note: _updateTime may disable the action resulting in
  19360. // an effective weight of 0
  19361. const weight = this._updateWeight( time );
  19362. if ( weight > 0 ) {
  19363. const interpolants = this._interpolants;
  19364. const propertyMixers = this._propertyBindings;
  19365. switch ( this.blendMode ) {
  19366. case AdditiveAnimationBlendMode:
  19367. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19368. interpolants[ j ].evaluate( clipTime );
  19369. propertyMixers[ j ].accumulateAdditive( weight );
  19370. }
  19371. break;
  19372. case NormalAnimationBlendMode:
  19373. default:
  19374. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19375. interpolants[ j ].evaluate( clipTime );
  19376. propertyMixers[ j ].accumulate( accuIndex, weight );
  19377. }
  19378. }
  19379. }
  19380. }
  19381. _updateWeight( time ) {
  19382. let weight = 0;
  19383. if ( this.enabled ) {
  19384. weight = this.weight;
  19385. const interpolant = this._weightInterpolant;
  19386. if ( interpolant !== null ) {
  19387. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19388. weight *= interpolantValue;
  19389. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19390. this.stopFading();
  19391. if ( interpolantValue === 0 ) {
  19392. // faded out, disable
  19393. this.enabled = false;
  19394. }
  19395. }
  19396. }
  19397. }
  19398. this._effectiveWeight = weight;
  19399. return weight;
  19400. }
  19401. _updateTimeScale( time ) {
  19402. let timeScale = 0;
  19403. if ( ! this.paused ) {
  19404. timeScale = this.timeScale;
  19405. const interpolant = this._timeScaleInterpolant;
  19406. if ( interpolant !== null ) {
  19407. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19408. timeScale *= interpolantValue;
  19409. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19410. this.stopWarping();
  19411. if ( timeScale === 0 ) {
  19412. // motion has halted, pause
  19413. this.paused = true;
  19414. } else {
  19415. // warp done - apply final time scale
  19416. this.timeScale = timeScale;
  19417. }
  19418. }
  19419. }
  19420. }
  19421. this._effectiveTimeScale = timeScale;
  19422. return timeScale;
  19423. }
  19424. _updateTime( deltaTime ) {
  19425. const duration = this._clip.duration;
  19426. const loop = this.loop;
  19427. let time = this.time + deltaTime;
  19428. let loopCount = this._loopCount;
  19429. const pingPong = ( loop === LoopPingPong );
  19430. if ( deltaTime === 0 ) {
  19431. if ( loopCount === - 1 ) return time;
  19432. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19433. }
  19434. if ( loop === LoopOnce ) {
  19435. if ( loopCount === - 1 ) {
  19436. // just started
  19437. this._loopCount = 0;
  19438. this._setEndings( true, true, false );
  19439. }
  19440. handle_stop: {
  19441. if ( time >= duration ) {
  19442. time = duration;
  19443. } else if ( time < 0 ) {
  19444. time = 0;
  19445. } else {
  19446. this.time = time;
  19447. break handle_stop;
  19448. }
  19449. if ( this.clampWhenFinished ) this.paused = true;
  19450. else this.enabled = false;
  19451. this.time = time;
  19452. this._mixer.dispatchEvent( {
  19453. type: 'finished', action: this,
  19454. direction: deltaTime < 0 ? - 1 : 1
  19455. } );
  19456. }
  19457. } else { // repetitive Repeat or PingPong
  19458. if ( loopCount === - 1 ) {
  19459. // just started
  19460. if ( deltaTime >= 0 ) {
  19461. loopCount = 0;
  19462. this._setEndings( true, this.repetitions === 0, pingPong );
  19463. } else {
  19464. // when looping in reverse direction, the initial
  19465. // transition through zero counts as a repetition,
  19466. // so leave loopCount at -1
  19467. this._setEndings( this.repetitions === 0, true, pingPong );
  19468. }
  19469. }
  19470. if ( time >= duration || time < 0 ) {
  19471. // wrap around
  19472. const loopDelta = Math.floor( time / duration ); // signed
  19473. time -= duration * loopDelta;
  19474. loopCount += Math.abs( loopDelta );
  19475. const pending = this.repetitions - loopCount;
  19476. if ( pending <= 0 ) {
  19477. // have to stop (switch state, clamp time, fire event)
  19478. if ( this.clampWhenFinished ) this.paused = true;
  19479. else this.enabled = false;
  19480. time = deltaTime > 0 ? duration : 0;
  19481. this.time = time;
  19482. this._mixer.dispatchEvent( {
  19483. type: 'finished', action: this,
  19484. direction: deltaTime > 0 ? 1 : - 1
  19485. } );
  19486. } else {
  19487. // keep running
  19488. if ( pending === 1 ) {
  19489. // entering the last round
  19490. const atStart = deltaTime < 0;
  19491. this._setEndings( atStart, ! atStart, pingPong );
  19492. } else {
  19493. this._setEndings( false, false, pingPong );
  19494. }
  19495. this._loopCount = loopCount;
  19496. this.time = time;
  19497. this._mixer.dispatchEvent( {
  19498. type: 'loop', action: this, loopDelta: loopDelta
  19499. } );
  19500. }
  19501. } else {
  19502. this.time = time;
  19503. }
  19504. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19505. // invert time for the "pong round"
  19506. return duration - time;
  19507. }
  19508. }
  19509. return time;
  19510. }
  19511. _setEndings( atStart, atEnd, pingPong ) {
  19512. const settings = this._interpolantSettings;
  19513. if ( pingPong ) {
  19514. settings.endingStart = ZeroSlopeEnding;
  19515. settings.endingEnd = ZeroSlopeEnding;
  19516. } else {
  19517. // assuming for LoopOnce atStart == atEnd == true
  19518. if ( atStart ) {
  19519. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19520. } else {
  19521. settings.endingStart = WrapAroundEnding;
  19522. }
  19523. if ( atEnd ) {
  19524. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19525. } else {
  19526. settings.endingEnd = WrapAroundEnding;
  19527. }
  19528. }
  19529. }
  19530. _scheduleFading( duration, weightNow, weightThen ) {
  19531. const mixer = this._mixer, now = mixer.time;
  19532. let interpolant = this._weightInterpolant;
  19533. if ( interpolant === null ) {
  19534. interpolant = mixer._lendControlInterpolant();
  19535. this._weightInterpolant = interpolant;
  19536. }
  19537. const times = interpolant.parameterPositions,
  19538. values = interpolant.sampleValues;
  19539. times[ 0 ] = now;
  19540. values[ 0 ] = weightNow;
  19541. times[ 1 ] = now + duration;
  19542. values[ 1 ] = weightThen;
  19543. return this;
  19544. }
  19545. }
  19546. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19547. class AnimationMixer extends EventDispatcher {
  19548. constructor( root ) {
  19549. super();
  19550. this._root = root;
  19551. this._initMemoryManager();
  19552. this._accuIndex = 0;
  19553. this.time = 0;
  19554. this.timeScale = 1.0;
  19555. }
  19556. _bindAction( action, prototypeAction ) {
  19557. const root = action._localRoot || this._root,
  19558. tracks = action._clip.tracks,
  19559. nTracks = tracks.length,
  19560. bindings = action._propertyBindings,
  19561. interpolants = action._interpolants,
  19562. rootUuid = root.uuid,
  19563. bindingsByRoot = this._bindingsByRootAndName;
  19564. let bindingsByName = bindingsByRoot[ rootUuid ];
  19565. if ( bindingsByName === undefined ) {
  19566. bindingsByName = {};
  19567. bindingsByRoot[ rootUuid ] = bindingsByName;
  19568. }
  19569. for ( let i = 0; i !== nTracks; ++ i ) {
  19570. const track = tracks[ i ],
  19571. trackName = track.name;
  19572. let binding = bindingsByName[ trackName ];
  19573. if ( binding !== undefined ) {
  19574. ++ binding.referenceCount;
  19575. bindings[ i ] = binding;
  19576. } else {
  19577. binding = bindings[ i ];
  19578. if ( binding !== undefined ) {
  19579. // existing binding, make sure the cache knows
  19580. if ( binding._cacheIndex === null ) {
  19581. ++ binding.referenceCount;
  19582. this._addInactiveBinding( binding, rootUuid, trackName );
  19583. }
  19584. continue;
  19585. }
  19586. const path = prototypeAction && prototypeAction.
  19587. _propertyBindings[ i ].binding.parsedPath;
  19588. binding = new PropertyMixer(
  19589. PropertyBinding.create( root, trackName, path ),
  19590. track.ValueTypeName, track.getValueSize() );
  19591. ++ binding.referenceCount;
  19592. this._addInactiveBinding( binding, rootUuid, trackName );
  19593. bindings[ i ] = binding;
  19594. }
  19595. interpolants[ i ].resultBuffer = binding.buffer;
  19596. }
  19597. }
  19598. _activateAction( action ) {
  19599. if ( ! this._isActiveAction( action ) ) {
  19600. if ( action._cacheIndex === null ) {
  19601. // this action has been forgotten by the cache, but the user
  19602. // appears to be still using it -> rebind
  19603. const rootUuid = ( action._localRoot || this._root ).uuid,
  19604. clipUuid = action._clip.uuid,
  19605. actionsForClip = this._actionsByClip[ clipUuid ];
  19606. this._bindAction( action,
  19607. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19608. this._addInactiveAction( action, clipUuid, rootUuid );
  19609. }
  19610. const bindings = action._propertyBindings;
  19611. // increment reference counts / sort out state
  19612. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19613. const binding = bindings[ i ];
  19614. if ( binding.useCount ++ === 0 ) {
  19615. this._lendBinding( binding );
  19616. binding.saveOriginalState();
  19617. }
  19618. }
  19619. this._lendAction( action );
  19620. }
  19621. }
  19622. _deactivateAction( action ) {
  19623. if ( this._isActiveAction( action ) ) {
  19624. const bindings = action._propertyBindings;
  19625. // decrement reference counts / sort out state
  19626. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19627. const binding = bindings[ i ];
  19628. if ( -- binding.useCount === 0 ) {
  19629. binding.restoreOriginalState();
  19630. this._takeBackBinding( binding );
  19631. }
  19632. }
  19633. this._takeBackAction( action );
  19634. }
  19635. }
  19636. // Memory manager
  19637. _initMemoryManager() {
  19638. this._actions = []; // 'nActiveActions' followed by inactive ones
  19639. this._nActiveActions = 0;
  19640. this._actionsByClip = {};
  19641. // inside:
  19642. // {
  19643. // knownActions: Array< AnimationAction > - used as prototypes
  19644. // actionByRoot: AnimationAction - lookup
  19645. // }
  19646. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19647. this._nActiveBindings = 0;
  19648. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19649. this._controlInterpolants = []; // same game as above
  19650. this._nActiveControlInterpolants = 0;
  19651. const scope = this;
  19652. this.stats = {
  19653. actions: {
  19654. get total() {
  19655. return scope._actions.length;
  19656. },
  19657. get inUse() {
  19658. return scope._nActiveActions;
  19659. }
  19660. },
  19661. bindings: {
  19662. get total() {
  19663. return scope._bindings.length;
  19664. },
  19665. get inUse() {
  19666. return scope._nActiveBindings;
  19667. }
  19668. },
  19669. controlInterpolants: {
  19670. get total() {
  19671. return scope._controlInterpolants.length;
  19672. },
  19673. get inUse() {
  19674. return scope._nActiveControlInterpolants;
  19675. }
  19676. }
  19677. };
  19678. }
  19679. // Memory management for AnimationAction objects
  19680. _isActiveAction( action ) {
  19681. const index = action._cacheIndex;
  19682. return index !== null && index < this._nActiveActions;
  19683. }
  19684. _addInactiveAction( action, clipUuid, rootUuid ) {
  19685. const actions = this._actions,
  19686. actionsByClip = this._actionsByClip;
  19687. let actionsForClip = actionsByClip[ clipUuid ];
  19688. if ( actionsForClip === undefined ) {
  19689. actionsForClip = {
  19690. knownActions: [ action ],
  19691. actionByRoot: {}
  19692. };
  19693. action._byClipCacheIndex = 0;
  19694. actionsByClip[ clipUuid ] = actionsForClip;
  19695. } else {
  19696. const knownActions = actionsForClip.knownActions;
  19697. action._byClipCacheIndex = knownActions.length;
  19698. knownActions.push( action );
  19699. }
  19700. action._cacheIndex = actions.length;
  19701. actions.push( action );
  19702. actionsForClip.actionByRoot[ rootUuid ] = action;
  19703. }
  19704. _removeInactiveAction( action ) {
  19705. const actions = this._actions,
  19706. lastInactiveAction = actions[ actions.length - 1 ],
  19707. cacheIndex = action._cacheIndex;
  19708. lastInactiveAction._cacheIndex = cacheIndex;
  19709. actions[ cacheIndex ] = lastInactiveAction;
  19710. actions.pop();
  19711. action._cacheIndex = null;
  19712. const clipUuid = action._clip.uuid,
  19713. actionsByClip = this._actionsByClip,
  19714. actionsForClip = actionsByClip[ clipUuid ],
  19715. knownActionsForClip = actionsForClip.knownActions,
  19716. lastKnownAction =
  19717. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19718. byClipCacheIndex = action._byClipCacheIndex;
  19719. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19720. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19721. knownActionsForClip.pop();
  19722. action._byClipCacheIndex = null;
  19723. const actionByRoot = actionsForClip.actionByRoot,
  19724. rootUuid = ( action._localRoot || this._root ).uuid;
  19725. delete actionByRoot[ rootUuid ];
  19726. if ( knownActionsForClip.length === 0 ) {
  19727. delete actionsByClip[ clipUuid ];
  19728. }
  19729. this._removeInactiveBindingsForAction( action );
  19730. }
  19731. _removeInactiveBindingsForAction( action ) {
  19732. const bindings = action._propertyBindings;
  19733. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19734. const binding = bindings[ i ];
  19735. if ( -- binding.referenceCount === 0 ) {
  19736. this._removeInactiveBinding( binding );
  19737. }
  19738. }
  19739. }
  19740. _lendAction( action ) {
  19741. // [ active actions | inactive actions ]
  19742. // [ active actions >| inactive actions ]
  19743. // s a
  19744. // <-swap->
  19745. // a s
  19746. const actions = this._actions,
  19747. prevIndex = action._cacheIndex,
  19748. lastActiveIndex = this._nActiveActions ++,
  19749. firstInactiveAction = actions[ lastActiveIndex ];
  19750. action._cacheIndex = lastActiveIndex;
  19751. actions[ lastActiveIndex ] = action;
  19752. firstInactiveAction._cacheIndex = prevIndex;
  19753. actions[ prevIndex ] = firstInactiveAction;
  19754. }
  19755. _takeBackAction( action ) {
  19756. // [ active actions | inactive actions ]
  19757. // [ active actions |< inactive actions ]
  19758. // a s
  19759. // <-swap->
  19760. // s a
  19761. const actions = this._actions,
  19762. prevIndex = action._cacheIndex,
  19763. firstInactiveIndex = -- this._nActiveActions,
  19764. lastActiveAction = actions[ firstInactiveIndex ];
  19765. action._cacheIndex = firstInactiveIndex;
  19766. actions[ firstInactiveIndex ] = action;
  19767. lastActiveAction._cacheIndex = prevIndex;
  19768. actions[ prevIndex ] = lastActiveAction;
  19769. }
  19770. // Memory management for PropertyMixer objects
  19771. _addInactiveBinding( binding, rootUuid, trackName ) {
  19772. const bindingsByRoot = this._bindingsByRootAndName,
  19773. bindings = this._bindings;
  19774. let bindingByName = bindingsByRoot[ rootUuid ];
  19775. if ( bindingByName === undefined ) {
  19776. bindingByName = {};
  19777. bindingsByRoot[ rootUuid ] = bindingByName;
  19778. }
  19779. bindingByName[ trackName ] = binding;
  19780. binding._cacheIndex = bindings.length;
  19781. bindings.push( binding );
  19782. }
  19783. _removeInactiveBinding( binding ) {
  19784. const bindings = this._bindings,
  19785. propBinding = binding.binding,
  19786. rootUuid = propBinding.rootNode.uuid,
  19787. trackName = propBinding.path,
  19788. bindingsByRoot = this._bindingsByRootAndName,
  19789. bindingByName = bindingsByRoot[ rootUuid ],
  19790. lastInactiveBinding = bindings[ bindings.length - 1 ],
  19791. cacheIndex = binding._cacheIndex;
  19792. lastInactiveBinding._cacheIndex = cacheIndex;
  19793. bindings[ cacheIndex ] = lastInactiveBinding;
  19794. bindings.pop();
  19795. delete bindingByName[ trackName ];
  19796. if ( Object.keys( bindingByName ).length === 0 ) {
  19797. delete bindingsByRoot[ rootUuid ];
  19798. }
  19799. }
  19800. _lendBinding( binding ) {
  19801. const bindings = this._bindings,
  19802. prevIndex = binding._cacheIndex,
  19803. lastActiveIndex = this._nActiveBindings ++,
  19804. firstInactiveBinding = bindings[ lastActiveIndex ];
  19805. binding._cacheIndex = lastActiveIndex;
  19806. bindings[ lastActiveIndex ] = binding;
  19807. firstInactiveBinding._cacheIndex = prevIndex;
  19808. bindings[ prevIndex ] = firstInactiveBinding;
  19809. }
  19810. _takeBackBinding( binding ) {
  19811. const bindings = this._bindings,
  19812. prevIndex = binding._cacheIndex,
  19813. firstInactiveIndex = -- this._nActiveBindings,
  19814. lastActiveBinding = bindings[ firstInactiveIndex ];
  19815. binding._cacheIndex = firstInactiveIndex;
  19816. bindings[ firstInactiveIndex ] = binding;
  19817. lastActiveBinding._cacheIndex = prevIndex;
  19818. bindings[ prevIndex ] = lastActiveBinding;
  19819. }
  19820. // Memory management of Interpolants for weight and time scale
  19821. _lendControlInterpolant() {
  19822. const interpolants = this._controlInterpolants,
  19823. lastActiveIndex = this._nActiveControlInterpolants ++;
  19824. let interpolant = interpolants[ lastActiveIndex ];
  19825. if ( interpolant === undefined ) {
  19826. interpolant = new LinearInterpolant(
  19827. new Float32Array( 2 ), new Float32Array( 2 ),
  19828. 1, _controlInterpolantsResultBuffer );
  19829. interpolant.__cacheIndex = lastActiveIndex;
  19830. interpolants[ lastActiveIndex ] = interpolant;
  19831. }
  19832. return interpolant;
  19833. }
  19834. _takeBackControlInterpolant( interpolant ) {
  19835. const interpolants = this._controlInterpolants,
  19836. prevIndex = interpolant.__cacheIndex,
  19837. firstInactiveIndex = -- this._nActiveControlInterpolants,
  19838. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  19839. interpolant.__cacheIndex = firstInactiveIndex;
  19840. interpolants[ firstInactiveIndex ] = interpolant;
  19841. lastActiveInterpolant.__cacheIndex = prevIndex;
  19842. interpolants[ prevIndex ] = lastActiveInterpolant;
  19843. }
  19844. // return an action for a clip optionally using a custom root target
  19845. // object (this method allocates a lot of dynamic memory in case a
  19846. // previously unknown clip/root combination is specified)
  19847. clipAction( clip, optionalRoot, blendMode ) {
  19848. const root = optionalRoot || this._root,
  19849. rootUuid = root.uuid;
  19850. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  19851. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  19852. const actionsForClip = this._actionsByClip[ clipUuid ];
  19853. let prototypeAction = null;
  19854. if ( blendMode === undefined ) {
  19855. if ( clipObject !== null ) {
  19856. blendMode = clipObject.blendMode;
  19857. } else {
  19858. blendMode = NormalAnimationBlendMode;
  19859. }
  19860. }
  19861. if ( actionsForClip !== undefined ) {
  19862. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  19863. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  19864. return existingAction;
  19865. }
  19866. // we know the clip, so we don't have to parse all
  19867. // the bindings again but can just copy
  19868. prototypeAction = actionsForClip.knownActions[ 0 ];
  19869. // also, take the clip from the prototype action
  19870. if ( clipObject === null )
  19871. clipObject = prototypeAction._clip;
  19872. }
  19873. // clip must be known when specified via string
  19874. if ( clipObject === null ) return null;
  19875. // allocate all resources required to run it
  19876. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  19877. this._bindAction( newAction, prototypeAction );
  19878. // and make the action known to the memory manager
  19879. this._addInactiveAction( newAction, clipUuid, rootUuid );
  19880. return newAction;
  19881. }
  19882. // get an existing action
  19883. existingAction( clip, optionalRoot ) {
  19884. const root = optionalRoot || this._root,
  19885. rootUuid = root.uuid,
  19886. clipObject = typeof clip === 'string' ?
  19887. AnimationClip.findByName( root, clip ) : clip,
  19888. clipUuid = clipObject ? clipObject.uuid : clip,
  19889. actionsForClip = this._actionsByClip[ clipUuid ];
  19890. if ( actionsForClip !== undefined ) {
  19891. return actionsForClip.actionByRoot[ rootUuid ] || null;
  19892. }
  19893. return null;
  19894. }
  19895. // deactivates all previously scheduled actions
  19896. stopAllAction() {
  19897. const actions = this._actions,
  19898. nActions = this._nActiveActions;
  19899. for ( let i = nActions - 1; i >= 0; -- i ) {
  19900. actions[ i ].stop();
  19901. }
  19902. return this;
  19903. }
  19904. // advance the time and update apply the animation
  19905. update( deltaTime ) {
  19906. deltaTime *= this.timeScale;
  19907. const actions = this._actions,
  19908. nActions = this._nActiveActions,
  19909. time = this.time += deltaTime,
  19910. timeDirection = Math.sign( deltaTime ),
  19911. accuIndex = this._accuIndex ^= 1;
  19912. // run active actions
  19913. for ( let i = 0; i !== nActions; ++ i ) {
  19914. const action = actions[ i ];
  19915. action._update( time, deltaTime, timeDirection, accuIndex );
  19916. }
  19917. // update scene graph
  19918. const bindings = this._bindings,
  19919. nBindings = this._nActiveBindings;
  19920. for ( let i = 0; i !== nBindings; ++ i ) {
  19921. bindings[ i ].apply( accuIndex );
  19922. }
  19923. return this;
  19924. }
  19925. // Allows you to seek to a specific time in an animation.
  19926. setTime( timeInSeconds ) {
  19927. this.time = 0; // Zero out time attribute for AnimationMixer object;
  19928. for ( let i = 0; i < this._actions.length; i ++ ) {
  19929. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  19930. }
  19931. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  19932. }
  19933. // return this mixer's root target object
  19934. getRoot() {
  19935. return this._root;
  19936. }
  19937. // free all resources specific to a particular clip
  19938. uncacheClip( clip ) {
  19939. const actions = this._actions,
  19940. clipUuid = clip.uuid,
  19941. actionsByClip = this._actionsByClip,
  19942. actionsForClip = actionsByClip[ clipUuid ];
  19943. if ( actionsForClip !== undefined ) {
  19944. // note: just calling _removeInactiveAction would mess up the
  19945. // iteration state and also require updating the state we can
  19946. // just throw away
  19947. const actionsToRemove = actionsForClip.knownActions;
  19948. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  19949. const action = actionsToRemove[ i ];
  19950. this._deactivateAction( action );
  19951. const cacheIndex = action._cacheIndex,
  19952. lastInactiveAction = actions[ actions.length - 1 ];
  19953. action._cacheIndex = null;
  19954. action._byClipCacheIndex = null;
  19955. lastInactiveAction._cacheIndex = cacheIndex;
  19956. actions[ cacheIndex ] = lastInactiveAction;
  19957. actions.pop();
  19958. this._removeInactiveBindingsForAction( action );
  19959. }
  19960. delete actionsByClip[ clipUuid ];
  19961. }
  19962. }
  19963. // free all resources specific to a particular root target object
  19964. uncacheRoot( root ) {
  19965. const rootUuid = root.uuid,
  19966. actionsByClip = this._actionsByClip;
  19967. for ( const clipUuid in actionsByClip ) {
  19968. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  19969. action = actionByRoot[ rootUuid ];
  19970. if ( action !== undefined ) {
  19971. this._deactivateAction( action );
  19972. this._removeInactiveAction( action );
  19973. }
  19974. }
  19975. const bindingsByRoot = this._bindingsByRootAndName,
  19976. bindingByName = bindingsByRoot[ rootUuid ];
  19977. if ( bindingByName !== undefined ) {
  19978. for ( const trackName in bindingByName ) {
  19979. const binding = bindingByName[ trackName ];
  19980. binding.restoreOriginalState();
  19981. this._removeInactiveBinding( binding );
  19982. }
  19983. }
  19984. }
  19985. // remove a targeted clip from the cache
  19986. uncacheAction( clip, optionalRoot ) {
  19987. const action = this.existingAction( clip, optionalRoot );
  19988. if ( action !== null ) {
  19989. this._deactivateAction( action );
  19990. this._removeInactiveAction( action );
  19991. }
  19992. }
  19993. }
  19994. let Uniform$1 = class Uniform {
  19995. constructor( value ) {
  19996. this.value = value;
  19997. }
  19998. clone() {
  19999. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  20000. }
  20001. };
  20002. let _id$8 = 0;
  20003. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  20004. constructor() {
  20005. super();
  20006. this.isUniformsGroup = true;
  20007. Object.defineProperty( this, 'id', { value: _id$8 ++ } );
  20008. this.name = '';
  20009. this.usage = StaticDrawUsage;
  20010. this.uniforms = [];
  20011. }
  20012. add( uniform ) {
  20013. this.uniforms.push( uniform );
  20014. return this;
  20015. }
  20016. remove( uniform ) {
  20017. const index = this.uniforms.indexOf( uniform );
  20018. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  20019. return this;
  20020. }
  20021. setName( name ) {
  20022. this.name = name;
  20023. return this;
  20024. }
  20025. setUsage( value ) {
  20026. this.usage = value;
  20027. return this;
  20028. }
  20029. dispose() {
  20030. this.dispatchEvent( { type: 'dispose' } );
  20031. return this;
  20032. }
  20033. copy( source ) {
  20034. this.name = source.name;
  20035. this.usage = source.usage;
  20036. const uniformsSource = source.uniforms;
  20037. this.uniforms.length = 0;
  20038. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  20039. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  20040. for ( let j = 0; j < uniforms.length; j ++ ) {
  20041. this.uniforms.push( uniforms[ j ].clone() );
  20042. }
  20043. }
  20044. return this;
  20045. }
  20046. clone() {
  20047. return new this.constructor().copy( this );
  20048. }
  20049. };
  20050. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20051. constructor( array, stride, meshPerAttribute = 1 ) {
  20052. super( array, stride );
  20053. this.isInstancedInterleavedBuffer = true;
  20054. this.meshPerAttribute = meshPerAttribute;
  20055. }
  20056. copy( source ) {
  20057. super.copy( source );
  20058. this.meshPerAttribute = source.meshPerAttribute;
  20059. return this;
  20060. }
  20061. clone( data ) {
  20062. const ib = super.clone( data );
  20063. ib.meshPerAttribute = this.meshPerAttribute;
  20064. return ib;
  20065. }
  20066. toJSON( data ) {
  20067. const json = super.toJSON( data );
  20068. json.isInstancedInterleavedBuffer = true;
  20069. json.meshPerAttribute = this.meshPerAttribute;
  20070. return json;
  20071. }
  20072. }
  20073. class GLBufferAttribute {
  20074. constructor( buffer, type, itemSize, elementSize, count ) {
  20075. this.isGLBufferAttribute = true;
  20076. this.name = '';
  20077. this.buffer = buffer;
  20078. this.type = type;
  20079. this.itemSize = itemSize;
  20080. this.elementSize = elementSize;
  20081. this.count = count;
  20082. this.version = 0;
  20083. }
  20084. set needsUpdate( value ) {
  20085. if ( value === true ) this.version ++;
  20086. }
  20087. setBuffer( buffer ) {
  20088. this.buffer = buffer;
  20089. return this;
  20090. }
  20091. setType( type, elementSize ) {
  20092. this.type = type;
  20093. this.elementSize = elementSize;
  20094. return this;
  20095. }
  20096. setItemSize( itemSize ) {
  20097. this.itemSize = itemSize;
  20098. return this;
  20099. }
  20100. setCount( count ) {
  20101. this.count = count;
  20102. return this;
  20103. }
  20104. }
  20105. const _matrix = /*@__PURE__*/ new Matrix4();
  20106. class Raycaster {
  20107. constructor( origin, direction, near = 0, far = Infinity ) {
  20108. this.ray = new Ray( origin, direction );
  20109. // direction is assumed to be normalized (for accurate distance calculations)
  20110. this.near = near;
  20111. this.far = far;
  20112. this.camera = null;
  20113. this.layers = new Layers();
  20114. this.params = {
  20115. Mesh: {},
  20116. Line: { threshold: 1 },
  20117. LOD: {},
  20118. Points: { threshold: 1 },
  20119. Sprite: {}
  20120. };
  20121. }
  20122. set( origin, direction ) {
  20123. // direction is assumed to be normalized (for accurate distance calculations)
  20124. this.ray.set( origin, direction );
  20125. }
  20126. setFromCamera( coords, camera ) {
  20127. if ( camera.isPerspectiveCamera ) {
  20128. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20129. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20130. this.camera = camera;
  20131. } else if ( camera.isOrthographicCamera ) {
  20132. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20133. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20134. this.camera = camera;
  20135. } else {
  20136. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20137. }
  20138. }
  20139. setFromXRController( controller ) {
  20140. _matrix.identity().extractRotation( controller.matrixWorld );
  20141. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20142. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20143. return this;
  20144. }
  20145. intersectObject( object, recursive = true, intersects = [] ) {
  20146. intersect( object, this, intersects, recursive );
  20147. intersects.sort( ascSort );
  20148. return intersects;
  20149. }
  20150. intersectObjects( objects, recursive = true, intersects = [] ) {
  20151. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20152. intersect( objects[ i ], this, intersects, recursive );
  20153. }
  20154. intersects.sort( ascSort );
  20155. return intersects;
  20156. }
  20157. }
  20158. function ascSort( a, b ) {
  20159. return a.distance - b.distance;
  20160. }
  20161. function intersect( object, raycaster, intersects, recursive ) {
  20162. let propagate = true;
  20163. if ( object.layers.test( raycaster.layers ) ) {
  20164. const result = object.raycast( raycaster, intersects );
  20165. if ( result === false ) propagate = false;
  20166. }
  20167. if ( propagate === true && recursive === true ) {
  20168. const children = object.children;
  20169. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20170. intersect( children[ i ], raycaster, intersects, true );
  20171. }
  20172. }
  20173. }
  20174. /**
  20175. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20176. *
  20177. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20178. * theta (the azimuthal angle) is measured from the positive z-axis.
  20179. */
  20180. class Spherical {
  20181. constructor( radius = 1, phi = 0, theta = 0 ) {
  20182. this.radius = radius;
  20183. this.phi = phi; // polar angle
  20184. this.theta = theta; // azimuthal angle
  20185. return this;
  20186. }
  20187. set( radius, phi, theta ) {
  20188. this.radius = radius;
  20189. this.phi = phi;
  20190. this.theta = theta;
  20191. return this;
  20192. }
  20193. copy( other ) {
  20194. this.radius = other.radius;
  20195. this.phi = other.phi;
  20196. this.theta = other.theta;
  20197. return this;
  20198. }
  20199. // restrict phi to be between EPS and PI-EPS
  20200. makeSafe() {
  20201. const EPS = 0.000001;
  20202. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20203. return this;
  20204. }
  20205. setFromVector3( v ) {
  20206. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20207. }
  20208. setFromCartesianCoords( x, y, z ) {
  20209. this.radius = Math.sqrt( x * x + y * y + z * z );
  20210. if ( this.radius === 0 ) {
  20211. this.theta = 0;
  20212. this.phi = 0;
  20213. } else {
  20214. this.theta = Math.atan2( x, z );
  20215. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20216. }
  20217. return this;
  20218. }
  20219. clone() {
  20220. return new this.constructor().copy( this );
  20221. }
  20222. }
  20223. /**
  20224. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20225. */
  20226. class Cylindrical {
  20227. constructor( radius = 1, theta = 0, y = 0 ) {
  20228. this.radius = radius; // distance from the origin to a point in the x-z plane
  20229. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20230. this.y = y; // height above the x-z plane
  20231. return this;
  20232. }
  20233. set( radius, theta, y ) {
  20234. this.radius = radius;
  20235. this.theta = theta;
  20236. this.y = y;
  20237. return this;
  20238. }
  20239. copy( other ) {
  20240. this.radius = other.radius;
  20241. this.theta = other.theta;
  20242. this.y = other.y;
  20243. return this;
  20244. }
  20245. setFromVector3( v ) {
  20246. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20247. }
  20248. setFromCartesianCoords( x, y, z ) {
  20249. this.radius = Math.sqrt( x * x + z * z );
  20250. this.theta = Math.atan2( x, z );
  20251. this.y = y;
  20252. return this;
  20253. }
  20254. clone() {
  20255. return new this.constructor().copy( this );
  20256. }
  20257. }
  20258. class Matrix2 {
  20259. constructor( n11, n12, n21, n22 ) {
  20260. Matrix2.prototype.isMatrix2 = true;
  20261. this.elements = [
  20262. 1, 0,
  20263. 0, 1,
  20264. ];
  20265. if ( n11 !== undefined ) {
  20266. this.set( n11, n12, n21, n22 );
  20267. }
  20268. }
  20269. identity() {
  20270. this.set(
  20271. 1, 0,
  20272. 0, 1,
  20273. );
  20274. return this;
  20275. }
  20276. fromArray( array, offset = 0 ) {
  20277. for ( let i = 0; i < 4; i ++ ) {
  20278. this.elements[ i ] = array[ i + offset ];
  20279. }
  20280. return this;
  20281. }
  20282. set( n11, n12, n21, n22 ) {
  20283. const te = this.elements;
  20284. te[ 0 ] = n11; te[ 2 ] = n12;
  20285. te[ 1 ] = n21; te[ 3 ] = n22;
  20286. return this;
  20287. }
  20288. }
  20289. const _vector$4 = /*@__PURE__*/ new Vector2();
  20290. class Box2 {
  20291. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20292. this.isBox2 = true;
  20293. this.min = min;
  20294. this.max = max;
  20295. }
  20296. set( min, max ) {
  20297. this.min.copy( min );
  20298. this.max.copy( max );
  20299. return this;
  20300. }
  20301. setFromPoints( points ) {
  20302. this.makeEmpty();
  20303. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20304. this.expandByPoint( points[ i ] );
  20305. }
  20306. return this;
  20307. }
  20308. setFromCenterAndSize( center, size ) {
  20309. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20310. this.min.copy( center ).sub( halfSize );
  20311. this.max.copy( center ).add( halfSize );
  20312. return this;
  20313. }
  20314. clone() {
  20315. return new this.constructor().copy( this );
  20316. }
  20317. copy( box ) {
  20318. this.min.copy( box.min );
  20319. this.max.copy( box.max );
  20320. return this;
  20321. }
  20322. makeEmpty() {
  20323. this.min.x = this.min.y = + Infinity;
  20324. this.max.x = this.max.y = - Infinity;
  20325. return this;
  20326. }
  20327. isEmpty() {
  20328. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20329. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20330. }
  20331. getCenter( target ) {
  20332. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20333. }
  20334. getSize( target ) {
  20335. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20336. }
  20337. expandByPoint( point ) {
  20338. this.min.min( point );
  20339. this.max.max( point );
  20340. return this;
  20341. }
  20342. expandByVector( vector ) {
  20343. this.min.sub( vector );
  20344. this.max.add( vector );
  20345. return this;
  20346. }
  20347. expandByScalar( scalar ) {
  20348. this.min.addScalar( - scalar );
  20349. this.max.addScalar( scalar );
  20350. return this;
  20351. }
  20352. containsPoint( point ) {
  20353. return point.x >= this.min.x && point.x <= this.max.x &&
  20354. point.y >= this.min.y && point.y <= this.max.y;
  20355. }
  20356. containsBox( box ) {
  20357. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20358. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20359. }
  20360. getParameter( point, target ) {
  20361. // This can potentially have a divide by zero if the box
  20362. // has a size dimension of 0.
  20363. return target.set(
  20364. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20365. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20366. );
  20367. }
  20368. intersectsBox( box ) {
  20369. // using 4 splitting planes to rule out intersections
  20370. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  20371. box.max.y >= this.min.y && box.min.y <= this.max.y;
  20372. }
  20373. clampPoint( point, target ) {
  20374. return target.copy( point ).clamp( this.min, this.max );
  20375. }
  20376. distanceToPoint( point ) {
  20377. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20378. }
  20379. intersect( box ) {
  20380. this.min.max( box.min );
  20381. this.max.min( box.max );
  20382. if ( this.isEmpty() ) this.makeEmpty();
  20383. return this;
  20384. }
  20385. union( box ) {
  20386. this.min.min( box.min );
  20387. this.max.max( box.max );
  20388. return this;
  20389. }
  20390. translate( offset ) {
  20391. this.min.add( offset );
  20392. this.max.add( offset );
  20393. return this;
  20394. }
  20395. equals( box ) {
  20396. return box.min.equals( this.min ) && box.max.equals( this.max );
  20397. }
  20398. }
  20399. const _startP = /*@__PURE__*/ new Vector3();
  20400. const _startEnd = /*@__PURE__*/ new Vector3();
  20401. class Line3 {
  20402. constructor( start = new Vector3(), end = new Vector3() ) {
  20403. this.start = start;
  20404. this.end = end;
  20405. }
  20406. set( start, end ) {
  20407. this.start.copy( start );
  20408. this.end.copy( end );
  20409. return this;
  20410. }
  20411. copy( line ) {
  20412. this.start.copy( line.start );
  20413. this.end.copy( line.end );
  20414. return this;
  20415. }
  20416. getCenter( target ) {
  20417. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20418. }
  20419. delta( target ) {
  20420. return target.subVectors( this.end, this.start );
  20421. }
  20422. distanceSq() {
  20423. return this.start.distanceToSquared( this.end );
  20424. }
  20425. distance() {
  20426. return this.start.distanceTo( this.end );
  20427. }
  20428. at( t, target ) {
  20429. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20430. }
  20431. closestPointToPointParameter( point, clampToLine ) {
  20432. _startP.subVectors( point, this.start );
  20433. _startEnd.subVectors( this.end, this.start );
  20434. const startEnd2 = _startEnd.dot( _startEnd );
  20435. const startEnd_startP = _startEnd.dot( _startP );
  20436. let t = startEnd_startP / startEnd2;
  20437. if ( clampToLine ) {
  20438. t = clamp$1( t, 0, 1 );
  20439. }
  20440. return t;
  20441. }
  20442. closestPointToPoint( point, clampToLine, target ) {
  20443. const t = this.closestPointToPointParameter( point, clampToLine );
  20444. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20445. }
  20446. applyMatrix4( matrix ) {
  20447. this.start.applyMatrix4( matrix );
  20448. this.end.applyMatrix4( matrix );
  20449. return this;
  20450. }
  20451. equals( line ) {
  20452. return line.start.equals( this.start ) && line.end.equals( this.end );
  20453. }
  20454. clone() {
  20455. return new this.constructor().copy( this );
  20456. }
  20457. }
  20458. const _vector$3 = /*@__PURE__*/ new Vector3();
  20459. class SpotLightHelper extends Object3D {
  20460. constructor( light, color ) {
  20461. super();
  20462. this.light = light;
  20463. this.matrixAutoUpdate = false;
  20464. this.color = color;
  20465. this.type = 'SpotLightHelper';
  20466. const geometry = new BufferGeometry();
  20467. const positions = [
  20468. 0, 0, 0, 0, 0, 1,
  20469. 0, 0, 0, 1, 0, 1,
  20470. 0, 0, 0, - 1, 0, 1,
  20471. 0, 0, 0, 0, 1, 1,
  20472. 0, 0, 0, 0, - 1, 1
  20473. ];
  20474. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20475. const p1 = ( i / l ) * Math.PI * 2;
  20476. const p2 = ( j / l ) * Math.PI * 2;
  20477. positions.push(
  20478. Math.cos( p1 ), Math.sin( p1 ), 1,
  20479. Math.cos( p2 ), Math.sin( p2 ), 1
  20480. );
  20481. }
  20482. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20483. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20484. this.cone = new LineSegments( geometry, material );
  20485. this.add( this.cone );
  20486. this.update();
  20487. }
  20488. dispose() {
  20489. this.cone.geometry.dispose();
  20490. this.cone.material.dispose();
  20491. }
  20492. update() {
  20493. this.light.updateWorldMatrix( true, false );
  20494. this.light.target.updateWorldMatrix( true, false );
  20495. // update the local matrix based on the parent and light target transforms
  20496. if ( this.parent ) {
  20497. this.parent.updateWorldMatrix( true );
  20498. this.matrix
  20499. .copy( this.parent.matrixWorld )
  20500. .invert()
  20501. .multiply( this.light.matrixWorld );
  20502. } else {
  20503. this.matrix.copy( this.light.matrixWorld );
  20504. }
  20505. this.matrixWorld.copy( this.light.matrixWorld );
  20506. const coneLength = this.light.distance ? this.light.distance : 1000;
  20507. const coneWidth = coneLength * Math.tan( this.light.angle );
  20508. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20509. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20510. this.cone.lookAt( _vector$3 );
  20511. if ( this.color !== undefined ) {
  20512. this.cone.material.color.set( this.color );
  20513. } else {
  20514. this.cone.material.color.copy( this.light.color );
  20515. }
  20516. }
  20517. }
  20518. const _vector$2 = /*@__PURE__*/ new Vector3();
  20519. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20520. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20521. class SkeletonHelper extends LineSegments {
  20522. constructor( object ) {
  20523. const bones = getBoneList( object );
  20524. const geometry = new BufferGeometry();
  20525. const vertices = [];
  20526. const colors = [];
  20527. const color1 = new Color( 0, 0, 1 );
  20528. const color2 = new Color( 0, 1, 0 );
  20529. for ( let i = 0; i < bones.length; i ++ ) {
  20530. const bone = bones[ i ];
  20531. if ( bone.parent && bone.parent.isBone ) {
  20532. vertices.push( 0, 0, 0 );
  20533. vertices.push( 0, 0, 0 );
  20534. colors.push( color1.r, color1.g, color1.b );
  20535. colors.push( color2.r, color2.g, color2.b );
  20536. }
  20537. }
  20538. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20539. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20540. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20541. super( geometry, material );
  20542. this.isSkeletonHelper = true;
  20543. this.type = 'SkeletonHelper';
  20544. this.root = object;
  20545. this.bones = bones;
  20546. this.matrix = object.matrixWorld;
  20547. this.matrixAutoUpdate = false;
  20548. }
  20549. updateMatrixWorld( force ) {
  20550. const bones = this.bones;
  20551. const geometry = this.geometry;
  20552. const position = geometry.getAttribute( 'position' );
  20553. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20554. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20555. const bone = bones[ i ];
  20556. if ( bone.parent && bone.parent.isBone ) {
  20557. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20558. _vector$2.setFromMatrixPosition( _boneMatrix );
  20559. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20560. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20561. _vector$2.setFromMatrixPosition( _boneMatrix );
  20562. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20563. j += 2;
  20564. }
  20565. }
  20566. geometry.getAttribute( 'position' ).needsUpdate = true;
  20567. super.updateMatrixWorld( force );
  20568. }
  20569. dispose() {
  20570. this.geometry.dispose();
  20571. this.material.dispose();
  20572. }
  20573. }
  20574. function getBoneList( object ) {
  20575. const boneList = [];
  20576. if ( object.isBone === true ) {
  20577. boneList.push( object );
  20578. }
  20579. for ( let i = 0; i < object.children.length; i ++ ) {
  20580. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20581. }
  20582. return boneList;
  20583. }
  20584. class PointLightHelper extends Mesh {
  20585. constructor( light, sphereSize, color ) {
  20586. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20587. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20588. super( geometry, material );
  20589. this.light = light;
  20590. this.color = color;
  20591. this.type = 'PointLightHelper';
  20592. this.matrix = this.light.matrixWorld;
  20593. this.matrixAutoUpdate = false;
  20594. this.update();
  20595. /*
  20596. // TODO: delete this comment?
  20597. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20598. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20599. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20600. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20601. const d = light.distance;
  20602. if ( d === 0.0 ) {
  20603. this.lightDistance.visible = false;
  20604. } else {
  20605. this.lightDistance.scale.set( d, d, d );
  20606. }
  20607. this.add( this.lightDistance );
  20608. */
  20609. }
  20610. dispose() {
  20611. this.geometry.dispose();
  20612. this.material.dispose();
  20613. }
  20614. update() {
  20615. this.light.updateWorldMatrix( true, false );
  20616. if ( this.color !== undefined ) {
  20617. this.material.color.set( this.color );
  20618. } else {
  20619. this.material.color.copy( this.light.color );
  20620. }
  20621. /*
  20622. const d = this.light.distance;
  20623. if ( d === 0.0 ) {
  20624. this.lightDistance.visible = false;
  20625. } else {
  20626. this.lightDistance.visible = true;
  20627. this.lightDistance.scale.set( d, d, d );
  20628. }
  20629. */
  20630. }
  20631. }
  20632. const _vector$1 = /*@__PURE__*/ new Vector3();
  20633. const _color1 = /*@__PURE__*/ new Color();
  20634. const _color2 = /*@__PURE__*/ new Color();
  20635. class HemisphereLightHelper extends Object3D {
  20636. constructor( light, size, color ) {
  20637. super();
  20638. this.light = light;
  20639. this.matrix = light.matrixWorld;
  20640. this.matrixAutoUpdate = false;
  20641. this.color = color;
  20642. this.type = 'HemisphereLightHelper';
  20643. const geometry = new OctahedronGeometry( size );
  20644. geometry.rotateY( Math.PI * 0.5 );
  20645. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20646. if ( this.color === undefined ) this.material.vertexColors = true;
  20647. const position = geometry.getAttribute( 'position' );
  20648. const colors = new Float32Array( position.count * 3 );
  20649. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20650. this.add( new Mesh( geometry, this.material ) );
  20651. this.update();
  20652. }
  20653. dispose() {
  20654. this.children[ 0 ].geometry.dispose();
  20655. this.children[ 0 ].material.dispose();
  20656. }
  20657. update() {
  20658. const mesh = this.children[ 0 ];
  20659. if ( this.color !== undefined ) {
  20660. this.material.color.set( this.color );
  20661. } else {
  20662. const colors = mesh.geometry.getAttribute( 'color' );
  20663. _color1.copy( this.light.color );
  20664. _color2.copy( this.light.groundColor );
  20665. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20666. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20667. colors.setXYZ( i, color.r, color.g, color.b );
  20668. }
  20669. colors.needsUpdate = true;
  20670. }
  20671. this.light.updateWorldMatrix( true, false );
  20672. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20673. }
  20674. }
  20675. class GridHelper extends LineSegments {
  20676. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20677. color1 = new Color( color1 );
  20678. color2 = new Color( color2 );
  20679. const center = divisions / 2;
  20680. const step = size / divisions;
  20681. const halfSize = size / 2;
  20682. const vertices = [], colors = [];
  20683. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20684. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20685. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20686. const color = i === center ? color1 : color2;
  20687. color.toArray( colors, j ); j += 3;
  20688. color.toArray( colors, j ); j += 3;
  20689. color.toArray( colors, j ); j += 3;
  20690. color.toArray( colors, j ); j += 3;
  20691. }
  20692. const geometry = new BufferGeometry();
  20693. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20694. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20695. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20696. super( geometry, material );
  20697. this.type = 'GridHelper';
  20698. }
  20699. dispose() {
  20700. this.geometry.dispose();
  20701. this.material.dispose();
  20702. }
  20703. }
  20704. class PolarGridHelper extends LineSegments {
  20705. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20706. color1 = new Color( color1 );
  20707. color2 = new Color( color2 );
  20708. const vertices = [];
  20709. const colors = [];
  20710. // create the sectors
  20711. if ( sectors > 1 ) {
  20712. for ( let i = 0; i < sectors; i ++ ) {
  20713. const v = ( i / sectors ) * ( Math.PI * 2 );
  20714. const x = Math.sin( v ) * radius;
  20715. const z = Math.cos( v ) * radius;
  20716. vertices.push( 0, 0, 0 );
  20717. vertices.push( x, 0, z );
  20718. const color = ( i & 1 ) ? color1 : color2;
  20719. colors.push( color.r, color.g, color.b );
  20720. colors.push( color.r, color.g, color.b );
  20721. }
  20722. }
  20723. // create the rings
  20724. for ( let i = 0; i < rings; i ++ ) {
  20725. const color = ( i & 1 ) ? color1 : color2;
  20726. const r = radius - ( radius / rings * i );
  20727. for ( let j = 0; j < divisions; j ++ ) {
  20728. // first vertex
  20729. let v = ( j / divisions ) * ( Math.PI * 2 );
  20730. let x = Math.sin( v ) * r;
  20731. let z = Math.cos( v ) * r;
  20732. vertices.push( x, 0, z );
  20733. colors.push( color.r, color.g, color.b );
  20734. // second vertex
  20735. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20736. x = Math.sin( v ) * r;
  20737. z = Math.cos( v ) * r;
  20738. vertices.push( x, 0, z );
  20739. colors.push( color.r, color.g, color.b );
  20740. }
  20741. }
  20742. const geometry = new BufferGeometry();
  20743. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20744. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20745. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20746. super( geometry, material );
  20747. this.type = 'PolarGridHelper';
  20748. }
  20749. dispose() {
  20750. this.geometry.dispose();
  20751. this.material.dispose();
  20752. }
  20753. }
  20754. const _v1 = /*@__PURE__*/ new Vector3();
  20755. const _v2 = /*@__PURE__*/ new Vector3();
  20756. const _v3 = /*@__PURE__*/ new Vector3();
  20757. class DirectionalLightHelper extends Object3D {
  20758. constructor( light, size, color ) {
  20759. super();
  20760. this.light = light;
  20761. this.matrix = light.matrixWorld;
  20762. this.matrixAutoUpdate = false;
  20763. this.color = color;
  20764. this.type = 'DirectionalLightHelper';
  20765. if ( size === undefined ) size = 1;
  20766. let geometry = new BufferGeometry();
  20767. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20768. - size, size, 0,
  20769. size, size, 0,
  20770. size, - size, 0,
  20771. - size, - size, 0,
  20772. - size, size, 0
  20773. ], 3 ) );
  20774. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20775. this.lightPlane = new Line( geometry, material );
  20776. this.add( this.lightPlane );
  20777. geometry = new BufferGeometry();
  20778. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  20779. this.targetLine = new Line( geometry, material );
  20780. this.add( this.targetLine );
  20781. this.update();
  20782. }
  20783. dispose() {
  20784. this.lightPlane.geometry.dispose();
  20785. this.lightPlane.material.dispose();
  20786. this.targetLine.geometry.dispose();
  20787. this.targetLine.material.dispose();
  20788. }
  20789. update() {
  20790. this.light.updateWorldMatrix( true, false );
  20791. this.light.target.updateWorldMatrix( true, false );
  20792. _v1.setFromMatrixPosition( this.light.matrixWorld );
  20793. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20794. _v3.subVectors( _v2, _v1 );
  20795. this.lightPlane.lookAt( _v2 );
  20796. if ( this.color !== undefined ) {
  20797. this.lightPlane.material.color.set( this.color );
  20798. this.targetLine.material.color.set( this.color );
  20799. } else {
  20800. this.lightPlane.material.color.copy( this.light.color );
  20801. this.targetLine.material.color.copy( this.light.color );
  20802. }
  20803. this.targetLine.lookAt( _v2 );
  20804. this.targetLine.scale.z = _v3.length();
  20805. }
  20806. }
  20807. const _vector = /*@__PURE__*/ new Vector3();
  20808. const _camera$1 = /*@__PURE__*/ new Camera();
  20809. /**
  20810. * - shows frustum, line of sight and up of the camera
  20811. * - suitable for fast updates
  20812. * - based on frustum visualization in lightgl.js shadowmap example
  20813. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  20814. */
  20815. class CameraHelper extends LineSegments {
  20816. constructor( camera ) {
  20817. const geometry = new BufferGeometry();
  20818. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  20819. const vertices = [];
  20820. const colors = [];
  20821. const pointMap = {};
  20822. // near
  20823. addLine( 'n1', 'n2' );
  20824. addLine( 'n2', 'n4' );
  20825. addLine( 'n4', 'n3' );
  20826. addLine( 'n3', 'n1' );
  20827. // far
  20828. addLine( 'f1', 'f2' );
  20829. addLine( 'f2', 'f4' );
  20830. addLine( 'f4', 'f3' );
  20831. addLine( 'f3', 'f1' );
  20832. // sides
  20833. addLine( 'n1', 'f1' );
  20834. addLine( 'n2', 'f2' );
  20835. addLine( 'n3', 'f3' );
  20836. addLine( 'n4', 'f4' );
  20837. // cone
  20838. addLine( 'p', 'n1' );
  20839. addLine( 'p', 'n2' );
  20840. addLine( 'p', 'n3' );
  20841. addLine( 'p', 'n4' );
  20842. // up
  20843. addLine( 'u1', 'u2' );
  20844. addLine( 'u2', 'u3' );
  20845. addLine( 'u3', 'u1' );
  20846. // target
  20847. addLine( 'c', 't' );
  20848. addLine( 'p', 'c' );
  20849. // cross
  20850. addLine( 'cn1', 'cn2' );
  20851. addLine( 'cn3', 'cn4' );
  20852. addLine( 'cf1', 'cf2' );
  20853. addLine( 'cf3', 'cf4' );
  20854. function addLine( a, b ) {
  20855. addPoint( a );
  20856. addPoint( b );
  20857. }
  20858. function addPoint( id ) {
  20859. vertices.push( 0, 0, 0 );
  20860. colors.push( 0, 0, 0 );
  20861. if ( pointMap[ id ] === undefined ) {
  20862. pointMap[ id ] = [];
  20863. }
  20864. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  20865. }
  20866. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20867. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20868. super( geometry, material );
  20869. this.type = 'CameraHelper';
  20870. this.camera = camera;
  20871. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  20872. this.matrix = camera.matrixWorld;
  20873. this.matrixAutoUpdate = false;
  20874. this.pointMap = pointMap;
  20875. this.update();
  20876. // colors
  20877. const colorFrustum = new Color( 0xffaa00 );
  20878. const colorCone = new Color( 0xff0000 );
  20879. const colorUp = new Color( 0x00aaff );
  20880. const colorTarget = new Color( 0xffffff );
  20881. const colorCross = new Color( 0x333333 );
  20882. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  20883. }
  20884. setColors( frustum, cone, up, target, cross ) {
  20885. const geometry = this.geometry;
  20886. const colorAttribute = geometry.getAttribute( 'color' );
  20887. // near
  20888. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  20889. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  20890. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  20891. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  20892. // far
  20893. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  20894. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  20895. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  20896. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  20897. // sides
  20898. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  20899. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  20900. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  20901. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  20902. // cone
  20903. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  20904. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  20905. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  20906. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  20907. // up
  20908. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  20909. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  20910. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  20911. // target
  20912. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  20913. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  20914. // cross
  20915. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  20916. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  20917. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  20918. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  20919. colorAttribute.needsUpdate = true;
  20920. }
  20921. update() {
  20922. const geometry = this.geometry;
  20923. const pointMap = this.pointMap;
  20924. const w = 1, h = 1;
  20925. // we need just camera projection matrix inverse
  20926. // world matrix must be identity
  20927. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  20928. // center / target
  20929. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  20930. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  20931. // near
  20932. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  20933. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  20934. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  20935. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  20936. // far
  20937. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  20938. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  20939. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  20940. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  20941. // up
  20942. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  20943. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  20944. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  20945. // cross
  20946. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  20947. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  20948. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  20949. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  20950. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  20951. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  20952. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  20953. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  20954. geometry.getAttribute( 'position' ).needsUpdate = true;
  20955. }
  20956. dispose() {
  20957. this.geometry.dispose();
  20958. this.material.dispose();
  20959. }
  20960. }
  20961. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  20962. _vector.set( x, y, z ).unproject( camera );
  20963. const points = pointMap[ point ];
  20964. if ( points !== undefined ) {
  20965. const position = geometry.getAttribute( 'position' );
  20966. for ( let i = 0, l = points.length; i < l; i ++ ) {
  20967. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  20968. }
  20969. }
  20970. }
  20971. const _box = /*@__PURE__*/ new Box3();
  20972. class BoxHelper extends LineSegments {
  20973. constructor( object, color = 0xffff00 ) {
  20974. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  20975. const positions = new Float32Array( 8 * 3 );
  20976. const geometry = new BufferGeometry();
  20977. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  20978. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  20979. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  20980. this.object = object;
  20981. this.type = 'BoxHelper';
  20982. this.matrixAutoUpdate = false;
  20983. this.update();
  20984. }
  20985. update( object ) {
  20986. if ( object !== undefined ) {
  20987. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  20988. }
  20989. if ( this.object !== undefined ) {
  20990. _box.setFromObject( this.object );
  20991. }
  20992. if ( _box.isEmpty() ) return;
  20993. const min = _box.min;
  20994. const max = _box.max;
  20995. /*
  20996. 5____4
  20997. 1/___0/|
  20998. | 6__|_7
  20999. 2/___3/
  21000. 0: max.x, max.y, max.z
  21001. 1: min.x, max.y, max.z
  21002. 2: min.x, min.y, max.z
  21003. 3: max.x, min.y, max.z
  21004. 4: max.x, max.y, min.z
  21005. 5: min.x, max.y, min.z
  21006. 6: min.x, min.y, min.z
  21007. 7: max.x, min.y, min.z
  21008. */
  21009. const position = this.geometry.attributes.position;
  21010. const array = position.array;
  21011. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  21012. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  21013. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  21014. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  21015. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  21016. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  21017. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  21018. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  21019. position.needsUpdate = true;
  21020. this.geometry.computeBoundingSphere();
  21021. }
  21022. setFromObject( object ) {
  21023. this.object = object;
  21024. this.update();
  21025. return this;
  21026. }
  21027. copy( source, recursive ) {
  21028. super.copy( source, recursive );
  21029. this.object = source.object;
  21030. return this;
  21031. }
  21032. dispose() {
  21033. this.geometry.dispose();
  21034. this.material.dispose();
  21035. }
  21036. }
  21037. class Box3Helper extends LineSegments {
  21038. constructor( box, color = 0xffff00 ) {
  21039. const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  21040. const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  21041. const geometry = new BufferGeometry();
  21042. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21043. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21044. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21045. this.box = box;
  21046. this.type = 'Box3Helper';
  21047. this.geometry.computeBoundingSphere();
  21048. }
  21049. updateMatrixWorld( force ) {
  21050. const box = this.box;
  21051. if ( box.isEmpty() ) return;
  21052. box.getCenter( this.position );
  21053. box.getSize( this.scale );
  21054. this.scale.multiplyScalar( 0.5 );
  21055. super.updateMatrixWorld( force );
  21056. }
  21057. dispose() {
  21058. this.geometry.dispose();
  21059. this.material.dispose();
  21060. }
  21061. }
  21062. class PlaneHelper extends Line {
  21063. constructor( plane, size = 1, hex = 0xffff00 ) {
  21064. const color = hex;
  21065. const positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ];
  21066. const geometry = new BufferGeometry();
  21067. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21068. geometry.computeBoundingSphere();
  21069. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21070. this.type = 'PlaneHelper';
  21071. this.plane = plane;
  21072. this.size = size;
  21073. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  21074. const geometry2 = new BufferGeometry();
  21075. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  21076. geometry2.computeBoundingSphere();
  21077. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  21078. }
  21079. updateMatrixWorld( force ) {
  21080. this.position.set( 0, 0, 0 );
  21081. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21082. this.lookAt( this.plane.normal );
  21083. this.translateZ( - this.plane.constant );
  21084. super.updateMatrixWorld( force );
  21085. }
  21086. dispose() {
  21087. this.geometry.dispose();
  21088. this.material.dispose();
  21089. this.children[ 0 ].geometry.dispose();
  21090. this.children[ 0 ].material.dispose();
  21091. }
  21092. }
  21093. const _axis = /*@__PURE__*/ new Vector3();
  21094. let _lineGeometry, _coneGeometry;
  21095. class ArrowHelper extends Object3D {
  21096. // dir is assumed to be normalized
  21097. constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21098. super();
  21099. this.type = 'ArrowHelper';
  21100. if ( _lineGeometry === undefined ) {
  21101. _lineGeometry = new BufferGeometry();
  21102. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21103. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21104. _coneGeometry.translate( 0, - 0.5, 0 );
  21105. }
  21106. this.position.copy( origin );
  21107. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21108. this.line.matrixAutoUpdate = false;
  21109. this.add( this.line );
  21110. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21111. this.cone.matrixAutoUpdate = false;
  21112. this.add( this.cone );
  21113. this.setDirection( dir );
  21114. this.setLength( length, headLength, headWidth );
  21115. }
  21116. setDirection( dir ) {
  21117. // dir is assumed to be normalized
  21118. if ( dir.y > 0.99999 ) {
  21119. this.quaternion.set( 0, 0, 0, 1 );
  21120. } else if ( dir.y < - 0.99999 ) {
  21121. this.quaternion.set( 1, 0, 0, 0 );
  21122. } else {
  21123. _axis.set( dir.z, 0, - dir.x ).normalize();
  21124. const radians = Math.acos( dir.y );
  21125. this.quaternion.setFromAxisAngle( _axis, radians );
  21126. }
  21127. }
  21128. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21129. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21130. this.line.updateMatrix();
  21131. this.cone.scale.set( headWidth, headLength, headWidth );
  21132. this.cone.position.y = length;
  21133. this.cone.updateMatrix();
  21134. }
  21135. setColor( color ) {
  21136. this.line.material.color.set( color );
  21137. this.cone.material.color.set( color );
  21138. }
  21139. copy( source ) {
  21140. super.copy( source, false );
  21141. this.line.copy( source.line );
  21142. this.cone.copy( source.cone );
  21143. return this;
  21144. }
  21145. dispose() {
  21146. this.line.geometry.dispose();
  21147. this.line.material.dispose();
  21148. this.cone.geometry.dispose();
  21149. this.cone.material.dispose();
  21150. }
  21151. }
  21152. class AxesHelper extends LineSegments {
  21153. constructor( size = 1 ) {
  21154. const vertices = [
  21155. 0, 0, 0, size, 0, 0,
  21156. 0, 0, 0, 0, size, 0,
  21157. 0, 0, 0, 0, 0, size
  21158. ];
  21159. const colors = [
  21160. 1, 0, 0, 1, 0.6, 0,
  21161. 0, 1, 0, 0.6, 1, 0,
  21162. 0, 0, 1, 0, 0.6, 1
  21163. ];
  21164. const geometry = new BufferGeometry();
  21165. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21166. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21167. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21168. super( geometry, material );
  21169. this.type = 'AxesHelper';
  21170. }
  21171. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21172. const color = new Color();
  21173. const array = this.geometry.attributes.color.array;
  21174. color.set( xAxisColor );
  21175. color.toArray( array, 0 );
  21176. color.toArray( array, 3 );
  21177. color.set( yAxisColor );
  21178. color.toArray( array, 6 );
  21179. color.toArray( array, 9 );
  21180. color.set( zAxisColor );
  21181. color.toArray( array, 12 );
  21182. color.toArray( array, 15 );
  21183. this.geometry.attributes.color.needsUpdate = true;
  21184. return this;
  21185. }
  21186. dispose() {
  21187. this.geometry.dispose();
  21188. this.material.dispose();
  21189. }
  21190. }
  21191. class ShapePath {
  21192. constructor() {
  21193. this.type = 'ShapePath';
  21194. this.color = new Color();
  21195. this.subPaths = [];
  21196. this.currentPath = null;
  21197. }
  21198. moveTo( x, y ) {
  21199. this.currentPath = new Path();
  21200. this.subPaths.push( this.currentPath );
  21201. this.currentPath.moveTo( x, y );
  21202. return this;
  21203. }
  21204. lineTo( x, y ) {
  21205. this.currentPath.lineTo( x, y );
  21206. return this;
  21207. }
  21208. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21209. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21210. return this;
  21211. }
  21212. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21213. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21214. return this;
  21215. }
  21216. splineThru( pts ) {
  21217. this.currentPath.splineThru( pts );
  21218. return this;
  21219. }
  21220. toShapes( isCCW ) {
  21221. function toShapesNoHoles( inSubpaths ) {
  21222. const shapes = [];
  21223. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21224. const tmpPath = inSubpaths[ i ];
  21225. const tmpShape = new Shape();
  21226. tmpShape.curves = tmpPath.curves;
  21227. shapes.push( tmpShape );
  21228. }
  21229. return shapes;
  21230. }
  21231. function isPointInsidePolygon( inPt, inPolygon ) {
  21232. const polyLen = inPolygon.length;
  21233. // inPt on polygon contour => immediate success or
  21234. // toggling of inside/outside at every single! intersection point of an edge
  21235. // with the horizontal line through inPt, left of inPt
  21236. // not counting lowerY endpoints of edges and whole edges on that line
  21237. let inside = false;
  21238. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21239. let edgeLowPt = inPolygon[ p ];
  21240. let edgeHighPt = inPolygon[ q ];
  21241. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21242. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21243. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21244. // not parallel
  21245. if ( edgeDy < 0 ) {
  21246. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21247. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21248. }
  21249. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21250. if ( inPt.y === edgeLowPt.y ) {
  21251. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21252. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21253. } else {
  21254. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21255. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21256. if ( perpEdge < 0 ) continue;
  21257. inside = ! inside; // true intersection left of inPt
  21258. }
  21259. } else {
  21260. // parallel or collinear
  21261. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21262. // edge lies on the same horizontal line as inPt
  21263. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21264. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21265. // continue;
  21266. }
  21267. }
  21268. return inside;
  21269. }
  21270. const isClockWise = ShapeUtils.isClockWise;
  21271. const subPaths = this.subPaths;
  21272. if ( subPaths.length === 0 ) return [];
  21273. let solid, tmpPath, tmpShape;
  21274. const shapes = [];
  21275. if ( subPaths.length === 1 ) {
  21276. tmpPath = subPaths[ 0 ];
  21277. tmpShape = new Shape();
  21278. tmpShape.curves = tmpPath.curves;
  21279. shapes.push( tmpShape );
  21280. return shapes;
  21281. }
  21282. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21283. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21284. // console.log("Holes first", holesFirst);
  21285. const betterShapeHoles = [];
  21286. const newShapes = [];
  21287. let newShapeHoles = [];
  21288. let mainIdx = 0;
  21289. let tmpPoints;
  21290. newShapes[ mainIdx ] = undefined;
  21291. newShapeHoles[ mainIdx ] = [];
  21292. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21293. tmpPath = subPaths[ i ];
  21294. tmpPoints = tmpPath.getPoints();
  21295. solid = isClockWise( tmpPoints );
  21296. solid = isCCW ? ! solid : solid;
  21297. if ( solid ) {
  21298. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21299. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21300. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21301. if ( holesFirst ) mainIdx ++;
  21302. newShapeHoles[ mainIdx ] = [];
  21303. //console.log('cw', i);
  21304. } else {
  21305. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21306. //console.log('ccw', i);
  21307. }
  21308. }
  21309. // only Holes? -> probably all Shapes with wrong orientation
  21310. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21311. if ( newShapes.length > 1 ) {
  21312. let ambiguous = false;
  21313. let toChange = 0;
  21314. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21315. betterShapeHoles[ sIdx ] = [];
  21316. }
  21317. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21318. const sho = newShapeHoles[ sIdx ];
  21319. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21320. const ho = sho[ hIdx ];
  21321. let hole_unassigned = true;
  21322. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21323. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21324. if ( sIdx !== s2Idx ) toChange ++;
  21325. if ( hole_unassigned ) {
  21326. hole_unassigned = false;
  21327. betterShapeHoles[ s2Idx ].push( ho );
  21328. } else {
  21329. ambiguous = true;
  21330. }
  21331. }
  21332. }
  21333. if ( hole_unassigned ) {
  21334. betterShapeHoles[ sIdx ].push( ho );
  21335. }
  21336. }
  21337. }
  21338. if ( toChange > 0 && ambiguous === false ) {
  21339. newShapeHoles = betterShapeHoles;
  21340. }
  21341. }
  21342. let tmpHoles;
  21343. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21344. tmpShape = newShapes[ i ].s;
  21345. shapes.push( tmpShape );
  21346. tmpHoles = newShapeHoles[ i ];
  21347. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21348. tmpShape.holes.push( tmpHoles[ j ].h );
  21349. }
  21350. }
  21351. //console.log("shape", shapes);
  21352. return shapes;
  21353. }
  21354. }
  21355. class Controls extends EventDispatcher {
  21356. constructor( object, domElement = null ) {
  21357. super();
  21358. this.object = object;
  21359. this.domElement = domElement;
  21360. this.enabled = true;
  21361. this.state = - 1;
  21362. this.keys = {};
  21363. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  21364. this.touches = { ONE: null, TWO: null };
  21365. }
  21366. connect() {}
  21367. disconnect() {}
  21368. dispose() {}
  21369. update( /* delta */ ) {}
  21370. }
  21371. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21372. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21373. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21374. super( width, height, { ...options, count } );
  21375. this.isWebGLMultipleRenderTargets = true;
  21376. }
  21377. get texture() {
  21378. return this.textures;
  21379. }
  21380. }
  21381. const refreshUniforms = [
  21382. 'alphaMap',
  21383. 'alphaTest',
  21384. 'anisotropy',
  21385. 'anisotropyMap',
  21386. 'anisotropyRotation',
  21387. 'aoMap',
  21388. 'attenuationColor',
  21389. 'attenuationDistance',
  21390. 'bumpMap',
  21391. 'clearcoat',
  21392. 'clearcoatMap',
  21393. 'clearcoatNormalMap',
  21394. 'clearcoatNormalScale',
  21395. 'clearcoatRoughness',
  21396. 'color',
  21397. 'dispersion',
  21398. 'displacementMap',
  21399. 'emissive',
  21400. 'emissiveMap',
  21401. 'envMap',
  21402. 'gradientMap',
  21403. 'ior',
  21404. 'iridescence',
  21405. 'iridescenceIOR',
  21406. 'iridescenceMap',
  21407. 'iridescenceThicknessMap',
  21408. 'lightMap',
  21409. 'map',
  21410. 'matcap',
  21411. 'metalness',
  21412. 'metalnessMap',
  21413. 'normalMap',
  21414. 'normalScale',
  21415. 'opacity',
  21416. 'roughness',
  21417. 'roughnessMap',
  21418. 'sheen',
  21419. 'sheenColor',
  21420. 'sheenColorMap',
  21421. 'sheenRoughnessMap',
  21422. 'shininess',
  21423. 'specular',
  21424. 'specularColor',
  21425. 'specularColorMap',
  21426. 'specularIntensity',
  21427. 'specularIntensityMap',
  21428. 'specularMap',
  21429. 'thickness',
  21430. 'transmission',
  21431. 'transmissionMap'
  21432. ];
  21433. class NodeMaterialObserver {
  21434. constructor( builder ) {
  21435. this.renderObjects = new WeakMap();
  21436. this.hasNode = this.containsNode( builder );
  21437. this.hasAnimation = builder.object.isSkinnedMesh === true;
  21438. this.refreshUniforms = refreshUniforms;
  21439. this.renderId = 0;
  21440. }
  21441. firstInitialization( renderObject ) {
  21442. const hasInitialized = this.renderObjects.has( renderObject );
  21443. if ( hasInitialized === false ) {
  21444. this.getRenderObjectData( renderObject );
  21445. return true;
  21446. }
  21447. return false;
  21448. }
  21449. getRenderObjectData( renderObject ) {
  21450. let data = this.renderObjects.get( renderObject );
  21451. if ( data === undefined ) {
  21452. data = {
  21453. material: this.getMaterialData( renderObject.material ),
  21454. worldMatrix: renderObject.object.matrixWorld.clone()
  21455. };
  21456. if ( renderObject.object.morphTargetInfluences ) {
  21457. data.morphTargetInfluences = renderObject.object.morphTargetInfluences.slice();
  21458. }
  21459. if ( renderObject.bundle !== null ) {
  21460. data.version = renderObject.bundle.version;
  21461. }
  21462. this.renderObjects.set( renderObject, data );
  21463. }
  21464. return data;
  21465. }
  21466. containsNode( builder ) {
  21467. const material = builder.material;
  21468. for ( const property in material ) {
  21469. if ( material[ property ] && material[ property ].isNode )
  21470. return true;
  21471. }
  21472. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  21473. return true;
  21474. return false;
  21475. }
  21476. getMaterialData( material ) {
  21477. const data = {};
  21478. for ( const property of this.refreshUniforms ) {
  21479. const value = material[ property ];
  21480. if ( value === null || value === undefined ) continue;
  21481. if ( typeof value === 'object' && value.clone !== undefined ) {
  21482. if ( value.isTexture === true ) {
  21483. data[ property ] = { id: value.id, version: value.version };
  21484. } else {
  21485. data[ property ] = value.clone();
  21486. }
  21487. } else {
  21488. data[ property ] = value;
  21489. }
  21490. }
  21491. return data;
  21492. }
  21493. equals( renderObject ) {
  21494. const { object, material } = renderObject;
  21495. const renderObjectData = this.getRenderObjectData( renderObject );
  21496. // world matrix
  21497. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  21498. renderObjectData.worldMatrix.copy( object.matrixWorld );
  21499. return false;
  21500. }
  21501. // material
  21502. const materialData = renderObjectData.material;
  21503. for ( const property in materialData ) {
  21504. const value = materialData[ property ];
  21505. const mtlValue = material[ property ];
  21506. if ( value.equals !== undefined ) {
  21507. if ( value.equals( mtlValue ) === false ) {
  21508. value.copy( mtlValue );
  21509. return false;
  21510. }
  21511. } else if ( mtlValue.isTexture === true ) {
  21512. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  21513. value.id = mtlValue.id;
  21514. value.version = mtlValue.version;
  21515. return false;
  21516. }
  21517. } else if ( value !== mtlValue ) {
  21518. materialData[ property ] = mtlValue;
  21519. return false;
  21520. }
  21521. }
  21522. // morph targets
  21523. if ( renderObjectData.morphTargetInfluences ) {
  21524. let morphChanged = false;
  21525. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  21526. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  21527. morphChanged = true;
  21528. }
  21529. }
  21530. if ( morphChanged ) return true;
  21531. }
  21532. // bundle
  21533. if ( renderObject.bundle !== null ) {
  21534. renderObjectData.version = renderObject.bundle.version;
  21535. }
  21536. return true;
  21537. }
  21538. needsRefresh( renderObject, nodeFrame ) {
  21539. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  21540. return true;
  21541. const { renderId } = nodeFrame;
  21542. if ( this.renderId !== renderId ) {
  21543. this.renderId = renderId;
  21544. return true;
  21545. }
  21546. const isStatic = renderObject.object.static === true;
  21547. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  21548. if ( isStatic || isBundle )
  21549. return false;
  21550. const notEqual = this.equals( renderObject ) !== true;
  21551. return notEqual;
  21552. }
  21553. }
  21554. function getCacheKey$1( object, force = false ) {
  21555. let cacheKey = '{';
  21556. if ( object.isNode === true ) {
  21557. cacheKey += object.id;
  21558. object = object.getSelf();
  21559. }
  21560. for ( const { property, childNode } of getNodeChildren( object ) ) {
  21561. cacheKey += ',' + property.slice( 0, - 4 ) + ':' + childNode.getCacheKey( force );
  21562. }
  21563. cacheKey += '}';
  21564. return cacheKey;
  21565. }
  21566. function* getNodeChildren( node, toJSON = false ) {
  21567. for ( const property in node ) {
  21568. // Ignore private properties.
  21569. if ( property.startsWith( '_' ) === true ) continue;
  21570. const object = node[ property ];
  21571. if ( Array.isArray( object ) === true ) {
  21572. for ( let i = 0; i < object.length; i ++ ) {
  21573. const child = object[ i ];
  21574. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21575. yield { property, index: i, childNode: child };
  21576. }
  21577. }
  21578. } else if ( object && object.isNode === true ) {
  21579. yield { property, childNode: object };
  21580. } else if ( typeof object === 'object' ) {
  21581. for ( const subProperty in object ) {
  21582. const child = object[ subProperty ];
  21583. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21584. yield { property, index: subProperty, childNode: child };
  21585. }
  21586. }
  21587. }
  21588. }
  21589. }
  21590. function getValueType( value ) {
  21591. if ( value === undefined || value === null ) return null;
  21592. const typeOf = typeof value;
  21593. if ( value.isNode === true ) {
  21594. return 'node';
  21595. } else if ( typeOf === 'number' ) {
  21596. return 'float';
  21597. } else if ( typeOf === 'boolean' ) {
  21598. return 'bool';
  21599. } else if ( typeOf === 'string' ) {
  21600. return 'string';
  21601. } else if ( typeOf === 'function' ) {
  21602. return 'shader';
  21603. } else if ( value.isVector2 === true ) {
  21604. return 'vec2';
  21605. } else if ( value.isVector3 === true ) {
  21606. return 'vec3';
  21607. } else if ( value.isVector4 === true ) {
  21608. return 'vec4';
  21609. } else if ( value.isMatrix3 === true ) {
  21610. return 'mat3';
  21611. } else if ( value.isMatrix4 === true ) {
  21612. return 'mat4';
  21613. } else if ( value.isColor === true ) {
  21614. return 'color';
  21615. } else if ( value instanceof ArrayBuffer ) {
  21616. return 'ArrayBuffer';
  21617. }
  21618. return null;
  21619. }
  21620. function getValueFromType( type, ...params ) {
  21621. const last4 = type ? type.slice( - 4 ) : undefined;
  21622. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  21623. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  21624. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  21625. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  21626. }
  21627. if ( type === 'color' ) {
  21628. return new Color( ...params );
  21629. } else if ( last4 === 'vec2' ) {
  21630. return new Vector2( ...params );
  21631. } else if ( last4 === 'vec3' ) {
  21632. return new Vector3( ...params );
  21633. } else if ( last4 === 'vec4' ) {
  21634. return new Vector4( ...params );
  21635. } else if ( last4 === 'mat3' ) {
  21636. return new Matrix3( ...params );
  21637. } else if ( last4 === 'mat4' ) {
  21638. return new Matrix4( ...params );
  21639. } else if ( type === 'bool' ) {
  21640. return params[ 0 ] || false;
  21641. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  21642. return params[ 0 ] || 0;
  21643. } else if ( type === 'string' ) {
  21644. return params[ 0 ] || '';
  21645. } else if ( type === 'ArrayBuffer' ) {
  21646. return base64ToArrayBuffer( params[ 0 ] );
  21647. }
  21648. return null;
  21649. }
  21650. function arrayBufferToBase64( arrayBuffer ) {
  21651. let chars = '';
  21652. const array = new Uint8Array( arrayBuffer );
  21653. for ( let i = 0; i < array.length; i ++ ) {
  21654. chars += String.fromCharCode( array[ i ] );
  21655. }
  21656. return btoa( chars );
  21657. }
  21658. function base64ToArrayBuffer( base64 ) {
  21659. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  21660. }
  21661. var NodeUtils = /*#__PURE__*/Object.freeze({
  21662. __proto__: null,
  21663. arrayBufferToBase64: arrayBufferToBase64,
  21664. base64ToArrayBuffer: base64ToArrayBuffer,
  21665. getCacheKey: getCacheKey$1,
  21666. getNodeChildren: getNodeChildren,
  21667. getValueFromType: getValueFromType,
  21668. getValueType: getValueType
  21669. });
  21670. const NodeShaderStage = {
  21671. VERTEX: 'vertex',
  21672. FRAGMENT: 'fragment'
  21673. };
  21674. const NodeUpdateType = {
  21675. NONE: 'none',
  21676. FRAME: 'frame',
  21677. RENDER: 'render',
  21678. OBJECT: 'object'
  21679. };
  21680. const NodeType = {
  21681. BOOLEAN: 'bool',
  21682. INTEGER: 'int',
  21683. FLOAT: 'float',
  21684. VECTOR2: 'vec2',
  21685. VECTOR3: 'vec3',
  21686. VECTOR4: 'vec4',
  21687. MATRIX2: 'mat2',
  21688. MATRIX3: 'mat3',
  21689. MATRIX4: 'mat4'
  21690. };
  21691. const defaultShaderStages = [ 'fragment', 'vertex' ];
  21692. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  21693. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  21694. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  21695. let _nodeId = 0;
  21696. class Node extends EventDispatcher {
  21697. static get type() {
  21698. return 'Node';
  21699. }
  21700. constructor( nodeType = null ) {
  21701. super();
  21702. this.nodeType = nodeType;
  21703. this.updateType = NodeUpdateType.NONE;
  21704. this.updateBeforeType = NodeUpdateType.NONE;
  21705. this.updateAfterType = NodeUpdateType.NONE;
  21706. this.uuid = MathUtils.generateUUID();
  21707. this.version = 0;
  21708. this._cacheKey = null;
  21709. this._cacheKeyVersion = 0;
  21710. this.global = false;
  21711. this.isNode = true;
  21712. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  21713. }
  21714. set needsUpdate( value ) {
  21715. if ( value === true ) {
  21716. this.version ++;
  21717. }
  21718. }
  21719. get type() {
  21720. return this.constructor.type;
  21721. }
  21722. onUpdate( callback, updateType ) {
  21723. this.updateType = updateType;
  21724. this.update = callback.bind( this.getSelf() );
  21725. return this;
  21726. }
  21727. onFrameUpdate( callback ) {
  21728. return this.onUpdate( callback, NodeUpdateType.FRAME );
  21729. }
  21730. onRenderUpdate( callback ) {
  21731. return this.onUpdate( callback, NodeUpdateType.RENDER );
  21732. }
  21733. onObjectUpdate( callback ) {
  21734. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  21735. }
  21736. onReference( callback ) {
  21737. this.updateReference = callback.bind( this.getSelf() );
  21738. return this;
  21739. }
  21740. getSelf() {
  21741. // Returns non-node object.
  21742. return this.self || this;
  21743. }
  21744. updateReference( /*state*/ ) {
  21745. return this;
  21746. }
  21747. isGlobal( /*builder*/ ) {
  21748. return this.global;
  21749. }
  21750. * getChildren() {
  21751. for ( const { childNode } of getNodeChildren( this ) ) {
  21752. yield childNode;
  21753. }
  21754. }
  21755. dispose() {
  21756. this.dispatchEvent( { type: 'dispose' } );
  21757. }
  21758. traverse( callback ) {
  21759. callback( this );
  21760. for ( const childNode of this.getChildren() ) {
  21761. childNode.traverse( callback );
  21762. }
  21763. }
  21764. getCacheKey( force = false ) {
  21765. force = force || this.version !== this._cacheKeyVersion;
  21766. if ( force === true || this._cacheKey === null ) {
  21767. this._cacheKey = getCacheKey$1( this, force );
  21768. this._cacheKeyVersion = this.version;
  21769. }
  21770. return this._cacheKey;
  21771. }
  21772. getScope() {
  21773. return this;
  21774. }
  21775. getHash( /*builder*/ ) {
  21776. return this.uuid;
  21777. }
  21778. getUpdateType() {
  21779. return this.updateType;
  21780. }
  21781. getUpdateBeforeType() {
  21782. return this.updateBeforeType;
  21783. }
  21784. getUpdateAfterType() {
  21785. return this.updateAfterType;
  21786. }
  21787. getElementType( builder ) {
  21788. const type = this.getNodeType( builder );
  21789. const elementType = builder.getElementType( type );
  21790. return elementType;
  21791. }
  21792. getNodeType( builder ) {
  21793. const nodeProperties = builder.getNodeProperties( this );
  21794. if ( nodeProperties.outputNode ) {
  21795. return nodeProperties.outputNode.getNodeType( builder );
  21796. }
  21797. return this.nodeType;
  21798. }
  21799. getShared( builder ) {
  21800. const hash = this.getHash( builder );
  21801. const nodeFromHash = builder.getNodeFromHash( hash );
  21802. return nodeFromHash || this;
  21803. }
  21804. setup( builder ) {
  21805. const nodeProperties = builder.getNodeProperties( this );
  21806. let index = 0;
  21807. for ( const childNode of this.getChildren() ) {
  21808. nodeProperties[ 'node' + index ++ ] = childNode;
  21809. }
  21810. // return a outputNode if exists
  21811. return null;
  21812. }
  21813. analyze( builder ) {
  21814. const usageCount = builder.increaseUsage( this );
  21815. if ( usageCount === 1 ) {
  21816. // node flow children
  21817. const nodeProperties = builder.getNodeProperties( this );
  21818. for ( const childNode of Object.values( nodeProperties ) ) {
  21819. if ( childNode && childNode.isNode === true ) {
  21820. childNode.build( builder );
  21821. }
  21822. }
  21823. }
  21824. }
  21825. generate( builder, output ) {
  21826. const { outputNode } = builder.getNodeProperties( this );
  21827. if ( outputNode && outputNode.isNode === true ) {
  21828. return outputNode.build( builder, output );
  21829. }
  21830. }
  21831. updateBefore( /*frame*/ ) {
  21832. console.warn( 'Abstract function.' );
  21833. }
  21834. updateAfter( /*frame*/ ) {
  21835. console.warn( 'Abstract function.' );
  21836. }
  21837. update( /*frame*/ ) {
  21838. console.warn( 'Abstract function.' );
  21839. }
  21840. build( builder, output = null ) {
  21841. const refNode = this.getShared( builder );
  21842. if ( this !== refNode ) {
  21843. return refNode.build( builder, output );
  21844. }
  21845. builder.addNode( this );
  21846. builder.addChain( this );
  21847. /* Build stages expected results:
  21848. - "setup" -> Node
  21849. - "analyze" -> null
  21850. - "generate" -> String
  21851. */
  21852. let result = null;
  21853. const buildStage = builder.getBuildStage();
  21854. if ( buildStage === 'setup' ) {
  21855. this.updateReference( builder );
  21856. const properties = builder.getNodeProperties( this );
  21857. if ( properties.initialized !== true ) {
  21858. const stackNodesBeforeSetup = builder.stack.nodes.length;
  21859. properties.initialized = true;
  21860. properties.outputNode = this.setup( builder );
  21861. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  21862. for ( const childNode of Object.values( properties ) ) {
  21863. if ( childNode && childNode.isNode === true ) {
  21864. childNode.build( builder );
  21865. }
  21866. }
  21867. }
  21868. } else if ( buildStage === 'analyze' ) {
  21869. this.analyze( builder );
  21870. } else if ( buildStage === 'generate' ) {
  21871. const isGenerateOnce = this.generate.length === 1;
  21872. if ( isGenerateOnce ) {
  21873. const type = this.getNodeType( builder );
  21874. const nodeData = builder.getDataFromNode( this );
  21875. result = nodeData.snippet;
  21876. if ( result === undefined ) {
  21877. result = this.generate( builder ) || '';
  21878. nodeData.snippet = result;
  21879. }
  21880. result = builder.format( result, type, output );
  21881. } else {
  21882. result = this.generate( builder, output ) || '';
  21883. }
  21884. }
  21885. builder.removeChain( this );
  21886. return result;
  21887. }
  21888. getSerializeChildren() {
  21889. return getNodeChildren( this );
  21890. }
  21891. serialize( json ) {
  21892. const nodeChildren = this.getSerializeChildren();
  21893. const inputNodes = {};
  21894. for ( const { property, index, childNode } of nodeChildren ) {
  21895. if ( index !== undefined ) {
  21896. if ( inputNodes[ property ] === undefined ) {
  21897. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  21898. }
  21899. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  21900. } else {
  21901. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  21902. }
  21903. }
  21904. if ( Object.keys( inputNodes ).length > 0 ) {
  21905. json.inputNodes = inputNodes;
  21906. }
  21907. }
  21908. deserialize( json ) {
  21909. if ( json.inputNodes !== undefined ) {
  21910. const nodes = json.meta.nodes;
  21911. for ( const property in json.inputNodes ) {
  21912. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  21913. const inputArray = [];
  21914. for ( const uuid of json.inputNodes[ property ] ) {
  21915. inputArray.push( nodes[ uuid ] );
  21916. }
  21917. this[ property ] = inputArray;
  21918. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  21919. const inputObject = {};
  21920. for ( const subProperty in json.inputNodes[ property ] ) {
  21921. const uuid = json.inputNodes[ property ][ subProperty ];
  21922. inputObject[ subProperty ] = nodes[ uuid ];
  21923. }
  21924. this[ property ] = inputObject;
  21925. } else {
  21926. const uuid = json.inputNodes[ property ];
  21927. this[ property ] = nodes[ uuid ];
  21928. }
  21929. }
  21930. }
  21931. }
  21932. toJSON( meta ) {
  21933. const { uuid, type } = this;
  21934. const isRoot = ( meta === undefined || typeof meta === 'string' );
  21935. if ( isRoot ) {
  21936. meta = {
  21937. textures: {},
  21938. images: {},
  21939. nodes: {}
  21940. };
  21941. }
  21942. // serialize
  21943. let data = meta.nodes[ uuid ];
  21944. if ( data === undefined ) {
  21945. data = {
  21946. uuid,
  21947. type,
  21948. meta,
  21949. metadata: {
  21950. version: 4.6,
  21951. type: 'Node',
  21952. generator: 'Node.toJSON'
  21953. }
  21954. };
  21955. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  21956. this.serialize( data );
  21957. delete data.meta;
  21958. }
  21959. // TODO: Copied from Object3D.toJSON
  21960. function extractFromCache( cache ) {
  21961. const values = [];
  21962. for ( const key in cache ) {
  21963. const data = cache[ key ];
  21964. delete data.metadata;
  21965. values.push( data );
  21966. }
  21967. return values;
  21968. }
  21969. if ( isRoot ) {
  21970. const textures = extractFromCache( meta.textures );
  21971. const images = extractFromCache( meta.images );
  21972. const nodes = extractFromCache( meta.nodes );
  21973. if ( textures.length > 0 ) data.textures = textures;
  21974. if ( images.length > 0 ) data.images = images;
  21975. if ( nodes.length > 0 ) data.nodes = nodes;
  21976. }
  21977. return data;
  21978. }
  21979. }
  21980. class ArrayElementNode extends Node {
  21981. static get type() {
  21982. return 'ArrayElementNode';
  21983. } // @TODO: If extending from TempNode it breaks webgpu_compute
  21984. constructor( node, indexNode ) {
  21985. super();
  21986. this.node = node;
  21987. this.indexNode = indexNode;
  21988. this.isArrayElementNode = true;
  21989. }
  21990. getNodeType( builder ) {
  21991. return this.node.getElementType( builder );
  21992. }
  21993. generate( builder ) {
  21994. const nodeSnippet = this.node.build( builder );
  21995. const indexSnippet = this.indexNode.build( builder, 'uint' );
  21996. return `${nodeSnippet}[ ${indexSnippet} ]`;
  21997. }
  21998. }
  21999. class ConvertNode extends Node {
  22000. static get type() {
  22001. return 'ConvertNode';
  22002. }
  22003. constructor( node, convertTo ) {
  22004. super();
  22005. this.node = node;
  22006. this.convertTo = convertTo;
  22007. }
  22008. getNodeType( builder ) {
  22009. const requestType = this.node.getNodeType( builder );
  22010. let convertTo = null;
  22011. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22012. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22013. convertTo = overloadingType;
  22014. }
  22015. }
  22016. return convertTo;
  22017. }
  22018. serialize( data ) {
  22019. super.serialize( data );
  22020. data.convertTo = this.convertTo;
  22021. }
  22022. deserialize( data ) {
  22023. super.deserialize( data );
  22024. this.convertTo = data.convertTo;
  22025. }
  22026. generate( builder, output ) {
  22027. const node = this.node;
  22028. const type = this.getNodeType( builder );
  22029. const snippet = node.build( builder, type );
  22030. return builder.format( snippet, type, output );
  22031. }
  22032. }
  22033. class TempNode extends Node {
  22034. static get type() {
  22035. return 'TempNode';
  22036. }
  22037. constructor( type ) {
  22038. super( type );
  22039. this.isTempNode = true;
  22040. }
  22041. hasDependencies( builder ) {
  22042. return builder.getDataFromNode( this ).usageCount > 1;
  22043. }
  22044. build( builder, output ) {
  22045. const buildStage = builder.getBuildStage();
  22046. if ( buildStage === 'generate' ) {
  22047. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22048. const nodeData = builder.getDataFromNode( this );
  22049. if ( nodeData.propertyName !== undefined ) {
  22050. return builder.format( nodeData.propertyName, type, output );
  22051. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22052. const snippet = super.build( builder, type );
  22053. const nodeVar = builder.getVarFromNode( this, null, type );
  22054. const propertyName = builder.getPropertyName( nodeVar );
  22055. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  22056. nodeData.snippet = snippet;
  22057. nodeData.propertyName = propertyName;
  22058. return builder.format( nodeData.propertyName, type, output );
  22059. }
  22060. }
  22061. return super.build( builder, output );
  22062. }
  22063. }
  22064. class JoinNode extends TempNode {
  22065. static get type() {
  22066. return 'JoinNode';
  22067. }
  22068. constructor( nodes = [], nodeType = null ) {
  22069. super( nodeType );
  22070. this.nodes = nodes;
  22071. }
  22072. getNodeType( builder ) {
  22073. if ( this.nodeType !== null ) {
  22074. return builder.getVectorType( this.nodeType );
  22075. }
  22076. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22077. }
  22078. generate( builder, output ) {
  22079. const type = this.getNodeType( builder );
  22080. const nodes = this.nodes;
  22081. const primitiveType = builder.getComponentType( type );
  22082. const snippetValues = [];
  22083. for ( const input of nodes ) {
  22084. let inputSnippet = input.build( builder );
  22085. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22086. if ( inputPrimitiveType !== primitiveType ) {
  22087. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22088. }
  22089. snippetValues.push( inputSnippet );
  22090. }
  22091. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22092. return builder.format( snippet, type, output );
  22093. }
  22094. }
  22095. const stringVectorComponents = vectorComponents.join( '' );
  22096. class SplitNode extends Node {
  22097. static get type() {
  22098. return 'SplitNode';
  22099. }
  22100. constructor( node, components = 'x' ) {
  22101. super();
  22102. this.node = node;
  22103. this.components = components;
  22104. this.isSplitNode = true;
  22105. }
  22106. getVectorLength() {
  22107. let vectorLength = this.components.length;
  22108. for ( const c of this.components ) {
  22109. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22110. }
  22111. return vectorLength;
  22112. }
  22113. getComponentType( builder ) {
  22114. return builder.getComponentType( this.node.getNodeType( builder ) );
  22115. }
  22116. getNodeType( builder ) {
  22117. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22118. }
  22119. generate( builder, output ) {
  22120. const node = this.node;
  22121. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22122. let snippet = null;
  22123. if ( nodeTypeLength > 1 ) {
  22124. let type = null;
  22125. const componentsLength = this.getVectorLength();
  22126. if ( componentsLength >= nodeTypeLength ) {
  22127. // needed expand the input node
  22128. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22129. }
  22130. const nodeSnippet = node.build( builder, type );
  22131. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22132. // unnecessary swizzle
  22133. snippet = builder.format( nodeSnippet, type, output );
  22134. } else {
  22135. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22136. }
  22137. } else {
  22138. // ignore .components if .node returns float/integer
  22139. snippet = node.build( builder, output );
  22140. }
  22141. return snippet;
  22142. }
  22143. serialize( data ) {
  22144. super.serialize( data );
  22145. data.components = this.components;
  22146. }
  22147. deserialize( data ) {
  22148. super.deserialize( data );
  22149. this.components = data.components;
  22150. }
  22151. }
  22152. class SetNode extends TempNode {
  22153. static get type() {
  22154. return 'SetNode';
  22155. }
  22156. constructor( sourceNode, components, targetNode ) {
  22157. super();
  22158. this.sourceNode = sourceNode;
  22159. this.components = components;
  22160. this.targetNode = targetNode;
  22161. }
  22162. getNodeType( builder ) {
  22163. return this.sourceNode.getNodeType( builder );
  22164. }
  22165. generate( builder ) {
  22166. const { sourceNode, components, targetNode } = this;
  22167. const sourceType = this.getNodeType( builder );
  22168. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  22169. const targetSnippet = targetNode.build( builder, targetType );
  22170. const sourceSnippet = sourceNode.build( builder, sourceType );
  22171. const length = builder.getTypeLength( sourceType );
  22172. const snippetValues = [];
  22173. for ( let i = 0; i < length; i ++ ) {
  22174. const component = vectorComponents[ i ];
  22175. if ( component === components[ 0 ] ) {
  22176. snippetValues.push( targetSnippet );
  22177. i += components.length - 1;
  22178. } else {
  22179. snippetValues.push( sourceSnippet + '.' + component );
  22180. }
  22181. }
  22182. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22183. }
  22184. }
  22185. class FlipNode extends TempNode {
  22186. static get type() {
  22187. return 'FlipNode';
  22188. }
  22189. constructor( sourceNode, components ) {
  22190. super();
  22191. this.sourceNode = sourceNode;
  22192. this.components = components;
  22193. }
  22194. getNodeType( builder ) {
  22195. return this.sourceNode.getNodeType( builder );
  22196. }
  22197. generate( builder ) {
  22198. const { components, sourceNode } = this;
  22199. const sourceType = this.getNodeType( builder );
  22200. const sourceSnippet = sourceNode.build( builder );
  22201. const sourceCache = builder.getVarFromNode( this );
  22202. const sourceProperty = builder.getPropertyName( sourceCache );
  22203. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet );
  22204. const length = builder.getTypeLength( sourceType );
  22205. const snippetValues = [];
  22206. let componentIndex = 0;
  22207. for ( let i = 0; i < length; i ++ ) {
  22208. const component = vectorComponents[ i ];
  22209. if ( component === components[ componentIndex ] ) {
  22210. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  22211. componentIndex ++;
  22212. } else {
  22213. snippetValues.push( sourceProperty + '.' + component );
  22214. }
  22215. }
  22216. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22217. }
  22218. }
  22219. class InputNode extends Node {
  22220. static get type() {
  22221. return 'InputNode';
  22222. }
  22223. constructor( value, nodeType = null ) {
  22224. super( nodeType );
  22225. this.isInputNode = true;
  22226. this.value = value;
  22227. this.precision = null;
  22228. }
  22229. getNodeType( /*builder*/ ) {
  22230. if ( this.nodeType === null ) {
  22231. return getValueType( this.value );
  22232. }
  22233. return this.nodeType;
  22234. }
  22235. getInputType( builder ) {
  22236. return this.getNodeType( builder );
  22237. }
  22238. setPrecision( precision ) {
  22239. this.precision = precision;
  22240. return this;
  22241. }
  22242. serialize( data ) {
  22243. super.serialize( data );
  22244. data.value = this.value;
  22245. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22246. data.valueType = getValueType( this.value );
  22247. data.nodeType = this.nodeType;
  22248. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22249. data.precision = this.precision;
  22250. }
  22251. deserialize( data ) {
  22252. super.deserialize( data );
  22253. this.nodeType = data.nodeType;
  22254. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22255. this.precision = data.precision || null;
  22256. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22257. }
  22258. generate( /*builder, output*/ ) {
  22259. console.warn( 'Abstract function.' );
  22260. }
  22261. }
  22262. class ConstNode extends InputNode {
  22263. static get type() {
  22264. return 'ConstNode';
  22265. }
  22266. constructor( value, nodeType = null ) {
  22267. super( value, nodeType );
  22268. this.isConstNode = true;
  22269. }
  22270. generateConst( builder ) {
  22271. return builder.generateConst( this.getNodeType( builder ), this.value );
  22272. }
  22273. generate( builder, output ) {
  22274. const type = this.getNodeType( builder );
  22275. return builder.format( this.generateConst( builder ), type, output );
  22276. }
  22277. }
  22278. //
  22279. let currentStack = null;
  22280. const NodeElements = new Map();
  22281. function addMethodChaining( name, nodeElement ) {
  22282. if ( NodeElements.has( name ) ) {
  22283. console.warn( `Redefinition of method chaining ${ name }` );
  22284. return;
  22285. }
  22286. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22287. NodeElements.set( name, nodeElement );
  22288. }
  22289. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22290. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  22291. const shaderNodeHandler = {
  22292. setup( NodeClosure, params ) {
  22293. const inputs = params.shift();
  22294. return NodeClosure( nodeObjects( inputs ), ...params );
  22295. },
  22296. get( node, prop, nodeObj ) {
  22297. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22298. if ( node.isStackNode !== true && prop === 'assign' ) {
  22299. return ( ...params ) => {
  22300. currentStack.assign( nodeObj, ...params );
  22301. return nodeObj;
  22302. };
  22303. } else if ( NodeElements.has( prop ) ) {
  22304. const nodeElement = NodeElements.get( prop );
  22305. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22306. } else if ( prop === 'self' ) {
  22307. return node;
  22308. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22309. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22310. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22311. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22312. // accessing properties ( swizzle )
  22313. prop = parseSwizzle( prop );
  22314. return nodeObject( new SplitNode( nodeObj, prop ) );
  22315. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22316. // set properties ( swizzle ) and sort to xyzw sequence
  22317. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  22318. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22319. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22320. // set properties ( swizzle ) and sort to xyzw sequence
  22321. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  22322. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  22323. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22324. // accessing property
  22325. if ( prop === 'width' ) prop = 'x';
  22326. else if ( prop === 'height' ) prop = 'y';
  22327. else if ( prop === 'depth' ) prop = 'z';
  22328. return nodeObject( new SplitNode( node, prop ) );
  22329. } else if ( /^\d+$/.test( prop ) === true ) {
  22330. // accessing array
  22331. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22332. }
  22333. }
  22334. return Reflect.get( node, prop, nodeObj );
  22335. },
  22336. set( node, prop, value, nodeObj ) {
  22337. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22338. // setting properties
  22339. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  22340. nodeObj[ prop ].assign( value );
  22341. return true;
  22342. }
  22343. }
  22344. return Reflect.set( node, prop, value, nodeObj );
  22345. }
  22346. };
  22347. const nodeObjectsCacheMap = new WeakMap();
  22348. const nodeBuilderFunctionsCacheMap = new WeakMap();
  22349. const ShaderNodeObject = function ( obj, altType = null ) {
  22350. const type = getValueType( obj );
  22351. if ( type === 'node' ) {
  22352. let nodeObject = nodeObjectsCacheMap.get( obj );
  22353. if ( nodeObject === undefined ) {
  22354. nodeObject = new Proxy( obj, shaderNodeHandler );
  22355. nodeObjectsCacheMap.set( obj, nodeObject );
  22356. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  22357. }
  22358. return nodeObject;
  22359. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  22360. return nodeObject( getConstNode( obj, altType ) );
  22361. } else if ( type === 'shader' ) {
  22362. return Fn( obj );
  22363. }
  22364. return obj;
  22365. };
  22366. const ShaderNodeObjects = function ( objects, altType = null ) {
  22367. for ( const name in objects ) {
  22368. objects[ name ] = nodeObject( objects[ name ], altType );
  22369. }
  22370. return objects;
  22371. };
  22372. const ShaderNodeArray = function ( array, altType = null ) {
  22373. const len = array.length;
  22374. for ( let i = 0; i < len; i ++ ) {
  22375. array[ i ] = nodeObject( array[ i ], altType );
  22376. }
  22377. return array;
  22378. };
  22379. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  22380. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  22381. if ( scope === null ) {
  22382. return ( ...params ) => {
  22383. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  22384. };
  22385. } else if ( factor !== null ) {
  22386. factor = nodeObject( factor );
  22387. return ( ...params ) => {
  22388. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  22389. };
  22390. } else {
  22391. return ( ...params ) => {
  22392. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  22393. };
  22394. }
  22395. };
  22396. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  22397. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  22398. };
  22399. class ShaderCallNodeInternal extends Node {
  22400. constructor( shaderNode, inputNodes ) {
  22401. super();
  22402. this.shaderNode = shaderNode;
  22403. this.inputNodes = inputNodes;
  22404. }
  22405. getNodeType( builder ) {
  22406. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  22407. }
  22408. call( builder ) {
  22409. const { shaderNode, inputNodes } = this;
  22410. const properties = builder.getNodeProperties( shaderNode );
  22411. if ( properties.onceOutput ) return properties.onceOutput;
  22412. //
  22413. let result = null;
  22414. if ( shaderNode.layout ) {
  22415. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  22416. if ( functionNodesCacheMap === undefined ) {
  22417. functionNodesCacheMap = new WeakMap();
  22418. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  22419. }
  22420. let functionNode = functionNodesCacheMap.get( shaderNode );
  22421. if ( functionNode === undefined ) {
  22422. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  22423. functionNodesCacheMap.set( shaderNode, functionNode );
  22424. }
  22425. if ( builder.currentFunctionNode !== null ) {
  22426. builder.currentFunctionNode.includes.push( functionNode );
  22427. }
  22428. result = nodeObject( functionNode.call( inputNodes ) );
  22429. } else {
  22430. const jsFunc = shaderNode.jsFunc;
  22431. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  22432. result = nodeObject( outputNode );
  22433. }
  22434. if ( shaderNode.once ) {
  22435. properties.onceOutput = result;
  22436. }
  22437. return result;
  22438. }
  22439. getOutputNode( builder ) {
  22440. const properties = builder.getNodeProperties( this );
  22441. if ( properties.outputNode === null ) {
  22442. properties.outputNode = this.setupOutput( builder );
  22443. }
  22444. return properties.outputNode;
  22445. }
  22446. setup( builder ) {
  22447. return this.getOutputNode( builder );
  22448. }
  22449. setupOutput( builder ) {
  22450. builder.addStack();
  22451. builder.stack.outputNode = this.call( builder );
  22452. return builder.removeStack();
  22453. }
  22454. generate( builder, output ) {
  22455. const outputNode = this.getOutputNode( builder );
  22456. return outputNode.build( builder, output );
  22457. }
  22458. }
  22459. class ShaderNodeInternal extends Node {
  22460. constructor( jsFunc, nodeType ) {
  22461. super( nodeType );
  22462. this.jsFunc = jsFunc;
  22463. this.layout = null;
  22464. this.global = true;
  22465. this.once = false;
  22466. }
  22467. setLayout( layout ) {
  22468. this.layout = layout;
  22469. return this;
  22470. }
  22471. call( inputs = null ) {
  22472. nodeObjects( inputs );
  22473. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  22474. }
  22475. setup() {
  22476. return this.call();
  22477. }
  22478. }
  22479. const bools = [ false, true ];
  22480. const uints = [ 0, 1, 2, 3 ];
  22481. const ints = [ - 1, - 2 ];
  22482. 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 ];
  22483. const boolsCacheMap = new Map();
  22484. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  22485. const uintsCacheMap = new Map();
  22486. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  22487. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  22488. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  22489. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  22490. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  22491. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  22492. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  22493. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  22494. const getConstNode = ( value, type ) => {
  22495. if ( constNodesCacheMap.has( value ) ) {
  22496. return constNodesCacheMap.get( value );
  22497. } else if ( value.isNode === true ) {
  22498. return value;
  22499. } else {
  22500. return new ConstNode( value, type );
  22501. }
  22502. };
  22503. const safeGetNodeType = ( node ) => {
  22504. try {
  22505. return node.getNodeType();
  22506. } catch ( _ ) {
  22507. return undefined;
  22508. }
  22509. };
  22510. const ConvertType = function ( type, cacheMap = null ) {
  22511. return ( ...params ) => {
  22512. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  22513. params = [ getValueFromType( type, ...params ) ];
  22514. }
  22515. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  22516. return nodeObject( cacheMap.get( params[ 0 ] ) );
  22517. }
  22518. if ( params.length === 1 ) {
  22519. const node = getConstNode( params[ 0 ], type );
  22520. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  22521. return nodeObject( new ConvertNode( node, type ) );
  22522. }
  22523. const nodes = params.map( param => getConstNode( param ) );
  22524. return nodeObject( new JoinNode( nodes, type ) );
  22525. };
  22526. };
  22527. // exports
  22528. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  22529. // utils
  22530. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  22531. // shader node base
  22532. function ShaderNode( jsFunc, nodeType ) {
  22533. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  22534. }
  22535. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  22536. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  22537. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  22538. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  22539. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  22540. const Fn = ( jsFunc, nodeType ) => {
  22541. const shaderNode = new ShaderNode( jsFunc, nodeType );
  22542. const fn = ( ...params ) => {
  22543. let inputs;
  22544. nodeObjects( params );
  22545. if ( params[ 0 ] && params[ 0 ].isNode ) {
  22546. inputs = [ ...params ];
  22547. } else {
  22548. inputs = params[ 0 ];
  22549. }
  22550. return shaderNode.call( inputs );
  22551. };
  22552. fn.shaderNode = shaderNode;
  22553. fn.setLayout = ( layout ) => {
  22554. shaderNode.setLayout( layout );
  22555. return fn;
  22556. };
  22557. fn.once = () => {
  22558. shaderNode.once = true;
  22559. return fn;
  22560. };
  22561. return fn;
  22562. };
  22563. const tslFn = ( ...params ) => { // @deprecated, r168
  22564. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  22565. return Fn( ...params );
  22566. };
  22567. //
  22568. addMethodChaining( 'toGlobal', ( node ) => {
  22569. node.global = true;
  22570. return node;
  22571. } );
  22572. //
  22573. const setCurrentStack = ( stack ) => {
  22574. currentStack = stack;
  22575. };
  22576. const getCurrentStack = () => currentStack;
  22577. const If = ( ...params ) => currentStack.If( ...params );
  22578. function append( node ) {
  22579. if ( currentStack ) currentStack.add( node );
  22580. return node;
  22581. }
  22582. addMethodChaining( 'append', append );
  22583. // types
  22584. const color = new ConvertType( 'color' );
  22585. const float = new ConvertType( 'float', cacheMaps.float );
  22586. const int = new ConvertType( 'int', cacheMaps.ints );
  22587. const uint = new ConvertType( 'uint', cacheMaps.uint );
  22588. const bool = new ConvertType( 'bool', cacheMaps.bool );
  22589. const vec2 = new ConvertType( 'vec2' );
  22590. const ivec2 = new ConvertType( 'ivec2' );
  22591. const uvec2 = new ConvertType( 'uvec2' );
  22592. const bvec2 = new ConvertType( 'bvec2' );
  22593. const vec3 = new ConvertType( 'vec3' );
  22594. const ivec3 = new ConvertType( 'ivec3' );
  22595. const uvec3 = new ConvertType( 'uvec3' );
  22596. const bvec3 = new ConvertType( 'bvec3' );
  22597. const vec4 = new ConvertType( 'vec4' );
  22598. const ivec4 = new ConvertType( 'ivec4' );
  22599. const uvec4 = new ConvertType( 'uvec4' );
  22600. const bvec4 = new ConvertType( 'bvec4' );
  22601. const mat2 = new ConvertType( 'mat2' );
  22602. const mat3 = new ConvertType( 'mat3' );
  22603. const mat4 = new ConvertType( 'mat4' );
  22604. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  22605. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  22606. addMethodChaining( 'toColor', color );
  22607. addMethodChaining( 'toFloat', float );
  22608. addMethodChaining( 'toInt', int );
  22609. addMethodChaining( 'toUint', uint );
  22610. addMethodChaining( 'toBool', bool );
  22611. addMethodChaining( 'toVec2', vec2 );
  22612. addMethodChaining( 'toIVec2', ivec2 );
  22613. addMethodChaining( 'toUVec2', uvec2 );
  22614. addMethodChaining( 'toBVec2', bvec2 );
  22615. addMethodChaining( 'toVec3', vec3 );
  22616. addMethodChaining( 'toIVec3', ivec3 );
  22617. addMethodChaining( 'toUVec3', uvec3 );
  22618. addMethodChaining( 'toBVec3', bvec3 );
  22619. addMethodChaining( 'toVec4', vec4 );
  22620. addMethodChaining( 'toIVec4', ivec4 );
  22621. addMethodChaining( 'toUVec4', uvec4 );
  22622. addMethodChaining( 'toBVec4', bvec4 );
  22623. addMethodChaining( 'toMat2', mat2 );
  22624. addMethodChaining( 'toMat3', mat3 );
  22625. addMethodChaining( 'toMat4', mat4 );
  22626. // basic nodes
  22627. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  22628. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  22629. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  22630. addMethodChaining( 'element', element );
  22631. addMethodChaining( 'convert', convert );
  22632. class UniformGroupNode extends Node {
  22633. static get type() {
  22634. return 'UniformGroupNode';
  22635. }
  22636. constructor( name, shared = false, order = 1 ) {
  22637. super( 'string' );
  22638. this.name = name;
  22639. this.version = 0;
  22640. this.shared = shared;
  22641. this.order = order;
  22642. this.isUniformGroup = true;
  22643. }
  22644. set needsUpdate( value ) {
  22645. if ( value === true ) this.version ++;
  22646. }
  22647. serialize( data ) {
  22648. super.serialize( data );
  22649. data.name = this.name;
  22650. data.version = this.version;
  22651. data.shared = this.shared;
  22652. }
  22653. deserialize( data ) {
  22654. super.deserialize( data );
  22655. this.name = data.name;
  22656. this.version = data.version;
  22657. this.shared = data.shared;
  22658. }
  22659. }
  22660. const uniformGroup = ( name ) => new UniformGroupNode( name );
  22661. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  22662. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  22663. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  22664. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  22665. class UniformNode extends InputNode {
  22666. static get type() {
  22667. return 'UniformNode';
  22668. }
  22669. constructor( value, nodeType = null ) {
  22670. super( value, nodeType );
  22671. this.isUniformNode = true;
  22672. this.name = '';
  22673. this.groupNode = objectGroup;
  22674. }
  22675. label( name ) {
  22676. this.name = name;
  22677. return this;
  22678. }
  22679. setGroup( group ) {
  22680. this.groupNode = group;
  22681. return this;
  22682. }
  22683. getGroup() {
  22684. return this.groupNode;
  22685. }
  22686. getUniformHash( builder ) {
  22687. return this.getHash( builder );
  22688. }
  22689. onUpdate( callback, updateType ) {
  22690. const self = this.getSelf();
  22691. callback = callback.bind( self );
  22692. return super.onUpdate( ( frame ) => {
  22693. const value = callback( frame, self );
  22694. if ( value !== undefined ) {
  22695. this.value = value;
  22696. }
  22697. }, updateType );
  22698. }
  22699. generate( builder, output ) {
  22700. const type = this.getNodeType( builder );
  22701. const hash = this.getUniformHash( builder );
  22702. let sharedNode = builder.getNodeFromHash( hash );
  22703. if ( sharedNode === undefined ) {
  22704. builder.setHashNode( this, hash );
  22705. sharedNode = this;
  22706. }
  22707. const sharedNodeType = sharedNode.getInputType( builder );
  22708. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  22709. const propertyName = builder.getPropertyName( nodeUniform );
  22710. if ( builder.context.label !== undefined ) delete builder.context.label;
  22711. return builder.format( propertyName, type, output );
  22712. }
  22713. }
  22714. const uniform = ( arg1, arg2 ) => {
  22715. const nodeType = getConstNodeType( arg2 || arg1 );
  22716. // @TODO: get ConstNode from .traverse() in the future
  22717. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  22718. return nodeObject( new UniformNode( value, nodeType ) );
  22719. };
  22720. class PropertyNode extends Node {
  22721. static get type() {
  22722. return 'PropertyNode';
  22723. }
  22724. constructor( nodeType, name = null, varying = false ) {
  22725. super( nodeType );
  22726. this.name = name;
  22727. this.varying = varying;
  22728. this.isPropertyNode = true;
  22729. }
  22730. getHash( builder ) {
  22731. return this.name || super.getHash( builder );
  22732. }
  22733. isGlobal( /*builder*/ ) {
  22734. return true;
  22735. }
  22736. generate( builder ) {
  22737. let nodeVar;
  22738. if ( this.varying === true ) {
  22739. nodeVar = builder.getVaryingFromNode( this, this.name );
  22740. nodeVar.needsInterpolation = true;
  22741. } else {
  22742. nodeVar = builder.getVarFromNode( this, this.name );
  22743. }
  22744. return builder.getPropertyName( nodeVar );
  22745. }
  22746. }
  22747. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  22748. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  22749. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  22750. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  22751. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  22752. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  22753. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  22754. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  22755. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  22756. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  22757. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  22758. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  22759. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  22760. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  22761. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  22762. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  22763. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  22764. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  22765. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  22766. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  22767. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  22768. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  22769. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  22770. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  22771. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  22772. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  22773. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  22774. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  22775. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  22776. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  22777. class AssignNode extends TempNode {
  22778. static get type() {
  22779. return 'AssignNode';
  22780. }
  22781. constructor( targetNode, sourceNode ) {
  22782. super();
  22783. this.targetNode = targetNode;
  22784. this.sourceNode = sourceNode;
  22785. }
  22786. hasDependencies() {
  22787. return false;
  22788. }
  22789. getNodeType( builder, output ) {
  22790. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  22791. }
  22792. needsSplitAssign( builder ) {
  22793. const { targetNode } = this;
  22794. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  22795. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  22796. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  22797. return assignDiferentVector;
  22798. }
  22799. return false;
  22800. }
  22801. generate( builder, output ) {
  22802. const { targetNode, sourceNode } = this;
  22803. const needsSplitAssign = this.needsSplitAssign( builder );
  22804. const targetType = targetNode.getNodeType( builder );
  22805. const target = targetNode.context( { assign: true } ).build( builder );
  22806. const source = sourceNode.build( builder, targetType );
  22807. const sourceType = sourceNode.getNodeType( builder );
  22808. const nodeData = builder.getDataFromNode( this );
  22809. //
  22810. let snippet;
  22811. if ( nodeData.initialized === true ) {
  22812. if ( output !== 'void' ) {
  22813. snippet = target;
  22814. }
  22815. } else if ( needsSplitAssign ) {
  22816. const sourceVar = builder.getVarFromNode( this, null, targetType );
  22817. const sourceProperty = builder.getPropertyName( sourceVar );
  22818. builder.addLineFlowCode( `${ sourceProperty } = ${ source }` );
  22819. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  22820. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  22821. const component = targetNode.components[ i ];
  22822. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]` );
  22823. }
  22824. if ( output !== 'void' ) {
  22825. snippet = target;
  22826. }
  22827. } else {
  22828. snippet = `${ target } = ${ source }`;
  22829. if ( output === 'void' || sourceType === 'void' ) {
  22830. builder.addLineFlowCode( snippet );
  22831. if ( output !== 'void' ) {
  22832. snippet = target;
  22833. }
  22834. }
  22835. }
  22836. nodeData.initialized = true;
  22837. return builder.format( snippet, targetType, output );
  22838. }
  22839. }
  22840. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  22841. addMethodChaining( 'assign', assign );
  22842. class FunctionCallNode extends TempNode {
  22843. static get type() {
  22844. return 'FunctionCallNode';
  22845. }
  22846. constructor( functionNode = null, parameters = {} ) {
  22847. super();
  22848. this.functionNode = functionNode;
  22849. this.parameters = parameters;
  22850. }
  22851. setParameters( parameters ) {
  22852. this.parameters = parameters;
  22853. return this;
  22854. }
  22855. getParameters() {
  22856. return this.parameters;
  22857. }
  22858. getNodeType( builder ) {
  22859. return this.functionNode.getNodeType( builder );
  22860. }
  22861. generate( builder ) {
  22862. const params = [];
  22863. const functionNode = this.functionNode;
  22864. const inputs = functionNode.getInputs( builder );
  22865. const parameters = this.parameters;
  22866. if ( Array.isArray( parameters ) ) {
  22867. for ( let i = 0; i < parameters.length; i ++ ) {
  22868. const inputNode = inputs[ i ];
  22869. const node = parameters[ i ];
  22870. params.push( node.build( builder, inputNode.type ) );
  22871. }
  22872. } else {
  22873. for ( const inputNode of inputs ) {
  22874. const node = parameters[ inputNode.name ];
  22875. if ( node !== undefined ) {
  22876. params.push( node.build( builder, inputNode.type ) );
  22877. } else {
  22878. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  22879. }
  22880. }
  22881. }
  22882. const functionName = functionNode.build( builder, 'property' );
  22883. return `${functionName}( ${params.join( ', ' )} )`;
  22884. }
  22885. }
  22886. const call = ( func, ...params ) => {
  22887. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  22888. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  22889. };
  22890. addMethodChaining( 'call', call );
  22891. class OperatorNode extends TempNode {
  22892. static get type() {
  22893. return 'OperatorNode';
  22894. }
  22895. constructor( op, aNode, bNode, ...params ) {
  22896. super();
  22897. if ( params.length > 0 ) {
  22898. let finalOp = new OperatorNode( op, aNode, bNode );
  22899. for ( let i = 0; i < params.length - 1; i ++ ) {
  22900. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  22901. }
  22902. aNode = finalOp;
  22903. bNode = params[ params.length - 1 ];
  22904. }
  22905. this.op = op;
  22906. this.aNode = aNode;
  22907. this.bNode = bNode;
  22908. }
  22909. getNodeType( builder, output ) {
  22910. const op = this.op;
  22911. const aNode = this.aNode;
  22912. const bNode = this.bNode;
  22913. const typeA = aNode.getNodeType( builder );
  22914. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  22915. if ( typeA === 'void' || typeB === 'void' ) {
  22916. return 'void';
  22917. } else if ( op === '%' ) {
  22918. return typeA;
  22919. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  22920. return builder.getIntegerType( typeA );
  22921. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  22922. return 'bool';
  22923. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  22924. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  22925. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  22926. } else {
  22927. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  22928. return typeB;
  22929. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  22930. // matrix x vector
  22931. return builder.getVectorFromMatrix( typeA );
  22932. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  22933. // vector x matrix
  22934. return builder.getVectorFromMatrix( typeB );
  22935. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  22936. // anytype x anytype: use the greater length vector
  22937. return typeB;
  22938. }
  22939. return typeA;
  22940. }
  22941. }
  22942. generate( builder, output ) {
  22943. const op = this.op;
  22944. const aNode = this.aNode;
  22945. const bNode = this.bNode;
  22946. const type = this.getNodeType( builder, output );
  22947. let typeA = null;
  22948. let typeB = null;
  22949. if ( type !== 'void' ) {
  22950. typeA = aNode.getNodeType( builder );
  22951. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  22952. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  22953. if ( builder.isVector( typeA ) ) {
  22954. typeB = typeA;
  22955. } else if ( typeA !== typeB ) {
  22956. typeA = typeB = 'float';
  22957. }
  22958. } else if ( op === '>>' || op === '<<' ) {
  22959. typeA = type;
  22960. typeB = builder.changeComponentType( typeB, 'uint' );
  22961. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  22962. // matrix x vector
  22963. typeB = builder.getVectorFromMatrix( typeA );
  22964. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  22965. // vector x matrix
  22966. typeA = builder.getVectorFromMatrix( typeB );
  22967. } else {
  22968. // anytype x anytype
  22969. typeA = typeB = type;
  22970. }
  22971. } else {
  22972. typeA = typeB = type;
  22973. }
  22974. const a = aNode.build( builder, typeA );
  22975. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  22976. const outputLength = builder.getTypeLength( output );
  22977. const fnOpSnippet = builder.getFunctionOperator( op );
  22978. if ( output !== 'void' ) {
  22979. if ( op === '<' && outputLength > 1 ) {
  22980. if ( builder.useComparisonMethod ) {
  22981. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  22982. } else {
  22983. return builder.format( `( ${ a } < ${ b } )`, type, output );
  22984. }
  22985. } else if ( op === '<=' && outputLength > 1 ) {
  22986. if ( builder.useComparisonMethod ) {
  22987. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  22988. } else {
  22989. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  22990. }
  22991. } else if ( op === '>' && outputLength > 1 ) {
  22992. if ( builder.useComparisonMethod ) {
  22993. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  22994. } else {
  22995. return builder.format( `( ${ a } > ${ b } )`, type, output );
  22996. }
  22997. } else if ( op === '>=' && outputLength > 1 ) {
  22998. if ( builder.useComparisonMethod ) {
  22999. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23000. } else {
  23001. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  23002. }
  23003. } else if ( op === '!' || op === '~' ) {
  23004. return builder.format( `(${op}${a})`, typeA, output );
  23005. } else if ( fnOpSnippet ) {
  23006. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23007. } else {
  23008. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  23009. }
  23010. } else if ( typeA !== 'void' ) {
  23011. if ( fnOpSnippet ) {
  23012. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23013. } else {
  23014. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  23015. }
  23016. }
  23017. }
  23018. serialize( data ) {
  23019. super.serialize( data );
  23020. data.op = this.op;
  23021. }
  23022. deserialize( data ) {
  23023. super.deserialize( data );
  23024. this.op = data.op;
  23025. }
  23026. }
  23027. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  23028. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  23029. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  23030. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  23031. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  23032. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  23033. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  23034. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  23035. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  23036. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  23037. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  23038. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  23039. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  23040. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  23041. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  23042. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  23043. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  23044. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  23045. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  23046. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  23047. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  23048. addMethodChaining( 'add', add );
  23049. addMethodChaining( 'sub', sub );
  23050. addMethodChaining( 'mul', mul );
  23051. addMethodChaining( 'div', div );
  23052. addMethodChaining( 'modInt', modInt );
  23053. addMethodChaining( 'equal', equal );
  23054. addMethodChaining( 'notEqual', notEqual );
  23055. addMethodChaining( 'lessThan', lessThan );
  23056. addMethodChaining( 'greaterThan', greaterThan );
  23057. addMethodChaining( 'lessThanEqual', lessThanEqual );
  23058. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  23059. addMethodChaining( 'and', and );
  23060. addMethodChaining( 'or', or );
  23061. addMethodChaining( 'not', not );
  23062. addMethodChaining( 'xor', xor );
  23063. addMethodChaining( 'bitAnd', bitAnd );
  23064. addMethodChaining( 'bitNot', bitNot );
  23065. addMethodChaining( 'bitOr', bitOr );
  23066. addMethodChaining( 'bitXor', bitXor );
  23067. addMethodChaining( 'shiftLeft', shiftLeft );
  23068. addMethodChaining( 'shiftRight', shiftRight );
  23069. const remainder = ( ...params ) => { // @deprecated, r168
  23070. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  23071. return modInt( ...params );
  23072. };
  23073. addMethodChaining( 'remainder', remainder );
  23074. class MathNode extends TempNode {
  23075. static get type() {
  23076. return 'MathNode';
  23077. }
  23078. constructor( method, aNode, bNode = null, cNode = null ) {
  23079. super();
  23080. this.method = method;
  23081. this.aNode = aNode;
  23082. this.bNode = bNode;
  23083. this.cNode = cNode;
  23084. }
  23085. getInputType( builder ) {
  23086. const aType = this.aNode.getNodeType( builder );
  23087. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  23088. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  23089. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  23090. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  23091. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  23092. if ( aLen > bLen && aLen > cLen ) {
  23093. return aType;
  23094. } else if ( bLen > cLen ) {
  23095. return bType;
  23096. } else if ( cLen > aLen ) {
  23097. return cType;
  23098. }
  23099. return aType;
  23100. }
  23101. getNodeType( builder ) {
  23102. const method = this.method;
  23103. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  23104. return 'float';
  23105. } else if ( method === MathNode.CROSS ) {
  23106. return 'vec3';
  23107. } else if ( method === MathNode.ALL ) {
  23108. return 'bool';
  23109. } else if ( method === MathNode.EQUALS ) {
  23110. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  23111. } else if ( method === MathNode.MOD ) {
  23112. return this.aNode.getNodeType( builder );
  23113. } else {
  23114. return this.getInputType( builder );
  23115. }
  23116. }
  23117. generate( builder, output ) {
  23118. const method = this.method;
  23119. const type = this.getNodeType( builder );
  23120. const inputType = this.getInputType( builder );
  23121. const a = this.aNode;
  23122. const b = this.bNode;
  23123. const c = this.cNode;
  23124. const isWebGL = builder.renderer.isWebGLRenderer === true;
  23125. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  23126. // dir can be either a direction vector or a normal vector
  23127. // upper-left 3x3 of matrix is assumed to be orthogonal
  23128. let tA = a;
  23129. let tB = b;
  23130. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  23131. tB = vec4( vec3( tB ), 0.0 );
  23132. } else {
  23133. tA = vec4( vec3( tA ), 0.0 );
  23134. }
  23135. const mulNode = mul( tA, tB ).xyz;
  23136. return normalize( mulNode ).build( builder, output );
  23137. } else if ( method === MathNode.NEGATE ) {
  23138. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  23139. } else if ( method === MathNode.ONE_MINUS ) {
  23140. return sub( 1.0, a ).build( builder, output );
  23141. } else if ( method === MathNode.RECIPROCAL ) {
  23142. return div( 1.0, a ).build( builder, output );
  23143. } else if ( method === MathNode.DIFFERENCE ) {
  23144. return abs( sub( a, b ) ).build( builder, output );
  23145. } else {
  23146. const params = [];
  23147. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  23148. params.push(
  23149. a.build( builder, type ),
  23150. b.build( builder, type )
  23151. );
  23152. } else if ( isWebGL && method === MathNode.STEP ) {
  23153. params.push(
  23154. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  23155. b.build( builder, inputType )
  23156. );
  23157. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  23158. params.push(
  23159. a.build( builder, inputType ),
  23160. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23161. );
  23162. } else if ( method === MathNode.REFRACT ) {
  23163. params.push(
  23164. a.build( builder, inputType ),
  23165. b.build( builder, inputType ),
  23166. c.build( builder, 'float' )
  23167. );
  23168. } else if ( method === MathNode.MIX ) {
  23169. params.push(
  23170. a.build( builder, inputType ),
  23171. b.build( builder, inputType ),
  23172. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23173. );
  23174. } else {
  23175. params.push( a.build( builder, inputType ) );
  23176. if ( b !== null ) params.push( b.build( builder, inputType ) );
  23177. if ( c !== null ) params.push( c.build( builder, inputType ) );
  23178. }
  23179. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  23180. }
  23181. }
  23182. serialize( data ) {
  23183. super.serialize( data );
  23184. data.method = this.method;
  23185. }
  23186. deserialize( data ) {
  23187. super.deserialize( data );
  23188. this.method = data.method;
  23189. }
  23190. }
  23191. // 1 input
  23192. MathNode.ALL = 'all';
  23193. MathNode.ANY = 'any';
  23194. MathNode.EQUALS = 'equals';
  23195. MathNode.RADIANS = 'radians';
  23196. MathNode.DEGREES = 'degrees';
  23197. MathNode.EXP = 'exp';
  23198. MathNode.EXP2 = 'exp2';
  23199. MathNode.LOG = 'log';
  23200. MathNode.LOG2 = 'log2';
  23201. MathNode.SQRT = 'sqrt';
  23202. MathNode.INVERSE_SQRT = 'inversesqrt';
  23203. MathNode.FLOOR = 'floor';
  23204. MathNode.CEIL = 'ceil';
  23205. MathNode.NORMALIZE = 'normalize';
  23206. MathNode.FRACT = 'fract';
  23207. MathNode.SIN = 'sin';
  23208. MathNode.COS = 'cos';
  23209. MathNode.TAN = 'tan';
  23210. MathNode.ASIN = 'asin';
  23211. MathNode.ACOS = 'acos';
  23212. MathNode.ATAN = 'atan';
  23213. MathNode.ABS = 'abs';
  23214. MathNode.SIGN = 'sign';
  23215. MathNode.LENGTH = 'length';
  23216. MathNode.NEGATE = 'negate';
  23217. MathNode.ONE_MINUS = 'oneMinus';
  23218. MathNode.DFDX = 'dFdx';
  23219. MathNode.DFDY = 'dFdy';
  23220. MathNode.ROUND = 'round';
  23221. MathNode.RECIPROCAL = 'reciprocal';
  23222. MathNode.TRUNC = 'trunc';
  23223. MathNode.FWIDTH = 'fwidth';
  23224. MathNode.BITCAST = 'bitcast';
  23225. MathNode.TRANSPOSE = 'transpose';
  23226. // 2 inputs
  23227. MathNode.ATAN2 = 'atan2';
  23228. MathNode.MIN = 'min';
  23229. MathNode.MAX = 'max';
  23230. MathNode.MOD = 'mod';
  23231. MathNode.STEP = 'step';
  23232. MathNode.REFLECT = 'reflect';
  23233. MathNode.DISTANCE = 'distance';
  23234. MathNode.DIFFERENCE = 'difference';
  23235. MathNode.DOT = 'dot';
  23236. MathNode.CROSS = 'cross';
  23237. MathNode.POW = 'pow';
  23238. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  23239. // 3 inputs
  23240. MathNode.MIX = 'mix';
  23241. MathNode.CLAMP = 'clamp';
  23242. MathNode.REFRACT = 'refract';
  23243. MathNode.SMOOTHSTEP = 'smoothstep';
  23244. MathNode.FACEFORWARD = 'faceforward';
  23245. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  23246. const INFINITY = /*@__PURE__*/ float( 1e6 );
  23247. const PI = /*@__PURE__*/ float( Math.PI );
  23248. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  23249. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  23250. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  23251. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  23252. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  23253. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  23254. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  23255. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  23256. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  23257. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  23258. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  23259. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  23260. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  23261. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  23262. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  23263. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  23264. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  23265. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  23266. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  23267. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  23268. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  23269. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  23270. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  23271. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  23272. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  23273. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  23274. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  23275. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  23276. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  23277. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  23278. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  23279. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  23280. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  23281. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  23282. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  23283. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  23284. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  23285. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  23286. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  23287. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  23288. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  23289. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  23290. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  23291. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  23292. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  23293. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  23294. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  23295. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  23296. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  23297. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  23298. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  23299. const lengthSq = ( a ) => dot( a, a );
  23300. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  23301. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  23302. const saturate = ( value ) => clamp( value );
  23303. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  23304. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  23305. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  23306. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  23307. const a = 12.9898, b = 78.233, c = 43758.5453;
  23308. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  23309. return fract( sin( sn ).mul( c ) );
  23310. } );
  23311. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  23312. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  23313. addMethodChaining( 'all', all );
  23314. addMethodChaining( 'any', any );
  23315. addMethodChaining( 'equals', equals );
  23316. addMethodChaining( 'radians', radians );
  23317. addMethodChaining( 'degrees', degrees );
  23318. addMethodChaining( 'exp', exp );
  23319. addMethodChaining( 'exp2', exp2 );
  23320. addMethodChaining( 'log', log );
  23321. addMethodChaining( 'log2', log2 );
  23322. addMethodChaining( 'sqrt', sqrt );
  23323. addMethodChaining( 'inverseSqrt', inverseSqrt );
  23324. addMethodChaining( 'floor', floor );
  23325. addMethodChaining( 'ceil', ceil );
  23326. addMethodChaining( 'normalize', normalize );
  23327. addMethodChaining( 'fract', fract );
  23328. addMethodChaining( 'sin', sin );
  23329. addMethodChaining( 'cos', cos );
  23330. addMethodChaining( 'tan', tan );
  23331. addMethodChaining( 'asin', asin );
  23332. addMethodChaining( 'acos', acos );
  23333. addMethodChaining( 'atan', atan );
  23334. addMethodChaining( 'abs', abs );
  23335. addMethodChaining( 'sign', sign );
  23336. addMethodChaining( 'length', length );
  23337. addMethodChaining( 'lengthSq', lengthSq );
  23338. addMethodChaining( 'negate', negate );
  23339. addMethodChaining( 'oneMinus', oneMinus );
  23340. addMethodChaining( 'dFdx', dFdx );
  23341. addMethodChaining( 'dFdy', dFdy );
  23342. addMethodChaining( 'round', round );
  23343. addMethodChaining( 'reciprocal', reciprocal );
  23344. addMethodChaining( 'trunc', trunc );
  23345. addMethodChaining( 'fwidth', fwidth );
  23346. addMethodChaining( 'atan2', atan2 );
  23347. addMethodChaining( 'min', min$1 );
  23348. addMethodChaining( 'max', max$1 );
  23349. addMethodChaining( 'mod', mod );
  23350. addMethodChaining( 'step', step );
  23351. addMethodChaining( 'reflect', reflect );
  23352. addMethodChaining( 'distance', distance );
  23353. addMethodChaining( 'dot', dot );
  23354. addMethodChaining( 'cross', cross );
  23355. addMethodChaining( 'pow', pow );
  23356. addMethodChaining( 'pow2', pow2 );
  23357. addMethodChaining( 'pow3', pow3 );
  23358. addMethodChaining( 'pow4', pow4 );
  23359. addMethodChaining( 'transformDirection', transformDirection );
  23360. addMethodChaining( 'mix', mixElement );
  23361. addMethodChaining( 'clamp', clamp );
  23362. addMethodChaining( 'refract', refract );
  23363. addMethodChaining( 'smoothstep', smoothstepElement );
  23364. addMethodChaining( 'faceForward', faceForward );
  23365. addMethodChaining( 'difference', difference );
  23366. addMethodChaining( 'saturate', saturate );
  23367. addMethodChaining( 'cbrt', cbrt );
  23368. addMethodChaining( 'transpose', transpose );
  23369. addMethodChaining( 'rand', rand );
  23370. class ConditionalNode extends Node {
  23371. static get type() {
  23372. return 'ConditionalNode';
  23373. }
  23374. constructor( condNode, ifNode, elseNode = null ) {
  23375. super();
  23376. this.condNode = condNode;
  23377. this.ifNode = ifNode;
  23378. this.elseNode = elseNode;
  23379. }
  23380. getNodeType( builder ) {
  23381. const ifType = this.ifNode.getNodeType( builder );
  23382. if ( this.elseNode !== null ) {
  23383. const elseType = this.elseNode.getNodeType( builder );
  23384. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  23385. return elseType;
  23386. }
  23387. }
  23388. return ifType;
  23389. }
  23390. setup( builder ) {
  23391. const properties = builder.getNodeProperties( this );
  23392. properties.condNode = this.condNode.cache();
  23393. properties.ifNode = this.ifNode.cache();
  23394. properties.elseNode = this.elseNode ? this.elseNode.cache() : null;
  23395. }
  23396. generate( builder, output ) {
  23397. const type = this.getNodeType( builder );
  23398. const nodeData = builder.getDataFromNode( this );
  23399. if ( nodeData.nodeProperty !== undefined ) {
  23400. return nodeData.nodeProperty;
  23401. }
  23402. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  23403. const needsOutput = output !== 'void';
  23404. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  23405. nodeData.nodeProperty = nodeProperty;
  23406. const nodeSnippet = condNode.build( builder, 'bool' );
  23407. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  23408. let ifSnippet = ifNode.build( builder, type );
  23409. if ( ifSnippet ) {
  23410. if ( needsOutput ) {
  23411. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  23412. } else {
  23413. ifSnippet = 'return ' + ifSnippet + ';';
  23414. }
  23415. }
  23416. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  23417. if ( elseNode !== null ) {
  23418. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  23419. let elseSnippet = elseNode.build( builder, type );
  23420. if ( elseSnippet ) {
  23421. if ( needsOutput ) {
  23422. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  23423. } else {
  23424. elseSnippet = 'return ' + elseSnippet + ';';
  23425. }
  23426. }
  23427. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  23428. } else {
  23429. builder.addFlowCode( '\n\n' );
  23430. }
  23431. return builder.format( nodeProperty, type, output );
  23432. }
  23433. }
  23434. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  23435. addMethodChaining( 'select', select );
  23436. //
  23437. const cond = ( ...params ) => { // @deprecated, r168
  23438. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  23439. return select( ...params );
  23440. };
  23441. addMethodChaining( 'cond', cond );
  23442. class ContextNode extends Node {
  23443. static get type() {
  23444. return 'ContextNode';
  23445. }
  23446. constructor( node, value = {} ) {
  23447. super();
  23448. this.isContextNode = true;
  23449. this.node = node;
  23450. this.value = value;
  23451. }
  23452. getScope() {
  23453. return this.node.getScope();
  23454. }
  23455. getNodeType( builder ) {
  23456. return this.node.getNodeType( builder );
  23457. }
  23458. analyze( builder ) {
  23459. this.node.build( builder );
  23460. }
  23461. setup( builder ) {
  23462. const previousContext = builder.getContext();
  23463. builder.setContext( { ...builder.context, ...this.value } );
  23464. const node = this.node.build( builder );
  23465. builder.setContext( previousContext );
  23466. return node;
  23467. }
  23468. generate( builder, output ) {
  23469. const previousContext = builder.getContext();
  23470. builder.setContext( { ...builder.context, ...this.value } );
  23471. const snippet = this.node.build( builder, output );
  23472. builder.setContext( previousContext );
  23473. return snippet;
  23474. }
  23475. }
  23476. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  23477. const label = ( node, name ) => context( node, { label: name } );
  23478. addMethodChaining( 'context', context );
  23479. addMethodChaining( 'label', label );
  23480. class VarNode extends Node {
  23481. static get type() {
  23482. return 'VarNode';
  23483. }
  23484. constructor( node, name = null ) {
  23485. super();
  23486. this.node = node;
  23487. this.name = name;
  23488. this.global = true;
  23489. this.isVarNode = true;
  23490. }
  23491. getHash( builder ) {
  23492. return this.name || super.getHash( builder );
  23493. }
  23494. getNodeType( builder ) {
  23495. return this.node.getNodeType( builder );
  23496. }
  23497. generate( builder ) {
  23498. const { node, name } = this;
  23499. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23500. const propertyName = builder.getPropertyName( nodeVar );
  23501. const snippet = node.build( builder, nodeVar.type );
  23502. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  23503. return propertyName;
  23504. }
  23505. }
  23506. const temp = /*@__PURE__*/ nodeProxy( VarNode );
  23507. addMethodChaining( 'temp', temp ); // @TODO: Will be removed in the future
  23508. addMethodChaining( 'toVar', ( ...params ) => temp( ...params ).append() );
  23509. class VaryingNode extends Node {
  23510. static get type() {
  23511. return 'VaryingNode';
  23512. }
  23513. constructor( node, name = null ) {
  23514. super();
  23515. this.node = node;
  23516. this.name = name;
  23517. this.isVaryingNode = true;
  23518. }
  23519. isGlobal() {
  23520. return true;
  23521. }
  23522. getHash( builder ) {
  23523. return this.name || super.getHash( builder );
  23524. }
  23525. getNodeType( builder ) {
  23526. // VaryingNode is auto type
  23527. return this.node.getNodeType( builder );
  23528. }
  23529. setupVarying( builder ) {
  23530. const properties = builder.getNodeProperties( this );
  23531. let varying = properties.varying;
  23532. if ( varying === undefined ) {
  23533. const name = this.name;
  23534. const type = this.getNodeType( builder );
  23535. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23536. properties.node = this.node;
  23537. }
  23538. // this property can be used to check if the varying can be optimized for a variable
  23539. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23540. return varying;
  23541. }
  23542. setup( builder ) {
  23543. this.setupVarying( builder );
  23544. }
  23545. analyze( builder ) {
  23546. this.setupVarying( builder );
  23547. return this.node.analyze( builder );
  23548. }
  23549. generate( builder ) {
  23550. const properties = builder.getNodeProperties( this );
  23551. const varying = this.setupVarying( builder );
  23552. if ( properties.propertyName === undefined ) {
  23553. const type = this.getNodeType( builder );
  23554. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23555. // force node run in vertex stage
  23556. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23557. properties.propertyName = propertyName;
  23558. }
  23559. return builder.getPropertyName( varying );
  23560. }
  23561. }
  23562. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  23563. addMethodChaining( 'varying', varying );
  23564. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  23565. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  23566. function getColorSpaceName( colorSpace ) {
  23567. let method = null;
  23568. if ( colorSpace === LinearSRGBColorSpace ) {
  23569. method = 'Linear';
  23570. } else if ( colorSpace === SRGBColorSpace ) {
  23571. method = 'sRGB';
  23572. }
  23573. return method;
  23574. }
  23575. function getColorSpaceMethod( source, target ) {
  23576. return getColorSpaceName( source ) + 'To' + getColorSpaceName( target );
  23577. }
  23578. class ColorSpaceNode extends TempNode {
  23579. static get type() {
  23580. return 'ColorSpaceNode';
  23581. }
  23582. constructor( colorNode, source, target ) {
  23583. super( 'vec4' );
  23584. this.colorNode = colorNode;
  23585. this.source = source;
  23586. this.target = target;
  23587. }
  23588. getColorSpace( builder, colorSpace ) {
  23589. if ( colorSpace === WORKING_COLOR_SPACE ) {
  23590. return ColorManagement.workingColorSpace;
  23591. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  23592. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  23593. }
  23594. return colorSpace;
  23595. }
  23596. setup( builder ) {
  23597. const { renderer } = builder;
  23598. const { colorNode } = this;
  23599. const source = this.getColorSpace( builder, this.source );
  23600. const target = this.getColorSpace( builder, this.target );
  23601. if ( source === target ) return colorNode;
  23602. const colorSpace = getColorSpaceMethod( source, target );
  23603. let outputNode = null;
  23604. const colorSpaceFn = renderer.nodes.library.getColorSpaceFunction( colorSpace );
  23605. if ( colorSpaceFn !== null ) {
  23606. outputNode = vec4( colorSpaceFn( colorNode.rgb ), colorNode.a );
  23607. } else {
  23608. console.error( 'ColorSpaceNode: Unsupported Color Space configuration.', colorSpace );
  23609. outputNode = colorNode;
  23610. }
  23611. return outputNode;
  23612. }
  23613. }
  23614. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  23615. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  23616. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  23617. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  23618. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  23619. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  23620. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  23621. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  23622. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  23623. static get type() {
  23624. return 'ReferenceElementNode';
  23625. }
  23626. constructor( referenceNode, indexNode ) {
  23627. super( referenceNode, indexNode );
  23628. this.referenceNode = referenceNode;
  23629. this.isReferenceElementNode = true;
  23630. }
  23631. getNodeType() {
  23632. return this.referenceNode.uniformType;
  23633. }
  23634. generate( builder ) {
  23635. const snippet = super.generate( builder );
  23636. const arrayType = this.referenceNode.getNodeType();
  23637. const elementType = this.getNodeType();
  23638. return builder.format( snippet, arrayType, elementType );
  23639. }
  23640. };
  23641. class ReferenceBaseNode extends Node {
  23642. static get type() {
  23643. return 'ReferenceBaseNode';
  23644. }
  23645. constructor( property, uniformType, object = null, count = null ) {
  23646. super();
  23647. this.property = property;
  23648. this.uniformType = uniformType;
  23649. this.object = object;
  23650. this.count = count;
  23651. this.properties = property.split( '.' );
  23652. this.reference = object;
  23653. this.node = null;
  23654. this.group = null;
  23655. this.updateType = NodeUpdateType.OBJECT;
  23656. }
  23657. setGroup( group ) {
  23658. this.group = group;
  23659. return this;
  23660. }
  23661. element( indexNode ) {
  23662. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  23663. }
  23664. setNodeType( uniformType ) {
  23665. const node = uniform( null, uniformType ).getSelf();
  23666. if ( this.group !== null ) {
  23667. node.setGroup( this.group );
  23668. }
  23669. this.node = node;
  23670. }
  23671. getNodeType( builder ) {
  23672. if ( this.node === null ) {
  23673. this.updateValue();
  23674. }
  23675. return this.node.getNodeType( builder );
  23676. }
  23677. getValueFromReference( object = this.reference ) {
  23678. const { properties } = this;
  23679. let value = object[ properties[ 0 ] ];
  23680. for ( let i = 1; i < properties.length; i ++ ) {
  23681. value = value[ properties[ i ] ];
  23682. }
  23683. return value;
  23684. }
  23685. updateReference( state ) {
  23686. this.reference = this.object !== null ? this.object : state.object;
  23687. return this.reference;
  23688. }
  23689. setup() {
  23690. this.updateValue();
  23691. return this.node;
  23692. }
  23693. update( /*frame*/ ) {
  23694. this.updateValue();
  23695. }
  23696. updateValue() {
  23697. if ( this.node === null ) this.setNodeType( this.uniformType );
  23698. const value = this.getValueFromReference();
  23699. if ( Array.isArray( value ) ) {
  23700. this.node.array = value;
  23701. } else {
  23702. this.node.value = value;
  23703. }
  23704. }
  23705. }
  23706. class RendererReferenceNode extends ReferenceBaseNode {
  23707. static get type() {
  23708. return 'RendererReferenceNode';
  23709. }
  23710. constructor( property, inputType, renderer = null ) {
  23711. super( property, inputType, renderer );
  23712. this.renderer = renderer;
  23713. this.setGroup( renderGroup );
  23714. }
  23715. updateReference( state ) {
  23716. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  23717. return this.reference;
  23718. }
  23719. }
  23720. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  23721. class ToneMappingNode extends TempNode {
  23722. static get type() {
  23723. return 'ToneMappingNode';
  23724. }
  23725. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  23726. super( 'vec3' );
  23727. this.toneMapping = toneMapping;
  23728. this.exposureNode = exposureNode;
  23729. this.colorNode = colorNode;
  23730. }
  23731. getCacheKey() {
  23732. let cacheKey = super.getCacheKey();
  23733. cacheKey = '{toneMapping:' + this.toneMapping + ',nodes:' + cacheKey + '}';
  23734. return cacheKey;
  23735. }
  23736. setup( builder ) {
  23737. const colorNode = this.colorNode || builder.context.color;
  23738. const toneMapping = this.toneMapping;
  23739. if ( toneMapping === NoToneMapping ) return colorNode;
  23740. let outputNode = null;
  23741. const toneMappingFn = builder.renderer.nodes.library.getToneMappingFunction( toneMapping );
  23742. if ( toneMappingFn !== null ) {
  23743. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  23744. } else {
  23745. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  23746. outputNode = colorNode;
  23747. }
  23748. return outputNode;
  23749. }
  23750. }
  23751. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  23752. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  23753. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  23754. class BufferAttributeNode extends InputNode {
  23755. static get type() {
  23756. return 'BufferAttributeNode';
  23757. }
  23758. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  23759. super( value, bufferType );
  23760. this.isBufferNode = true;
  23761. this.bufferType = bufferType;
  23762. this.bufferStride = bufferStride;
  23763. this.bufferOffset = bufferOffset;
  23764. this.usage = StaticDrawUsage;
  23765. this.instanced = false;
  23766. this.attribute = null;
  23767. this.global = true;
  23768. if ( value && value.isBufferAttribute === true ) {
  23769. this.attribute = value;
  23770. this.usage = value.usage;
  23771. this.instanced = value.isInstancedBufferAttribute;
  23772. }
  23773. }
  23774. getHash( builder ) {
  23775. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  23776. let bufferData = builder.globalCache.getData( this.value );
  23777. if ( bufferData === undefined ) {
  23778. bufferData = {
  23779. node: this
  23780. };
  23781. builder.globalCache.setData( this.value, bufferData );
  23782. }
  23783. return bufferData.node.uuid;
  23784. }
  23785. return this.uuid;
  23786. }
  23787. getNodeType( builder ) {
  23788. if ( this.bufferType === null ) {
  23789. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  23790. }
  23791. return this.bufferType;
  23792. }
  23793. setup( builder ) {
  23794. if ( this.attribute !== null ) return;
  23795. const type = this.getNodeType( builder );
  23796. const array = this.value;
  23797. const itemSize = builder.getTypeLength( type );
  23798. const stride = this.bufferStride || itemSize;
  23799. const offset = this.bufferOffset;
  23800. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  23801. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  23802. buffer.setUsage( this.usage );
  23803. this.attribute = bufferAttribute;
  23804. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  23805. }
  23806. generate( builder ) {
  23807. const nodeType = this.getNodeType( builder );
  23808. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  23809. const propertyName = builder.getPropertyName( nodeAttribute );
  23810. let output = null;
  23811. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  23812. this.name = propertyName;
  23813. output = propertyName;
  23814. } else {
  23815. const nodeVarying = varying( this );
  23816. output = nodeVarying.build( builder, nodeType );
  23817. }
  23818. return output;
  23819. }
  23820. getInputType( /*builder*/ ) {
  23821. return 'bufferAttribute';
  23822. }
  23823. setUsage( value ) {
  23824. this.usage = value;
  23825. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  23826. this.attribute.usage = value;
  23827. }
  23828. return this;
  23829. }
  23830. setInstanced( value ) {
  23831. this.instanced = value;
  23832. return this;
  23833. }
  23834. }
  23835. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  23836. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  23837. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  23838. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  23839. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  23840. class ComputeNode extends Node {
  23841. static get type() {
  23842. return 'ComputeNode';
  23843. }
  23844. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  23845. super( 'void' );
  23846. this.isComputeNode = true;
  23847. this.computeNode = computeNode;
  23848. this.count = count;
  23849. this.workgroupSize = workgroupSize;
  23850. this.dispatchCount = 0;
  23851. this.version = 1;
  23852. this.updateBeforeType = NodeUpdateType.OBJECT;
  23853. this.updateDispatchCount();
  23854. }
  23855. dispose() {
  23856. this.dispatchEvent( { type: 'dispose' } );
  23857. }
  23858. set needsUpdate( value ) {
  23859. if ( value === true ) this.version ++;
  23860. }
  23861. updateDispatchCount() {
  23862. const { count, workgroupSize } = this;
  23863. let size = workgroupSize[ 0 ];
  23864. for ( let i = 1; i < workgroupSize.length; i ++ )
  23865. size *= workgroupSize[ i ];
  23866. this.dispatchCount = Math.ceil( count / size );
  23867. }
  23868. onInit() { }
  23869. updateBefore( { renderer } ) {
  23870. renderer.compute( this );
  23871. }
  23872. generate( builder ) {
  23873. const { shaderStage } = builder;
  23874. if ( shaderStage === 'compute' ) {
  23875. const snippet = this.computeNode.build( builder, 'void' );
  23876. if ( snippet !== '' ) {
  23877. builder.addLineFlowCode( snippet );
  23878. }
  23879. }
  23880. }
  23881. }
  23882. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  23883. addMethodChaining( 'compute', compute );
  23884. class CacheNode extends Node {
  23885. static get type() {
  23886. return 'CacheNode';
  23887. }
  23888. constructor( node, parent = true ) {
  23889. super();
  23890. this.node = node;
  23891. this.parent = parent;
  23892. this.isCacheNode = true;
  23893. }
  23894. getNodeType( builder ) {
  23895. return this.node.getNodeType( builder );
  23896. }
  23897. build( builder, ...params ) {
  23898. const previousCache = builder.getCache();
  23899. const cache = builder.getCacheFromNode( this, this.parent );
  23900. builder.setCache( cache );
  23901. const data = this.node.build( builder, ...params );
  23902. builder.setCache( previousCache );
  23903. return data;
  23904. }
  23905. }
  23906. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  23907. addMethodChaining( 'cache', cache );
  23908. class BypassNode extends Node {
  23909. static get type() {
  23910. return 'BypassNode';
  23911. }
  23912. constructor( returnNode, callNode ) {
  23913. super();
  23914. this.isBypassNode = true;
  23915. this.outputNode = returnNode;
  23916. this.callNode = callNode;
  23917. }
  23918. getNodeType( builder ) {
  23919. return this.outputNode.getNodeType( builder );
  23920. }
  23921. generate( builder ) {
  23922. const snippet = this.callNode.build( builder, 'void' );
  23923. if ( snippet !== '' ) {
  23924. builder.addLineFlowCode( snippet );
  23925. }
  23926. return this.outputNode.build( builder );
  23927. }
  23928. }
  23929. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  23930. addMethodChaining( 'bypass', bypass );
  23931. class RemapNode extends Node {
  23932. static get type() {
  23933. return 'RemapNode';
  23934. }
  23935. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  23936. super();
  23937. this.node = node;
  23938. this.inLowNode = inLowNode;
  23939. this.inHighNode = inHighNode;
  23940. this.outLowNode = outLowNode;
  23941. this.outHighNode = outHighNode;
  23942. this.doClamp = true;
  23943. }
  23944. setup() {
  23945. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  23946. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  23947. if ( doClamp === true ) t = t.clamp();
  23948. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  23949. }
  23950. }
  23951. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  23952. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  23953. addMethodChaining( 'remap', remap );
  23954. addMethodChaining( 'remapClamp', remapClamp );
  23955. class ExpressionNode extends Node {
  23956. static get type() {
  23957. return 'ExpressionNode';
  23958. }
  23959. constructor( snippet = '', nodeType = 'void' ) {
  23960. super( nodeType );
  23961. this.snippet = snippet;
  23962. }
  23963. generate( builder, output ) {
  23964. const type = this.getNodeType( builder );
  23965. const snippet = this.snippet;
  23966. if ( type === 'void' ) {
  23967. builder.addLineFlowCode( snippet );
  23968. } else {
  23969. return builder.format( `( ${ snippet } )`, type, output );
  23970. }
  23971. }
  23972. }
  23973. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  23974. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  23975. const Return = () => expression( 'return' ).append();
  23976. addMethodChaining( 'discard', Discard );
  23977. class RenderOutputNode extends TempNode {
  23978. static get type() {
  23979. return 'RenderOutputNode';
  23980. }
  23981. constructor( colorNode, toneMapping, outputColorSpace ) {
  23982. super( 'vec4' );
  23983. this.colorNode = colorNode;
  23984. this.toneMapping = toneMapping;
  23985. this.outputColorSpace = outputColorSpace;
  23986. this.isRenderOutput = true;
  23987. }
  23988. setup( { context } ) {
  23989. let outputNode = this.colorNode || context.color;
  23990. // tone mapping
  23991. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  23992. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  23993. if ( toneMapping !== NoToneMapping ) {
  23994. outputNode = outputNode.toneMapping( toneMapping );
  23995. }
  23996. // working to output color space
  23997. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  23998. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  23999. }
  24000. return outputNode;
  24001. }
  24002. }
  24003. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  24004. addMethodChaining( 'renderOutput', renderOutput );
  24005. // Non-PURE exports list, side-effects are required here.
  24006. // TSL Base Syntax
  24007. function addNodeElement( name/*, nodeElement*/ ) {
  24008. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  24009. }
  24010. class AttributeNode extends Node {
  24011. static get type() {
  24012. return 'AttributeNode';
  24013. }
  24014. constructor( attributeName, nodeType = null ) {
  24015. super( nodeType );
  24016. this.global = true;
  24017. this._attributeName = attributeName;
  24018. }
  24019. getHash( builder ) {
  24020. return this.getAttributeName( builder );
  24021. }
  24022. getNodeType( builder ) {
  24023. let nodeType = this.nodeType;
  24024. if ( nodeType === null ) {
  24025. const attributeName = this.getAttributeName( builder );
  24026. if ( builder.hasGeometryAttribute( attributeName ) ) {
  24027. const attribute = builder.geometry.getAttribute( attributeName );
  24028. nodeType = builder.getTypeFromAttribute( attribute );
  24029. } else {
  24030. nodeType = 'float';
  24031. }
  24032. }
  24033. return nodeType;
  24034. }
  24035. setAttributeName( attributeName ) {
  24036. this._attributeName = attributeName;
  24037. return this;
  24038. }
  24039. getAttributeName( /*builder*/ ) {
  24040. return this._attributeName;
  24041. }
  24042. generate( builder ) {
  24043. const attributeName = this.getAttributeName( builder );
  24044. const nodeType = this.getNodeType( builder );
  24045. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  24046. if ( geometryAttribute === true ) {
  24047. const attribute = builder.geometry.getAttribute( attributeName );
  24048. const attributeType = builder.getTypeFromAttribute( attribute );
  24049. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  24050. if ( builder.shaderStage === 'vertex' ) {
  24051. return builder.format( nodeAttribute.name, attributeType, nodeType );
  24052. } else {
  24053. const nodeVarying = varying( this );
  24054. return nodeVarying.build( builder, nodeType );
  24055. }
  24056. } else {
  24057. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  24058. return builder.generateConst( nodeType );
  24059. }
  24060. }
  24061. serialize( data ) {
  24062. super.serialize( data );
  24063. data.global = this.global;
  24064. data._attributeName = this._attributeName;
  24065. }
  24066. deserialize( data ) {
  24067. super.deserialize( data );
  24068. this.global = data.global;
  24069. this._attributeName = data._attributeName;
  24070. }
  24071. }
  24072. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  24073. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  24074. class TextureSizeNode extends Node {
  24075. static get type() {
  24076. return 'TextureSizeNode';
  24077. }
  24078. constructor( textureNode, levelNode = null ) {
  24079. super( 'uvec2' );
  24080. this.isTextureSizeNode = true;
  24081. this.textureNode = textureNode;
  24082. this.levelNode = levelNode;
  24083. }
  24084. generate( builder, output ) {
  24085. const textureProperty = this.textureNode.build( builder, 'property' );
  24086. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  24087. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  24088. }
  24089. }
  24090. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  24091. class MaxMipLevelNode extends UniformNode {
  24092. static get type() {
  24093. return 'MaxMipLevelNode';
  24094. }
  24095. constructor( textureNode ) {
  24096. super( 0 );
  24097. this._textureNode = textureNode;
  24098. this.updateType = NodeUpdateType.FRAME;
  24099. }
  24100. get textureNode() {
  24101. return this._textureNode;
  24102. }
  24103. get texture() {
  24104. return this._textureNode.value;
  24105. }
  24106. update() {
  24107. const texture = this.texture;
  24108. const images = texture.images;
  24109. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24110. if ( image && image.width !== undefined ) {
  24111. const { width, height } = image;
  24112. this.value = Math.log2( Math.max( width, height ) );
  24113. }
  24114. }
  24115. }
  24116. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  24117. class TextureNode extends UniformNode {
  24118. static get type() {
  24119. return 'TextureNode';
  24120. }
  24121. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24122. super( value );
  24123. this.isTextureNode = true;
  24124. this.uvNode = uvNode;
  24125. this.levelNode = levelNode;
  24126. this.biasNode = biasNode;
  24127. this.compareNode = null;
  24128. this.depthNode = null;
  24129. this.gradNode = null;
  24130. this.sampler = true;
  24131. this.updateMatrix = false;
  24132. this.updateType = NodeUpdateType.NONE;
  24133. this.referenceNode = null;
  24134. this._value = value;
  24135. this._matrixUniform = null;
  24136. this.setUpdateMatrix( uvNode === null );
  24137. }
  24138. set value( value ) {
  24139. if ( this.referenceNode ) {
  24140. this.referenceNode.value = value;
  24141. } else {
  24142. this._value = value;
  24143. }
  24144. }
  24145. get value() {
  24146. return this.referenceNode ? this.referenceNode.value : this._value;
  24147. }
  24148. getUniformHash( /*builder*/ ) {
  24149. return this.value.uuid;
  24150. }
  24151. getNodeType( /*builder*/ ) {
  24152. if ( this.value.isDepthTexture === true ) return 'float';
  24153. if ( this.value.type === UnsignedIntType ) {
  24154. return 'uvec4';
  24155. } else if ( this.value.type === IntType ) {
  24156. return 'ivec4';
  24157. }
  24158. return 'vec4';
  24159. }
  24160. getInputType( /*builder*/ ) {
  24161. return 'texture';
  24162. }
  24163. getDefaultUV() {
  24164. return uv( this.value.channel );
  24165. }
  24166. updateReference( /*state*/ ) {
  24167. return this.value;
  24168. }
  24169. getTransformedUV( uvNode ) {
  24170. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  24171. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  24172. }
  24173. setUpdateMatrix( value ) {
  24174. this.updateMatrix = value;
  24175. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24176. return this;
  24177. }
  24178. setupUV( builder, uvNode ) {
  24179. const texture = this.value;
  24180. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24181. if ( this.sampler ) {
  24182. uvNode = uvNode.flipY();
  24183. } else {
  24184. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24185. }
  24186. }
  24187. return uvNode;
  24188. }
  24189. setup( builder ) {
  24190. const properties = builder.getNodeProperties( this );
  24191. properties.referenceNode = this.referenceNode;
  24192. //
  24193. let uvNode = this.uvNode;
  24194. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24195. uvNode = builder.context.getUV( this );
  24196. }
  24197. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24198. if ( this.updateMatrix === true ) {
  24199. uvNode = this.getTransformedUV( uvNode );
  24200. }
  24201. uvNode = this.setupUV( builder, uvNode );
  24202. //
  24203. let levelNode = this.levelNode;
  24204. if ( levelNode === null && builder.context.getTextureLevel ) {
  24205. levelNode = builder.context.getTextureLevel( this );
  24206. }
  24207. //
  24208. properties.uvNode = uvNode;
  24209. properties.levelNode = levelNode;
  24210. properties.biasNode = this.biasNode;
  24211. properties.compareNode = this.compareNode;
  24212. properties.gradNode = this.gradNode;
  24213. properties.depthNode = this.depthNode;
  24214. }
  24215. generateUV( builder, uvNode ) {
  24216. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24217. }
  24218. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24219. const texture = this.value;
  24220. let snippet;
  24221. if ( levelSnippet ) {
  24222. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24223. } else if ( biasSnippet ) {
  24224. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  24225. } else if ( gradSnippet ) {
  24226. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24227. } else if ( compareSnippet ) {
  24228. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24229. } else if ( this.sampler === false ) {
  24230. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24231. } else {
  24232. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24233. }
  24234. return snippet;
  24235. }
  24236. generate( builder, output ) {
  24237. const properties = builder.getNodeProperties( this );
  24238. const texture = this.value;
  24239. if ( ! texture || texture.isTexture !== true ) {
  24240. throw new Error( 'TextureNode: Need a three.js texture.' );
  24241. }
  24242. const textureProperty = super.generate( builder, 'property' );
  24243. if ( output === 'sampler' ) {
  24244. return textureProperty + '_sampler';
  24245. } else if ( builder.isReference( output ) ) {
  24246. return textureProperty;
  24247. } else {
  24248. const nodeData = builder.getDataFromNode( this );
  24249. let propertyName = nodeData.propertyName;
  24250. if ( propertyName === undefined ) {
  24251. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24252. const uvSnippet = this.generateUV( builder, uvNode );
  24253. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24254. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24255. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24256. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24257. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24258. const nodeVar = builder.getVarFromNode( this );
  24259. propertyName = builder.getPropertyName( nodeVar );
  24260. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24261. builder.addLineFlowCode( `${propertyName} = ${snippet}` );
  24262. nodeData.snippet = snippet;
  24263. nodeData.propertyName = propertyName;
  24264. }
  24265. let snippet = propertyName;
  24266. const nodeType = this.getNodeType( builder );
  24267. if ( builder.needsToWorkingColorSpace( texture ) ) {
  24268. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24269. }
  24270. return builder.format( snippet, nodeType, output );
  24271. }
  24272. }
  24273. setSampler( value ) {
  24274. this.sampler = value;
  24275. return this;
  24276. }
  24277. getSampler() {
  24278. return this.sampler;
  24279. }
  24280. // @TODO: Move to TSL
  24281. uv( uvNode ) {
  24282. const textureNode = this.clone();
  24283. textureNode.uvNode = nodeObject( uvNode );
  24284. textureNode.referenceNode = this.getSelf();
  24285. return nodeObject( textureNode );
  24286. }
  24287. blur( amountNode ) {
  24288. const textureNode = this.clone();
  24289. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24290. textureNode.referenceNode = this.getSelf();
  24291. return nodeObject( textureNode );
  24292. }
  24293. level( levelNode ) {
  24294. const textureNode = this.clone();
  24295. textureNode.levelNode = nodeObject( levelNode );
  24296. textureNode.referenceNode = this.getSelf();
  24297. return nodeObject( textureNode );
  24298. }
  24299. size( levelNode ) {
  24300. return textureSize( this, levelNode );
  24301. }
  24302. bias( biasNode ) {
  24303. const textureNode = this.clone();
  24304. textureNode.biasNode = nodeObject( biasNode );
  24305. textureNode.referenceNode = this.getSelf();
  24306. return nodeObject( textureNode );
  24307. }
  24308. compare( compareNode ) {
  24309. const textureNode = this.clone();
  24310. textureNode.compareNode = nodeObject( compareNode );
  24311. textureNode.referenceNode = this.getSelf();
  24312. return nodeObject( textureNode );
  24313. }
  24314. grad( gradNodeX, gradNodeY ) {
  24315. const textureNode = this.clone();
  24316. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24317. textureNode.referenceNode = this.getSelf();
  24318. return nodeObject( textureNode );
  24319. }
  24320. depth( depthNode ) {
  24321. const textureNode = this.clone();
  24322. textureNode.depthNode = nodeObject( depthNode );
  24323. textureNode.referenceNode = this.getSelf();
  24324. return nodeObject( textureNode );
  24325. }
  24326. // --
  24327. serialize( data ) {
  24328. super.serialize( data );
  24329. data.value = this.value.toJSON( data.meta ).uuid;
  24330. data.sampler = this.sampler;
  24331. data.updateMatrix = this.updateMatrix;
  24332. data.updateType = this.updateType;
  24333. }
  24334. deserialize( data ) {
  24335. super.deserialize( data );
  24336. this.value = data.meta.textures[ data.value ];
  24337. this.sampler = data.sampler;
  24338. this.updateMatrix = data.updateMatrix;
  24339. this.updateType = data.updateType;
  24340. }
  24341. update() {
  24342. const texture = this.value;
  24343. const matrixUniform = this._matrixUniform;
  24344. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  24345. if ( texture.matrixAutoUpdate === true ) {
  24346. texture.updateMatrix();
  24347. }
  24348. }
  24349. clone() {
  24350. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24351. newNode.sampler = this.sampler;
  24352. return newNode;
  24353. }
  24354. }
  24355. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  24356. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24357. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24358. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24359. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24360. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24361. const cameraLogDepth = /*@__PURE__*/ uniform( 'float' ).label( 'cameraLogDepth' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  24362. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24363. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24364. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24365. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24366. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24367. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24368. class Object3DNode extends Node {
  24369. static get type() {
  24370. return 'Object3DNode';
  24371. }
  24372. constructor( scope, object3d = null ) {
  24373. super();
  24374. this.scope = scope;
  24375. this.object3d = object3d;
  24376. this.updateType = NodeUpdateType.OBJECT;
  24377. this._uniformNode = new UniformNode( null );
  24378. }
  24379. getNodeType() {
  24380. const scope = this.scope;
  24381. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24382. return 'mat4';
  24383. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24384. return 'vec3';
  24385. }
  24386. }
  24387. update( frame ) {
  24388. const object = this.object3d;
  24389. const uniformNode = this._uniformNode;
  24390. const scope = this.scope;
  24391. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24392. uniformNode.value = object.matrixWorld;
  24393. } else if ( scope === Object3DNode.POSITION ) {
  24394. uniformNode.value = uniformNode.value || new Vector3();
  24395. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24396. } else if ( scope === Object3DNode.SCALE ) {
  24397. uniformNode.value = uniformNode.value || new Vector3();
  24398. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  24399. } else if ( scope === Object3DNode.DIRECTION ) {
  24400. uniformNode.value = uniformNode.value || new Vector3();
  24401. object.getWorldDirection( uniformNode.value );
  24402. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  24403. const camera = frame.camera;
  24404. uniformNode.value = uniformNode.value || new Vector3();
  24405. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24406. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  24407. }
  24408. }
  24409. generate( builder ) {
  24410. const scope = this.scope;
  24411. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24412. this._uniformNode.nodeType = 'mat4';
  24413. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24414. this._uniformNode.nodeType = 'vec3';
  24415. }
  24416. return this._uniformNode.build( builder );
  24417. }
  24418. serialize( data ) {
  24419. super.serialize( data );
  24420. data.scope = this.scope;
  24421. }
  24422. deserialize( data ) {
  24423. super.deserialize( data );
  24424. this.scope = data.scope;
  24425. }
  24426. }
  24427. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  24428. Object3DNode.POSITION = 'position';
  24429. Object3DNode.SCALE = 'scale';
  24430. Object3DNode.VIEW_POSITION = 'viewPosition';
  24431. Object3DNode.DIRECTION = 'direction';
  24432. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  24433. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  24434. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  24435. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  24436. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  24437. class ModelNode extends Object3DNode {
  24438. static get type() {
  24439. return 'ModelNode';
  24440. }
  24441. constructor( scope ) {
  24442. super( scope );
  24443. }
  24444. update( frame ) {
  24445. this.object3d = frame.object;
  24446. super.update( frame );
  24447. }
  24448. }
  24449. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  24450. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  24451. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  24452. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  24453. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  24454. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  24455. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  24456. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  24457. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24458. builder.context.isHighPrecisionModelViewMatrix = true;
  24459. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  24460. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24461. } );
  24462. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  24463. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24464. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  24465. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  24466. if ( isHighPrecisionModelViewMatrix !== true ) {
  24467. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24468. }
  24469. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  24470. } );
  24471. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  24472. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  24473. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  24474. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  24475. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  24476. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  24477. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  24478. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  24479. class FrontFacingNode extends Node {
  24480. static get type() {
  24481. return 'FrontFacingNode';
  24482. }
  24483. constructor() {
  24484. super( 'bool' );
  24485. this.isFrontFacingNode = true;
  24486. }
  24487. generate( builder ) {
  24488. const { renderer, material } = builder;
  24489. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  24490. if ( material.side === BackSide ) {
  24491. return 'false';
  24492. }
  24493. }
  24494. return builder.getFrontFacing();
  24495. }
  24496. }
  24497. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  24498. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  24499. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  24500. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  24501. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  24502. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  24503. return vec3( 0, 1, 0 );
  24504. }
  24505. return normalGeometry;
  24506. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  24507. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  24508. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24509. let node;
  24510. if ( builder.material.flatShading === true ) {
  24511. node = normalFlat;
  24512. } else {
  24513. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  24514. }
  24515. return node;
  24516. }, 'vec3' ).once() )().toVar( 'normalView' );
  24517. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  24518. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24519. return builder.context.setupNormal();
  24520. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  24521. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  24522. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24523. return builder.context.setupClearcoatNormal();
  24524. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  24525. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  24526. const m = mat3( matrix );
  24527. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  24528. return m.mul( transformedNormal ).xyz;
  24529. } );
  24530. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  24531. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  24532. if ( modelNormalViewMatrix !== null ) {
  24533. return modelNormalViewMatrix.transformDirection( normal );
  24534. }
  24535. //
  24536. const transformedNormal = modelNormalMatrix.mul( normal );
  24537. return cameraViewMatrix.transformDirection( transformedNormal );
  24538. } );
  24539. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  24540. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  24541. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  24542. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24543. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24544. class CubeTextureNode extends TextureNode {
  24545. static get type() {
  24546. return 'CubeTextureNode';
  24547. }
  24548. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24549. super( value, uvNode, levelNode, biasNode );
  24550. this.isCubeTextureNode = true;
  24551. }
  24552. getInputType( /*builder*/ ) {
  24553. return 'cubeTexture';
  24554. }
  24555. getDefaultUV() {
  24556. const texture = this.value;
  24557. if ( texture.mapping === CubeReflectionMapping ) {
  24558. return reflectVector;
  24559. } else if ( texture.mapping === CubeRefractionMapping ) {
  24560. return refractVector;
  24561. } else {
  24562. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  24563. return vec3( 0, 0, 0 );
  24564. }
  24565. }
  24566. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  24567. setupUV( builder, uvNode ) {
  24568. const texture = this.value;
  24569. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  24570. return vec3( uvNode.x.negate(), uvNode.yz );
  24571. } else {
  24572. return uvNode;
  24573. }
  24574. }
  24575. generateUV( builder, cubeUV ) {
  24576. return cubeUV.build( builder, 'vec3' );
  24577. }
  24578. }
  24579. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  24580. class BufferNode extends UniformNode {
  24581. static get type() {
  24582. return 'BufferNode';
  24583. }
  24584. constructor( value, bufferType, bufferCount = 0 ) {
  24585. super( value, bufferType );
  24586. this.isBufferNode = true;
  24587. this.bufferType = bufferType;
  24588. this.bufferCount = bufferCount;
  24589. }
  24590. getElementType( builder ) {
  24591. return this.getNodeType( builder );
  24592. }
  24593. getInputType( /*builder*/ ) {
  24594. return 'buffer';
  24595. }
  24596. }
  24597. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24598. class UniformArrayElementNode extends ArrayElementNode {
  24599. static get type() {
  24600. return 'UniformArrayElementNode';
  24601. }
  24602. constructor( arrayBuffer, indexNode ) {
  24603. super( arrayBuffer, indexNode );
  24604. this.isArrayBufferElementNode = true;
  24605. }
  24606. generate( builder ) {
  24607. const snippet = super.generate( builder );
  24608. const type = this.getNodeType();
  24609. return builder.format( snippet, 'vec4', type );
  24610. }
  24611. }
  24612. class UniformArrayNode extends BufferNode {
  24613. static get type() {
  24614. return 'UniformArrayNode';
  24615. }
  24616. constructor( value, elementType = null ) {
  24617. super( null, 'vec4' );
  24618. this.array = value;
  24619. this.elementType = elementType;
  24620. this._elementType = null;
  24621. this._elementLength = 0;
  24622. this.updateType = NodeUpdateType.RENDER;
  24623. this.isArrayBufferNode = true;
  24624. }
  24625. getElementType() {
  24626. return this.elementType || this._elementType;
  24627. }
  24628. getElementLength() {
  24629. return this._elementLength;
  24630. }
  24631. update( /*frame*/ ) {
  24632. const { array, value } = this;
  24633. const elementLength = this.getElementLength();
  24634. const elementType = this.getElementType();
  24635. if ( elementLength === 1 ) {
  24636. for ( let i = 0; i < array.length; i ++ ) {
  24637. const index = i * 4;
  24638. value[ index ] = array[ i ];
  24639. }
  24640. } else if ( elementType === 'color' ) {
  24641. for ( let i = 0; i < array.length; i ++ ) {
  24642. const index = i * 4;
  24643. const vector = array[ i ];
  24644. value[ index ] = vector.r;
  24645. value[ index + 1 ] = vector.g;
  24646. value[ index + 2 ] = vector.b || 0;
  24647. //value[ index + 3 ] = vector.a || 0;
  24648. }
  24649. } else {
  24650. for ( let i = 0; i < array.length; i ++ ) {
  24651. const index = i * 4;
  24652. const vector = array[ i ];
  24653. value[ index ] = vector.x;
  24654. value[ index + 1 ] = vector.y;
  24655. value[ index + 2 ] = vector.z || 0;
  24656. value[ index + 3 ] = vector.w || 0;
  24657. }
  24658. }
  24659. }
  24660. setup( builder ) {
  24661. const length = this.array.length;
  24662. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24663. this._elementLength = builder.getTypeLength( this._elementType );
  24664. let arrayType = Float32Array;
  24665. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  24666. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  24667. this.value = new arrayType( length * 4 );
  24668. this.bufferCount = length;
  24669. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  24670. return super.setup( builder );
  24671. }
  24672. element( indexNode ) {
  24673. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  24674. }
  24675. }
  24676. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  24677. //
  24678. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  24679. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  24680. return nodeObject( new UniformArrayNode( values, nodeType ) );
  24681. };
  24682. class ReferenceElementNode extends ArrayElementNode {
  24683. static get type() {
  24684. return 'ReferenceElementNode';
  24685. }
  24686. constructor( referenceNode, indexNode ) {
  24687. super( referenceNode, indexNode );
  24688. this.referenceNode = referenceNode;
  24689. this.isReferenceElementNode = true;
  24690. }
  24691. getNodeType() {
  24692. return this.referenceNode.uniformType;
  24693. }
  24694. generate( builder ) {
  24695. const snippet = super.generate( builder );
  24696. const arrayType = this.referenceNode.getNodeType();
  24697. const elementType = this.getNodeType();
  24698. return builder.format( snippet, arrayType, elementType );
  24699. }
  24700. }
  24701. // TODO: Extends this from ReferenceBaseNode
  24702. class ReferenceNode extends Node {
  24703. static get type() {
  24704. return 'ReferenceNode';
  24705. }
  24706. constructor( property, uniformType, object = null, count = null ) {
  24707. super();
  24708. this.property = property;
  24709. this.uniformType = uniformType;
  24710. this.object = object;
  24711. this.count = count;
  24712. this.properties = property.split( '.' );
  24713. this.reference = object;
  24714. this.node = null;
  24715. this.group = null;
  24716. this.name = null;
  24717. this.updateType = NodeUpdateType.OBJECT;
  24718. }
  24719. element( indexNode ) {
  24720. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  24721. }
  24722. setGroup( group ) {
  24723. this.group = group;
  24724. return this;
  24725. }
  24726. label( name ) {
  24727. this.name = name;
  24728. return this;
  24729. }
  24730. setNodeType( uniformType ) {
  24731. let node = null;
  24732. if ( this.count !== null ) {
  24733. node = buffer( null, uniformType, this.count );
  24734. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  24735. node = uniformArray( null, uniformType );
  24736. } else if ( uniformType === 'texture' ) {
  24737. node = texture( null );
  24738. } else if ( uniformType === 'cubeTexture' ) {
  24739. node = cubeTexture( null );
  24740. } else {
  24741. node = uniform( null, uniformType );
  24742. }
  24743. if ( this.group !== null ) {
  24744. node.setGroup( this.group );
  24745. }
  24746. if ( this.name !== null ) node.label( this.name );
  24747. this.node = node.getSelf();
  24748. }
  24749. getNodeType( builder ) {
  24750. if ( this.node === null ) {
  24751. this.updateValue();
  24752. }
  24753. return this.node.getNodeType( builder );
  24754. }
  24755. getValueFromReference( object = this.reference ) {
  24756. const { properties } = this;
  24757. let value = object[ properties[ 0 ] ];
  24758. for ( let i = 1; i < properties.length; i ++ ) {
  24759. value = value[ properties[ i ] ];
  24760. }
  24761. return value;
  24762. }
  24763. updateReference( state ) {
  24764. this.reference = this.object !== null ? this.object : state.object;
  24765. return this.reference;
  24766. }
  24767. setup() {
  24768. this.updateValue();
  24769. return this.node;
  24770. }
  24771. update( /*frame*/ ) {
  24772. this.updateValue();
  24773. }
  24774. updateValue() {
  24775. if ( this.node === null ) this.setNodeType( this.uniformType );
  24776. const value = this.getValueFromReference();
  24777. if ( Array.isArray( value ) ) {
  24778. this.node.array = value;
  24779. } else {
  24780. this.node.value = value;
  24781. }
  24782. }
  24783. }
  24784. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  24785. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  24786. class MaterialReferenceNode extends ReferenceNode {
  24787. static get type() {
  24788. return 'MaterialReferenceNode';
  24789. }
  24790. constructor( property, inputType, material = null ) {
  24791. super( property, inputType, material );
  24792. this.material = material;
  24793. //this.updateType = NodeUpdateType.RENDER;
  24794. this.isMaterialReferenceNode = true;
  24795. }
  24796. /*setNodeType( node ) {
  24797. super.setNodeType( node );
  24798. this.node.groupNode = renderGroup;
  24799. }*/
  24800. updateReference( state ) {
  24801. this.reference = this.material !== null ? this.material : state.material;
  24802. return this.reference;
  24803. }
  24804. }
  24805. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  24806. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  24807. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  24808. builder.geometry.computeTangents();
  24809. }
  24810. return attribute( 'tangent', 'vec4' );
  24811. } )();
  24812. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  24813. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  24814. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  24815. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  24816. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  24817. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  24818. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  24819. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  24820. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  24821. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  24822. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  24823. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  24824. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  24825. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  24826. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  24827. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  24828. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  24829. let bentNormal = anisotropyB.cross( positionViewDirection );
  24830. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  24831. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  24832. return bentNormal;
  24833. } )();
  24834. // Normal Mapping Without Precomputed Tangents
  24835. // http://www.thetenthplanet.de/archives/1180
  24836. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  24837. const { eye_pos, surf_norm, mapN, uv } = inputs;
  24838. const q0 = eye_pos.dFdx();
  24839. const q1 = eye_pos.dFdy();
  24840. const st0 = uv.dFdx();
  24841. const st1 = uv.dFdy();
  24842. const N = surf_norm; // normalized
  24843. const q1perp = q1.cross( N );
  24844. const q0perp = N.cross( q0 );
  24845. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  24846. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  24847. const det = T.dot( T ).max( B.dot( B ) );
  24848. const scale = faceDirection.mul( det.inverseSqrt() );
  24849. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  24850. } );
  24851. class NormalMapNode extends TempNode {
  24852. static get type() {
  24853. return 'NormalMapNode';
  24854. }
  24855. constructor( node, scaleNode = null ) {
  24856. super( 'vec3' );
  24857. this.node = node;
  24858. this.scaleNode = scaleNode;
  24859. this.normalMapType = TangentSpaceNormalMap;
  24860. }
  24861. setup( builder ) {
  24862. const { normalMapType, scaleNode } = this;
  24863. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  24864. if ( scaleNode !== null ) {
  24865. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  24866. }
  24867. let outputNode = null;
  24868. if ( normalMapType === ObjectSpaceNormalMap ) {
  24869. outputNode = transformNormalToView( normalMap );
  24870. } else if ( normalMapType === TangentSpaceNormalMap ) {
  24871. const tangent = builder.hasGeometryAttribute( 'tangent' );
  24872. if ( tangent === true ) {
  24873. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  24874. } else {
  24875. outputNode = perturbNormal2Arb( {
  24876. eye_pos: positionView,
  24877. surf_norm: normalView,
  24878. mapN: normalMap,
  24879. uv: uv()
  24880. } );
  24881. }
  24882. }
  24883. return outputNode;
  24884. }
  24885. }
  24886. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  24887. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  24888. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  24889. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  24890. // It's used to preserve the same TextureNode instance
  24891. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  24892. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  24893. return vec2(
  24894. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  24895. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  24896. ).mul( bumpScale );
  24897. } );
  24898. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  24899. const perturbNormalArb = Fn( ( inputs ) => {
  24900. const { surf_pos, surf_norm, dHdxy } = inputs;
  24901. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  24902. const vSigmaX = surf_pos.dFdx().normalize();
  24903. const vSigmaY = surf_pos.dFdy().normalize();
  24904. const vN = surf_norm; // normalized
  24905. const R1 = vSigmaY.cross( vN );
  24906. const R2 = vN.cross( vSigmaX );
  24907. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  24908. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  24909. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  24910. } );
  24911. class BumpMapNode extends TempNode {
  24912. static get type() {
  24913. return 'BumpMapNode';
  24914. }
  24915. constructor( textureNode, scaleNode = null ) {
  24916. super( 'vec3' );
  24917. this.textureNode = textureNode;
  24918. this.scaleNode = scaleNode;
  24919. }
  24920. setup() {
  24921. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  24922. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  24923. return perturbNormalArb( {
  24924. surf_pos: positionView,
  24925. surf_norm: normalView,
  24926. dHdxy
  24927. } );
  24928. }
  24929. }
  24930. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  24931. const _propertyCache = new Map();
  24932. class MaterialNode extends Node {
  24933. static get type() {
  24934. return 'MaterialNode';
  24935. }
  24936. constructor( scope ) {
  24937. super();
  24938. this.scope = scope;
  24939. }
  24940. getCache( property, type ) {
  24941. let node = _propertyCache.get( property );
  24942. if ( node === undefined ) {
  24943. node = materialReference( property, type );
  24944. _propertyCache.set( property, node );
  24945. }
  24946. return node;
  24947. }
  24948. getFloat( property ) {
  24949. return this.getCache( property, 'float' );
  24950. }
  24951. getColor( property ) {
  24952. return this.getCache( property, 'color' );
  24953. }
  24954. getTexture( property ) {
  24955. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  24956. }
  24957. setup( builder ) {
  24958. const material = builder.context.material;
  24959. const scope = this.scope;
  24960. let node = null;
  24961. if ( scope === MaterialNode.COLOR ) {
  24962. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  24963. if ( material.map && material.map.isTexture === true ) {
  24964. node = colorNode.mul( this.getTexture( 'map' ) );
  24965. } else {
  24966. node = colorNode;
  24967. }
  24968. } else if ( scope === MaterialNode.OPACITY ) {
  24969. const opacityNode = this.getFloat( scope );
  24970. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  24971. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  24972. } else {
  24973. node = opacityNode;
  24974. }
  24975. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  24976. if ( material.specularMap && material.specularMap.isTexture === true ) {
  24977. node = this.getTexture( 'specular' ).r;
  24978. } else {
  24979. node = float( 1 );
  24980. }
  24981. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  24982. const specularIntensity = this.getFloat( scope );
  24983. if ( material.specularMap ) {
  24984. node = specularIntensity.mul( this.getTexture( scope ).a );
  24985. } else {
  24986. node = specularIntensity;
  24987. }
  24988. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  24989. const specularColorNode = this.getColor( scope );
  24990. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  24991. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  24992. } else {
  24993. node = specularColorNode;
  24994. }
  24995. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  24996. const roughnessNode = this.getFloat( scope );
  24997. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  24998. node = roughnessNode.mul( this.getTexture( scope ).g );
  24999. } else {
  25000. node = roughnessNode;
  25001. }
  25002. } else if ( scope === MaterialNode.METALNESS ) {
  25003. const metalnessNode = this.getFloat( scope );
  25004. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25005. node = metalnessNode.mul( this.getTexture( scope ).b );
  25006. } else {
  25007. node = metalnessNode;
  25008. }
  25009. } else if ( scope === MaterialNode.EMISSIVE ) {
  25010. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  25011. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  25012. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25013. node = emissiveNode.mul( this.getTexture( scope ) );
  25014. } else {
  25015. node = emissiveNode;
  25016. }
  25017. } else if ( scope === MaterialNode.NORMAL ) {
  25018. if ( material.normalMap ) {
  25019. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  25020. node.normalMapType = material.normalMapType;
  25021. } else if ( material.bumpMap ) {
  25022. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  25023. } else {
  25024. node = normalView;
  25025. }
  25026. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25027. const clearcoatNode = this.getFloat( scope );
  25028. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25029. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25030. } else {
  25031. node = clearcoatNode;
  25032. }
  25033. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25034. const clearcoatRoughnessNode = this.getFloat( scope );
  25035. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25036. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25037. } else {
  25038. node = clearcoatRoughnessNode;
  25039. }
  25040. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25041. if ( material.clearcoatNormalMap ) {
  25042. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  25043. } else {
  25044. node = normalView;
  25045. }
  25046. } else if ( scope === MaterialNode.SHEEN ) {
  25047. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25048. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25049. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25050. } else {
  25051. node = sheenNode;
  25052. }
  25053. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25054. const sheenRoughnessNode = this.getFloat( scope );
  25055. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25056. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25057. } else {
  25058. node = sheenRoughnessNode;
  25059. }
  25060. node = node.clamp( 0.07, 1.0 );
  25061. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25062. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25063. const anisotropyPolar = this.getTexture( scope );
  25064. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25065. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25066. } else {
  25067. node = materialAnisotropyVector;
  25068. }
  25069. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25070. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25071. if ( material.iridescenceThicknessMap ) {
  25072. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25073. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25074. } else {
  25075. node = iridescenceThicknessMaximum;
  25076. }
  25077. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25078. const transmissionNode = this.getFloat( scope );
  25079. if ( material.transmissionMap ) {
  25080. node = transmissionNode.mul( this.getTexture( scope ).r );
  25081. } else {
  25082. node = transmissionNode;
  25083. }
  25084. } else if ( scope === MaterialNode.THICKNESS ) {
  25085. const thicknessNode = this.getFloat( scope );
  25086. if ( material.thicknessMap ) {
  25087. node = thicknessNode.mul( this.getTexture( scope ).g );
  25088. } else {
  25089. node = thicknessNode;
  25090. }
  25091. } else if ( scope === MaterialNode.IOR ) {
  25092. node = this.getFloat( scope );
  25093. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  25094. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  25095. } else if ( scope === MaterialNode.AO_MAP ) {
  25096. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  25097. } else {
  25098. const outputType = this.getNodeType( builder );
  25099. node = this.getCache( scope, outputType );
  25100. }
  25101. return node;
  25102. }
  25103. }
  25104. MaterialNode.ALPHA_TEST = 'alphaTest';
  25105. MaterialNode.COLOR = 'color';
  25106. MaterialNode.OPACITY = 'opacity';
  25107. MaterialNode.SHININESS = 'shininess';
  25108. MaterialNode.SPECULAR = 'specular';
  25109. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25110. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25111. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25112. MaterialNode.REFLECTIVITY = 'reflectivity';
  25113. MaterialNode.ROUGHNESS = 'roughness';
  25114. MaterialNode.METALNESS = 'metalness';
  25115. MaterialNode.NORMAL = 'normal';
  25116. MaterialNode.CLEARCOAT = 'clearcoat';
  25117. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25118. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25119. MaterialNode.EMISSIVE = 'emissive';
  25120. MaterialNode.ROTATION = 'rotation';
  25121. MaterialNode.SHEEN = 'sheen';
  25122. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25123. MaterialNode.ANISOTROPY = 'anisotropy';
  25124. MaterialNode.IRIDESCENCE = 'iridescence';
  25125. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25126. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25127. MaterialNode.IOR = 'ior';
  25128. MaterialNode.TRANSMISSION = 'transmission';
  25129. MaterialNode.THICKNESS = 'thickness';
  25130. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25131. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25132. MaterialNode.LINE_SCALE = 'scale';
  25133. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25134. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25135. MaterialNode.LINE_WIDTH = 'linewidth';
  25136. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25137. MaterialNode.POINT_WIDTH = 'pointWidth';
  25138. MaterialNode.DISPERSION = 'dispersion';
  25139. MaterialNode.LIGHT_MAP = 'light';
  25140. MaterialNode.AO_MAP = 'ao';
  25141. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25142. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25143. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25144. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25145. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25146. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25147. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25148. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25149. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25150. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25151. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25152. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25153. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  25154. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25155. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25156. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  25157. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25158. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25159. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25160. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25161. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25162. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25163. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25164. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25165. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25166. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  25167. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25168. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25169. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25170. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25171. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25172. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25173. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25174. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25175. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25176. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  25177. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  25178. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  25179. return frame.material;
  25180. } ).onRenderUpdate( function ( { material } ) {
  25181. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25182. } );
  25183. class ModelViewProjectionNode extends TempNode {
  25184. static get type() {
  25185. return 'ModelViewProjectionNode';
  25186. }
  25187. constructor( positionNode = null ) {
  25188. super( 'vec4' );
  25189. this.positionNode = positionNode;
  25190. }
  25191. setup( builder ) {
  25192. if ( builder.shaderStage === 'fragment' ) {
  25193. return varying( builder.context.mvp );
  25194. }
  25195. const position = this.positionNode || positionLocal;
  25196. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  25197. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  25198. }
  25199. }
  25200. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  25201. class IndexNode extends Node {
  25202. static get type() {
  25203. return 'IndexNode';
  25204. }
  25205. constructor( scope ) {
  25206. super( 'uint' );
  25207. this.scope = scope;
  25208. this.isInstanceIndexNode = true;
  25209. }
  25210. generate( builder ) {
  25211. const nodeType = this.getNodeType( builder );
  25212. const scope = this.scope;
  25213. let propertyName;
  25214. if ( scope === IndexNode.VERTEX ) {
  25215. propertyName = builder.getVertexIndex();
  25216. } else if ( scope === IndexNode.INSTANCE ) {
  25217. propertyName = builder.getInstanceIndex();
  25218. } else if ( scope === IndexNode.DRAW ) {
  25219. propertyName = builder.getDrawIndex();
  25220. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  25221. propertyName = builder.getInvocationLocalIndex();
  25222. } else {
  25223. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  25224. }
  25225. let output;
  25226. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25227. output = propertyName;
  25228. } else {
  25229. const nodeVarying = varying( this );
  25230. output = nodeVarying.build( builder, nodeType );
  25231. }
  25232. return output;
  25233. }
  25234. }
  25235. IndexNode.VERTEX = 'vertex';
  25236. IndexNode.INSTANCE = 'instance';
  25237. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  25238. IndexNode.DRAW = 'draw';
  25239. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  25240. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  25241. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  25242. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  25243. class InstanceNode extends Node {
  25244. static get type() {
  25245. return 'InstanceNode';
  25246. }
  25247. constructor( instanceMesh ) {
  25248. super( 'void' );
  25249. this.instanceMesh = instanceMesh;
  25250. this.instanceMatrixNode = null;
  25251. this.instanceColorNode = null;
  25252. this.updateType = NodeUpdateType.FRAME;
  25253. this.buffer = null;
  25254. this.bufferColor = null;
  25255. }
  25256. setup( builder ) {
  25257. let instanceMatrixNode = this.instanceMatrixNode;
  25258. let instanceColorNode = this.instanceColorNode;
  25259. const instanceMesh = this.instanceMesh;
  25260. if ( instanceMatrixNode === null ) {
  25261. const instanceAttribute = instanceMesh.instanceMatrix;
  25262. // 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.
  25263. if ( instanceMesh.count <= 1000 ) {
  25264. instanceMatrixNode = buffer( instanceAttribute.array, 'mat4', Math.max( instanceMesh.count, 1 ) ).element( instanceIndex );
  25265. } else {
  25266. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25267. this.buffer = buffer;
  25268. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25269. const instanceBuffers = [
  25270. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25271. bufferFn( buffer, 'vec4', 16, 0 ),
  25272. bufferFn( buffer, 'vec4', 16, 4 ),
  25273. bufferFn( buffer, 'vec4', 16, 8 ),
  25274. bufferFn( buffer, 'vec4', 16, 12 )
  25275. ];
  25276. instanceMatrixNode = mat4( ...instanceBuffers );
  25277. }
  25278. this.instanceMatrixNode = instanceMatrixNode;
  25279. }
  25280. const instanceColorAttribute = instanceMesh.instanceColor;
  25281. if ( instanceColorAttribute && instanceColorNode === null ) {
  25282. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25283. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25284. this.bufferColor = buffer;
  25285. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25286. this.instanceColorNode = instanceColorNode;
  25287. }
  25288. // POSITION
  25289. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25290. positionLocal.assign( instancePosition );
  25291. // NORMAL
  25292. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25293. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  25294. // ASSIGNS
  25295. normalLocal.assign( instanceNormal );
  25296. }
  25297. // COLOR
  25298. if ( this.instanceColorNode !== null ) {
  25299. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25300. }
  25301. }
  25302. update( /*frame*/ ) {
  25303. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25304. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25305. }
  25306. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25307. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25308. }
  25309. }
  25310. }
  25311. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  25312. class BatchNode extends Node {
  25313. static get type() {
  25314. return 'BatchNode';
  25315. }
  25316. constructor( batchMesh ) {
  25317. super( 'void' );
  25318. this.batchMesh = batchMesh;
  25319. this.batchingIdNode = null;
  25320. }
  25321. setup( builder ) {
  25322. // POSITION
  25323. if ( this.batchingIdNode === null ) {
  25324. if ( builder.getDrawIndex() === null ) {
  25325. this.batchingIdNode = instanceIndex;
  25326. } else {
  25327. this.batchingIdNode = drawIndex;
  25328. }
  25329. }
  25330. const getIndirectIndex = Fn( ( [ id ] ) => {
  25331. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25332. const x = int( id ).modInt( int( size ) );
  25333. const y = int( id ).div( int( size ) );
  25334. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25335. } ).setLayout( {
  25336. name: 'getIndirectIndex',
  25337. type: 'uint',
  25338. inputs: [
  25339. { name: 'id', type: 'int' }
  25340. ]
  25341. } );
  25342. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  25343. const matricesTexture = this.batchMesh._matricesTexture;
  25344. const size = textureSize( textureLoad( matricesTexture ), 0 );
  25345. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  25346. const x = j.modInt( size );
  25347. const y = j.div( int( size ) );
  25348. const batchingMatrix = mat4(
  25349. textureLoad( matricesTexture, ivec2( x, y ) ),
  25350. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  25351. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  25352. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  25353. );
  25354. const colorsTexture = this.batchMesh._colorsTexture;
  25355. if ( colorsTexture !== null ) {
  25356. const getBatchingColor = Fn( ( [ id ] ) => {
  25357. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  25358. const j = id;
  25359. const x = j.modInt( size );
  25360. const y = j.div( size );
  25361. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  25362. } ).setLayout( {
  25363. name: 'getBatchingColor',
  25364. type: 'vec3',
  25365. inputs: [
  25366. { name: 'id', type: 'int' }
  25367. ]
  25368. } );
  25369. const color = getBatchingColor( indirectId );
  25370. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  25371. }
  25372. const bm = mat3( batchingMatrix );
  25373. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25374. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25375. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25376. normalLocal.assign( batchingNormal );
  25377. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25378. tangentLocal.mulAssign( bm );
  25379. }
  25380. }
  25381. }
  25382. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  25383. const _frameId = new WeakMap();
  25384. class SkinningNode extends Node {
  25385. static get type() {
  25386. return 'SkinningNode';
  25387. }
  25388. constructor( skinnedMesh, useReference = false ) {
  25389. super( 'void' );
  25390. this.skinnedMesh = skinnedMesh;
  25391. this.useReference = useReference;
  25392. this.updateType = NodeUpdateType.OBJECT;
  25393. //
  25394. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25395. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25396. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25397. if ( useReference ) {
  25398. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25399. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25400. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25401. } else {
  25402. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25403. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25404. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25405. }
  25406. this.bindMatrixNode = bindMatrixNode;
  25407. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25408. this.boneMatricesNode = boneMatricesNode;
  25409. this.previousBoneMatricesNode = null;
  25410. }
  25411. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  25412. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25413. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25414. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25415. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25416. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25417. // POSITION
  25418. const skinVertex = bindMatrixNode.mul( position );
  25419. const skinned = add(
  25420. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25421. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25422. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25423. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25424. );
  25425. return bindMatrixInverseNode.mul( skinned ).xyz;
  25426. }
  25427. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  25428. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25429. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25430. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25431. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25432. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25433. // NORMAL
  25434. let skinMatrix = add(
  25435. skinWeightNode.x.mul( boneMatX ),
  25436. skinWeightNode.y.mul( boneMatY ),
  25437. skinWeightNode.z.mul( boneMatZ ),
  25438. skinWeightNode.w.mul( boneMatW )
  25439. );
  25440. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25441. return skinMatrix.transformDirection( normal ).xyz;
  25442. }
  25443. getPreviousSkinnedPosition( builder ) {
  25444. const skinnedMesh = builder.object;
  25445. if ( this.previousBoneMatricesNode === null ) {
  25446. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  25447. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25448. }
  25449. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  25450. }
  25451. needsPreviousBoneMatrices( builder ) {
  25452. const mrt = builder.renderer.getMRT();
  25453. return mrt && mrt.has( 'velocity' );
  25454. }
  25455. setup( builder ) {
  25456. if ( this.needsPreviousBoneMatrices( builder ) ) {
  25457. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  25458. }
  25459. const skinPosition = this.getSkinnedPosition();
  25460. positionLocal.assign( skinPosition );
  25461. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25462. const skinNormal = this.getSkinnedNormal();
  25463. normalLocal.assign( skinNormal );
  25464. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25465. tangentLocal.assign( skinNormal );
  25466. }
  25467. }
  25468. }
  25469. generate( builder, output ) {
  25470. if ( output !== 'void' ) {
  25471. return positionLocal.build( builder, output );
  25472. }
  25473. }
  25474. update( frame ) {
  25475. const object = this.useReference ? frame.object : this.skinnedMesh;
  25476. const skeleton = object.skeleton;
  25477. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  25478. _frameId.set( skeleton, frame.frameId );
  25479. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  25480. skeleton.update();
  25481. }
  25482. }
  25483. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25484. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25485. class LoopNode extends Node {
  25486. static get type() {
  25487. return 'LoopNode';
  25488. }
  25489. constructor( params = [] ) {
  25490. super();
  25491. this.params = params;
  25492. }
  25493. getVarName( index ) {
  25494. return String.fromCharCode( 'i'.charCodeAt() + index );
  25495. }
  25496. getProperties( builder ) {
  25497. const properties = builder.getNodeProperties( this );
  25498. if ( properties.stackNode !== undefined ) return properties;
  25499. //
  25500. const inputs = {};
  25501. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25502. const param = this.params[ i ];
  25503. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25504. const type = ( param.isNode !== true && param.type ) || 'int';
  25505. inputs[ name ] = expression( name, type );
  25506. }
  25507. const stack = builder.addStack(); // TODO: cache() it
  25508. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25509. properties.stackNode = stack;
  25510. builder.removeStack();
  25511. return properties;
  25512. }
  25513. getNodeType( builder ) {
  25514. const { returnsNode } = this.getProperties( builder );
  25515. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25516. }
  25517. setup( builder ) {
  25518. // setup properties
  25519. this.getProperties( builder );
  25520. }
  25521. generate( builder ) {
  25522. const properties = this.getProperties( builder );
  25523. const params = this.params;
  25524. const stackNode = properties.stackNode;
  25525. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25526. const param = params[ i ];
  25527. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25528. if ( param.isNode ) {
  25529. type = 'int';
  25530. name = this.getVarName( i );
  25531. start = '0';
  25532. end = param.build( builder, type );
  25533. condition = '<';
  25534. } else {
  25535. type = param.type || 'int';
  25536. name = param.name || this.getVarName( i );
  25537. start = param.start;
  25538. end = param.end;
  25539. condition = param.condition;
  25540. update = param.update;
  25541. if ( typeof start === 'number' ) start = start.toString();
  25542. else if ( start && start.isNode ) start = start.build( builder, type );
  25543. if ( typeof end === 'number' ) end = end.toString();
  25544. else if ( end && end.isNode ) end = end.build( builder, type );
  25545. if ( start !== undefined && end === undefined ) {
  25546. start = start + ' - 1';
  25547. end = '0';
  25548. condition = '>=';
  25549. } else if ( end !== undefined && start === undefined ) {
  25550. start = '0';
  25551. condition = '<';
  25552. }
  25553. if ( condition === undefined ) {
  25554. if ( Number( start ) > Number( end ) ) {
  25555. condition = '>=';
  25556. } else {
  25557. condition = '<';
  25558. }
  25559. }
  25560. }
  25561. const internalParam = { start, end, condition };
  25562. //
  25563. const startSnippet = internalParam.start;
  25564. const endSnippet = internalParam.end;
  25565. let declarationSnippet = '';
  25566. let conditionalSnippet = '';
  25567. let updateSnippet = '';
  25568. if ( ! update ) {
  25569. if ( type === 'int' || type === 'uint' ) {
  25570. if ( condition.includes( '<' ) ) update = '++';
  25571. else update = '--';
  25572. } else {
  25573. if ( condition.includes( '<' ) ) update = '+= 1.';
  25574. else update = '-= 1.';
  25575. }
  25576. }
  25577. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25578. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25579. updateSnippet += name + ' ' + update;
  25580. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25581. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25582. }
  25583. const stackSnippet = stackNode.build( builder, 'void' );
  25584. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25585. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25586. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25587. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25588. }
  25589. builder.addFlowTab();
  25590. return returnsSnippet;
  25591. }
  25592. }
  25593. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25594. const Continue = () => expression( 'continue' ).append();
  25595. const Break = () => expression( 'break' ).append();
  25596. //
  25597. const loop = ( ...params ) => { // @deprecated, r168
  25598. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  25599. return Loop( ...params );
  25600. };
  25601. const _morphTextures = /*@__PURE__*/ new WeakMap();
  25602. const _morphVec4 = /*@__PURE__*/ new Vector4();
  25603. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25604. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25605. const y = texelIndex.div( width );
  25606. const x = texelIndex.sub( y.mul( width ) );
  25607. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25608. return bufferAttrib.mul( influence );
  25609. } );
  25610. function getEntry( geometry ) {
  25611. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25612. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25613. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25614. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25615. // into an array of data textures. Each layer represents a single morph target.
  25616. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25617. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25618. let entry = _morphTextures.get( geometry );
  25619. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25620. if ( entry !== undefined ) entry.texture.dispose();
  25621. const morphTargets = geometry.morphAttributes.position || [];
  25622. const morphNormals = geometry.morphAttributes.normal || [];
  25623. const morphColors = geometry.morphAttributes.color || [];
  25624. let vertexDataCount = 0;
  25625. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25626. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25627. if ( hasMorphColors === true ) vertexDataCount = 3;
  25628. let width = geometry.attributes.position.count * vertexDataCount;
  25629. let height = 1;
  25630. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25631. if ( width > maxTextureSize ) {
  25632. height = Math.ceil( width / maxTextureSize );
  25633. width = maxTextureSize;
  25634. }
  25635. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25636. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25637. bufferTexture.type = FloatType;
  25638. bufferTexture.needsUpdate = true;
  25639. // fill buffer
  25640. const vertexDataStride = vertexDataCount * 4;
  25641. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25642. const morphTarget = morphTargets[ i ];
  25643. const morphNormal = morphNormals[ i ];
  25644. const morphColor = morphColors[ i ];
  25645. const offset = width * height * 4 * i;
  25646. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25647. const stride = j * vertexDataStride;
  25648. if ( hasMorphPosition === true ) {
  25649. _morphVec4.fromBufferAttribute( morphTarget, j );
  25650. buffer[ offset + stride + 0 ] = _morphVec4.x;
  25651. buffer[ offset + stride + 1 ] = _morphVec4.y;
  25652. buffer[ offset + stride + 2 ] = _morphVec4.z;
  25653. buffer[ offset + stride + 3 ] = 0;
  25654. }
  25655. if ( hasMorphNormals === true ) {
  25656. _morphVec4.fromBufferAttribute( morphNormal, j );
  25657. buffer[ offset + stride + 4 ] = _morphVec4.x;
  25658. buffer[ offset + stride + 5 ] = _morphVec4.y;
  25659. buffer[ offset + stride + 6 ] = _morphVec4.z;
  25660. buffer[ offset + stride + 7 ] = 0;
  25661. }
  25662. if ( hasMorphColors === true ) {
  25663. _morphVec4.fromBufferAttribute( morphColor, j );
  25664. buffer[ offset + stride + 8 ] = _morphVec4.x;
  25665. buffer[ offset + stride + 9 ] = _morphVec4.y;
  25666. buffer[ offset + stride + 10 ] = _morphVec4.z;
  25667. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  25668. }
  25669. }
  25670. }
  25671. entry = {
  25672. count: morphTargetsCount,
  25673. texture: bufferTexture,
  25674. stride: vertexDataCount,
  25675. size: new Vector2( width, height )
  25676. };
  25677. _morphTextures.set( geometry, entry );
  25678. function disposeTexture() {
  25679. bufferTexture.dispose();
  25680. _morphTextures.delete( geometry );
  25681. geometry.removeEventListener( 'dispose', disposeTexture );
  25682. }
  25683. geometry.addEventListener( 'dispose', disposeTexture );
  25684. }
  25685. return entry;
  25686. }
  25687. class MorphNode extends Node {
  25688. static get type() {
  25689. return 'MorphNode';
  25690. }
  25691. constructor( mesh ) {
  25692. super( 'void' );
  25693. this.mesh = mesh;
  25694. this.morphBaseInfluence = uniform( 1 );
  25695. this.updateType = NodeUpdateType.OBJECT;
  25696. }
  25697. setup( builder ) {
  25698. const { geometry } = builder;
  25699. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25700. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  25701. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25702. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25703. // nodes
  25704. const { texture: bufferMap, stride, size } = getEntry( geometry );
  25705. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  25706. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  25707. const width = int( size.width );
  25708. Loop( morphTargetsCount, ( { i } ) => {
  25709. const influence = float( 0 ).toVar();
  25710. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  25711. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  25712. } else {
  25713. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  25714. }
  25715. if ( hasMorphPosition === true ) {
  25716. positionLocal.addAssign( getMorph( {
  25717. bufferMap,
  25718. influence,
  25719. stride,
  25720. width,
  25721. depth: i,
  25722. offset: int( 0 )
  25723. } ) );
  25724. }
  25725. if ( hasMorphNormals === true ) {
  25726. normalLocal.addAssign( getMorph( {
  25727. bufferMap,
  25728. influence,
  25729. stride,
  25730. width,
  25731. depth: i,
  25732. offset: int( 1 )
  25733. } ) );
  25734. }
  25735. } );
  25736. }
  25737. update() {
  25738. const morphBaseInfluence = this.morphBaseInfluence;
  25739. if ( this.mesh.geometry.morphTargetsRelative ) {
  25740. morphBaseInfluence.value = 1;
  25741. } else {
  25742. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  25743. }
  25744. }
  25745. }
  25746. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  25747. const sortLights = ( lights ) => {
  25748. return lights.sort( ( a, b ) => a.id - b.id );
  25749. };
  25750. const getLightNodeById = ( id, lightNodes ) => {
  25751. for ( const lightNode of lightNodes ) {
  25752. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  25753. return lightNode;
  25754. }
  25755. }
  25756. return null;
  25757. };
  25758. class LightsNode extends Node {
  25759. static get type() {
  25760. return 'LightsNode';
  25761. }
  25762. constructor( lights = [] ) {
  25763. super( 'vec3' );
  25764. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  25765. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  25766. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  25767. this._lights = lights;
  25768. this._lightNodes = null;
  25769. this._lightNodesHash = null;
  25770. this.global = true;
  25771. }
  25772. getHash( builder ) {
  25773. if ( this._lightNodesHash === null ) {
  25774. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  25775. const hash = [];
  25776. for ( const lightNode of this._lightNodes ) {
  25777. hash.push( lightNode.getHash() );
  25778. }
  25779. this._lightNodesHash = 'lights-' + hash.join( ',' );
  25780. }
  25781. return this._lightNodesHash;
  25782. }
  25783. analyze( builder ) {
  25784. const properties = builder.getDataFromNode( this );
  25785. for ( const node of properties.nodes ) {
  25786. node.build( builder );
  25787. }
  25788. }
  25789. setupLightsNode( builder ) {
  25790. const lightNodes = [];
  25791. const previousLightNodes = this._lightNodes;
  25792. const lights = sortLights( this._lights );
  25793. const nodeLibrary = builder.renderer.nodes.library;
  25794. for ( const light of lights ) {
  25795. if ( light.isNode ) {
  25796. lightNodes.push( nodeObject( light ) );
  25797. } else {
  25798. let lightNode = null;
  25799. if ( previousLightNodes !== null ) {
  25800. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  25801. }
  25802. if ( lightNode === null ) {
  25803. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  25804. if ( lightNodeClass === null ) {
  25805. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  25806. continue;
  25807. }
  25808. lightNodes.push( nodeObject( new lightNodeClass( light ) ) );
  25809. }
  25810. }
  25811. }
  25812. this._lightNodes = lightNodes;
  25813. }
  25814. setup( builder ) {
  25815. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  25816. const context = builder.context;
  25817. const lightingModel = context.lightingModel;
  25818. let outgoingLightNode = this.outgoingLightNode;
  25819. if ( lightingModel ) {
  25820. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  25821. context.outgoingLight = outgoingLightNode;
  25822. const stack = builder.addStack();
  25823. //
  25824. const properties = builder.getDataFromNode( this );
  25825. properties.nodes = stack.nodes;
  25826. //
  25827. lightingModel.start( context, stack, builder );
  25828. // lights
  25829. for ( const lightNode of _lightNodes ) {
  25830. lightNode.build( builder );
  25831. }
  25832. //
  25833. lightingModel.indirect( context, stack, builder );
  25834. //
  25835. const { backdrop, backdropAlpha } = context;
  25836. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  25837. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  25838. if ( backdrop !== null ) {
  25839. if ( backdropAlpha !== null ) {
  25840. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  25841. } else {
  25842. totalDiffuse = vec3( backdrop );
  25843. }
  25844. context.material.transparent = true;
  25845. }
  25846. totalDiffuseNode.assign( totalDiffuse );
  25847. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  25848. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  25849. //
  25850. lightingModel.finish( context, stack, builder );
  25851. //
  25852. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  25853. }
  25854. return outgoingLightNode;
  25855. }
  25856. setLights( lights ) {
  25857. this._lights = lights;
  25858. this._lightNodes = null;
  25859. this._lightNodesHash = null;
  25860. return this;
  25861. }
  25862. getLights() {
  25863. return this._lights;
  25864. }
  25865. }
  25866. const lights = /*@__PURE__*/ nodeProxy( LightsNode );
  25867. class LightingNode extends Node {
  25868. static get type() {
  25869. return 'LightingNode';
  25870. }
  25871. constructor() {
  25872. super( 'vec3' );
  25873. this.isLightingNode = true;
  25874. }
  25875. generate( /*builder*/ ) {
  25876. console.warn( 'Abstract function.' );
  25877. }
  25878. }
  25879. class AONode extends LightingNode {
  25880. static get type() {
  25881. return 'AONode';
  25882. }
  25883. constructor( aoNode = null ) {
  25884. super();
  25885. this.aoNode = aoNode;
  25886. }
  25887. setup( builder ) {
  25888. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  25889. }
  25890. }
  25891. class LightingContextNode extends ContextNode {
  25892. static get type() {
  25893. return 'LightingContextNode';
  25894. }
  25895. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  25896. super( node );
  25897. this.lightingModel = lightingModel;
  25898. this.backdropNode = backdropNode;
  25899. this.backdropAlphaNode = backdropAlphaNode;
  25900. this._value = null;
  25901. }
  25902. getContext() {
  25903. const { backdropNode, backdropAlphaNode } = this;
  25904. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  25905. directSpecular = vec3().toVar( 'directSpecular' ),
  25906. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  25907. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  25908. const reflectedLight = {
  25909. directDiffuse,
  25910. directSpecular,
  25911. indirectDiffuse,
  25912. indirectSpecular
  25913. };
  25914. const context = {
  25915. radiance: vec3().toVar( 'radiance' ),
  25916. irradiance: vec3().toVar( 'irradiance' ),
  25917. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  25918. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  25919. reflectedLight,
  25920. backdrop: backdropNode,
  25921. backdropAlpha: backdropAlphaNode
  25922. };
  25923. return context;
  25924. }
  25925. setup( builder ) {
  25926. this.value = this._value || ( this._value = this.getContext() );
  25927. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  25928. return super.setup( builder );
  25929. }
  25930. }
  25931. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  25932. class IrradianceNode extends LightingNode {
  25933. static get type() {
  25934. return 'IrradianceNode';
  25935. }
  25936. constructor( node ) {
  25937. super();
  25938. this.node = node;
  25939. }
  25940. setup( builder ) {
  25941. builder.context.irradiance.addAssign( this.node );
  25942. }
  25943. }
  25944. let screenSizeVec, viewportVec;
  25945. class ScreenNode extends Node {
  25946. static get type() {
  25947. return 'ScreenNode';
  25948. }
  25949. constructor( scope ) {
  25950. super();
  25951. this.scope = scope;
  25952. this.isViewportNode = true;
  25953. }
  25954. getNodeType() {
  25955. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  25956. else return 'vec2';
  25957. }
  25958. getUpdateType() {
  25959. let updateType = NodeUpdateType.NONE;
  25960. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  25961. updateType = NodeUpdateType.RENDER;
  25962. }
  25963. this.updateType = updateType;
  25964. return updateType;
  25965. }
  25966. update( { renderer } ) {
  25967. const renderTarget = renderer.getRenderTarget();
  25968. if ( this.scope === ScreenNode.VIEWPORT ) {
  25969. if ( renderTarget !== null ) {
  25970. viewportVec.copy( renderTarget.viewport );
  25971. } else {
  25972. renderer.getViewport( viewportVec );
  25973. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  25974. }
  25975. } else {
  25976. if ( renderTarget !== null ) {
  25977. screenSizeVec.width = renderTarget.width;
  25978. screenSizeVec.height = renderTarget.height;
  25979. } else {
  25980. renderer.getDrawingBufferSize( screenSizeVec );
  25981. }
  25982. }
  25983. }
  25984. setup( /*builder*/ ) {
  25985. const scope = this.scope;
  25986. let output = null;
  25987. if ( scope === ScreenNode.SIZE ) {
  25988. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  25989. } else if ( scope === ScreenNode.VIEWPORT ) {
  25990. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  25991. } else {
  25992. output = vec2( screenCoordinate.div( screenSize ) );
  25993. }
  25994. return output;
  25995. }
  25996. generate( builder ) {
  25997. if ( this.scope === ScreenNode.COORDINATE ) {
  25998. let coord = builder.getFragCoord();
  25999. if ( builder.isFlipY() ) {
  26000. // follow webgpu standards
  26001. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  26002. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  26003. }
  26004. return coord;
  26005. }
  26006. return super.generate( builder );
  26007. }
  26008. }
  26009. ScreenNode.COORDINATE = 'coordinate';
  26010. ScreenNode.VIEWPORT = 'viewport';
  26011. ScreenNode.SIZE = 'size';
  26012. ScreenNode.UV = 'uv';
  26013. // Screen
  26014. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  26015. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  26016. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  26017. // Viewport
  26018. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  26019. const viewportSize = viewport.zw;
  26020. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  26021. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  26022. // Deprecated
  26023. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  26024. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  26025. return screenSize;
  26026. }, 'vec2' ).once() )();
  26027. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26028. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  26029. return screenUV;
  26030. }, 'vec2' ).once() )();
  26031. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26032. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  26033. return screenUV.flipY();
  26034. }, 'vec2' ).once() )();
  26035. const _size$a = /*@__PURE__*/ new Vector2();
  26036. class ViewportTextureNode extends TextureNode {
  26037. static get type() {
  26038. return 'ViewportTextureNode';
  26039. }
  26040. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  26041. if ( framebufferTexture === null ) {
  26042. framebufferTexture = new FramebufferTexture();
  26043. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26044. }
  26045. super( framebufferTexture, uvNode, levelNode );
  26046. this.generateMipmaps = false;
  26047. this.isOutputTextureNode = true;
  26048. this.updateBeforeType = NodeUpdateType.FRAME;
  26049. }
  26050. updateBefore( frame ) {
  26051. const renderer = frame.renderer;
  26052. renderer.getDrawingBufferSize( _size$a );
  26053. //
  26054. const framebufferTexture = this.value;
  26055. if ( framebufferTexture.image.width !== _size$a.width || framebufferTexture.image.height !== _size$a.height ) {
  26056. framebufferTexture.image.width = _size$a.width;
  26057. framebufferTexture.image.height = _size$a.height;
  26058. framebufferTexture.needsUpdate = true;
  26059. }
  26060. //
  26061. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26062. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26063. renderer.copyFramebufferToTexture( framebufferTexture );
  26064. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26065. }
  26066. clone() {
  26067. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26068. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26069. return viewportTextureNode;
  26070. }
  26071. }
  26072. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  26073. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26074. let sharedDepthbuffer = null;
  26075. class ViewportDepthTextureNode extends ViewportTextureNode {
  26076. static get type() {
  26077. return 'ViewportDepthTextureNode';
  26078. }
  26079. constructor( uvNode = screenUV, levelNode = null ) {
  26080. if ( sharedDepthbuffer === null ) {
  26081. sharedDepthbuffer = new DepthTexture();
  26082. }
  26083. super( uvNode, levelNode, sharedDepthbuffer );
  26084. }
  26085. }
  26086. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  26087. class ViewportDepthNode extends Node {
  26088. static get type() {
  26089. return 'ViewportDepthNode';
  26090. }
  26091. constructor( scope, valueNode = null ) {
  26092. super( 'float' );
  26093. this.scope = scope;
  26094. this.valueNode = valueNode;
  26095. this.isViewportDepthNode = true;
  26096. }
  26097. generate( builder ) {
  26098. const { scope } = this;
  26099. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26100. return builder.getFragDepth();
  26101. }
  26102. return super.generate( builder );
  26103. }
  26104. setup( { camera } ) {
  26105. const { scope } = this;
  26106. const value = this.valueNode;
  26107. let node = null;
  26108. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26109. if ( value !== null ) {
  26110. node = depthBase().assign( value );
  26111. }
  26112. } else if ( scope === ViewportDepthNode.DEPTH ) {
  26113. if ( camera.isPerspectiveCamera ) {
  26114. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26115. } else {
  26116. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26117. }
  26118. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26119. if ( value !== null ) {
  26120. if ( camera.isPerspectiveCamera ) {
  26121. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  26122. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26123. } else {
  26124. node = value;
  26125. }
  26126. } else {
  26127. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26128. }
  26129. }
  26130. return node;
  26131. }
  26132. }
  26133. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  26134. ViewportDepthNode.DEPTH = 'depth';
  26135. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26136. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26137. // -near maps to 0; -far maps to 1
  26138. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26139. // maps orthographic depth in [ 0, 1 ] to viewZ
  26140. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26141. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26142. // -near maps to 0; -far maps to 1
  26143. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26144. // maps perspective depth in [ 0, 1 ] to viewZ
  26145. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26146. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  26147. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26148. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26149. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  26150. depth.assign = ( value ) => depthBase( value );
  26151. class ClippingNode extends Node {
  26152. static get type() {
  26153. return 'ClippingNode';
  26154. }
  26155. constructor( scope = ClippingNode.DEFAULT ) {
  26156. super();
  26157. this.scope = scope;
  26158. }
  26159. setup( builder ) {
  26160. super.setup( builder );
  26161. const clippingContext = builder.clippingContext;
  26162. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26163. const numClippingPlanes = globalClippingCount + localClippingCount;
  26164. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26165. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26166. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26167. } else {
  26168. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26169. }
  26170. }
  26171. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26172. return Fn( () => {
  26173. const clippingPlanes = uniformArray( planes );
  26174. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26175. const distanceGradient = property( 'float', 'distanceToGradient' );
  26176. const clipOpacity = property( 'float', 'clipOpacity' );
  26177. clipOpacity.assign( 1 );
  26178. let plane;
  26179. Loop( numUnionClippingPlanes, ( { i } ) => {
  26180. plane = clippingPlanes.element( i );
  26181. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26182. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26183. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26184. clipOpacity.equal( 0.0 ).discard();
  26185. } );
  26186. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26187. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26188. unionClipOpacity.assign( 1 );
  26189. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26190. plane = clippingPlanes.element( i );
  26191. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26192. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26193. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26194. } );
  26195. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26196. }
  26197. diffuseColor.a.mulAssign( clipOpacity );
  26198. diffuseColor.a.equal( 0.0 ).discard();
  26199. } )();
  26200. }
  26201. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26202. return Fn( () => {
  26203. const clippingPlanes = uniformArray( planes );
  26204. let plane;
  26205. Loop( numUnionClippingPlanes, ( { i } ) => {
  26206. plane = clippingPlanes.element( i );
  26207. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26208. } );
  26209. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26210. const clipped = property( 'bool', 'clipped' );
  26211. clipped.assign( true );
  26212. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26213. plane = clippingPlanes.element( i );
  26214. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26215. } );
  26216. clipped.discard();
  26217. }
  26218. } )();
  26219. }
  26220. }
  26221. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26222. ClippingNode.DEFAULT = 'default';
  26223. const clipping = () => nodeObject( new ClippingNode() );
  26224. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26225. class NodeMaterial extends Material {
  26226. static get type() {
  26227. return 'NodeMaterial';
  26228. }
  26229. constructor() {
  26230. super();
  26231. this.isNodeMaterial = true;
  26232. this.type = this.constructor.type;
  26233. this.forceSinglePass = false;
  26234. this.fog = true;
  26235. this.lights = false;
  26236. this.lightsNode = null;
  26237. this.envNode = null;
  26238. this.aoNode = null;
  26239. this.colorNode = null;
  26240. this.normalNode = null;
  26241. this.opacityNode = null;
  26242. this.backdropNode = null;
  26243. this.backdropAlphaNode = null;
  26244. this.alphaTestNode = null;
  26245. this.positionNode = null;
  26246. this.depthNode = null;
  26247. this.shadowNode = null;
  26248. this.shadowPositionNode = null;
  26249. this.outputNode = null;
  26250. this.mrtNode = null;
  26251. this.fragmentNode = null;
  26252. this.vertexNode = null;
  26253. }
  26254. customProgramCacheKey() {
  26255. return this.type + getCacheKey$1( this );
  26256. }
  26257. build( builder ) {
  26258. this.setup( builder );
  26259. }
  26260. setupObserver( builder ) {
  26261. return new NodeMaterialObserver( builder );
  26262. }
  26263. setup( builder ) {
  26264. builder.context.setupNormal = () => this.setupNormal( builder );
  26265. // < VERTEX STAGE >
  26266. builder.addStack();
  26267. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26268. builder.addFlow( 'vertex', builder.removeStack() );
  26269. // < FRAGMENT STAGE >
  26270. builder.addStack();
  26271. let resultNode;
  26272. const clippingNode = this.setupClipping( builder );
  26273. if ( this.depthWrite === true ) this.setupDepth( builder );
  26274. if ( this.fragmentNode === null ) {
  26275. this.setupDiffuseColor( builder );
  26276. this.setupVariants( builder );
  26277. const outgoingLightNode = this.setupLighting( builder );
  26278. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26279. // force unsigned floats - useful for RenderTargets
  26280. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26281. resultNode = this.setupOutput( builder, basicOutput );
  26282. // OUTPUT NODE
  26283. output.assign( resultNode );
  26284. //
  26285. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26286. // MRT
  26287. const renderTarget = builder.renderer.getRenderTarget();
  26288. if ( renderTarget !== null ) {
  26289. const mrt = builder.renderer.getMRT();
  26290. const materialMRT = this.mrtNode;
  26291. if ( mrt !== null ) {
  26292. resultNode = mrt;
  26293. if ( materialMRT !== null ) {
  26294. resultNode = mrt.merge( materialMRT );
  26295. }
  26296. } else if ( materialMRT !== null ) {
  26297. resultNode = materialMRT;
  26298. }
  26299. }
  26300. } else {
  26301. let fragmentNode = this.fragmentNode;
  26302. if ( fragmentNode.isOutputStructNode !== true ) {
  26303. fragmentNode = vec4( fragmentNode );
  26304. }
  26305. resultNode = this.setupOutput( builder, fragmentNode );
  26306. }
  26307. builder.stack.outputNode = resultNode;
  26308. builder.addFlow( 'fragment', builder.removeStack() );
  26309. // < MONITOR >
  26310. builder.monitor = this.setupObserver( builder );
  26311. }
  26312. setupClipping( builder ) {
  26313. if ( builder.clippingContext === null ) return null;
  26314. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26315. let result = null;
  26316. if ( globalClippingCount || localClippingCount ) {
  26317. const samples = builder.renderer.samples;
  26318. if ( this.alphaToCoverage && samples > 1 ) {
  26319. // to be added to flow when the color/alpha value has been determined
  26320. result = clippingAlpha();
  26321. } else {
  26322. builder.stack.add( clipping() );
  26323. }
  26324. }
  26325. return result;
  26326. }
  26327. setupDepth( builder ) {
  26328. const { renderer } = builder;
  26329. // Depth
  26330. let depthNode = this.depthNode;
  26331. if ( depthNode === null ) {
  26332. const mrt = renderer.getMRT();
  26333. if ( mrt && mrt.has( 'depth' ) ) {
  26334. depthNode = mrt.get( 'depth' );
  26335. } else if ( renderer.logarithmicDepthBuffer === true ) {
  26336. const fragDepth = modelViewProjection().w.add( 1 );
  26337. depthNode = fragDepth.log2().mul( cameraLogDepth ).mul( 0.5 );
  26338. }
  26339. }
  26340. if ( depthNode !== null ) {
  26341. depth.assign( depthNode ).append();
  26342. }
  26343. }
  26344. setupPosition( builder ) {
  26345. const { object } = builder;
  26346. const geometry = object.geometry;
  26347. builder.addStack();
  26348. // Vertex
  26349. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26350. morphReference( object ).append();
  26351. }
  26352. if ( object.isSkinnedMesh === true ) {
  26353. skinningReference( object ).append();
  26354. }
  26355. if ( this.displacementMap ) {
  26356. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26357. const displacementScale = materialReference( 'displacementScale', 'float' );
  26358. const displacementBias = materialReference( 'displacementBias', 'float' );
  26359. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26360. }
  26361. if ( object.isBatchedMesh ) {
  26362. batch( object ).append();
  26363. }
  26364. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26365. instance( object ).append();
  26366. }
  26367. if ( this.positionNode !== null ) {
  26368. positionLocal.assign( this.positionNode );
  26369. }
  26370. const mvp = modelViewProjection();
  26371. builder.context.vertex = builder.removeStack();
  26372. builder.context.mvp = mvp;
  26373. return mvp;
  26374. }
  26375. setupDiffuseColor( { object, geometry } ) {
  26376. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26377. // VERTEX COLORS
  26378. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26379. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26380. }
  26381. // Instanced colors
  26382. if ( object.instanceColor ) {
  26383. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26384. colorNode = instanceColor.mul( colorNode );
  26385. }
  26386. if ( object.isBatchedMesh && object._colorsTexture ) {
  26387. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  26388. colorNode = batchColor.mul( colorNode );
  26389. }
  26390. // COLOR
  26391. diffuseColor.assign( colorNode );
  26392. // OPACITY
  26393. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26394. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26395. // ALPHA TEST
  26396. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26397. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26398. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26399. }
  26400. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26401. diffuseColor.a.assign( 1.0 );
  26402. }
  26403. }
  26404. setupVariants( /*builder*/ ) {
  26405. // Interface function.
  26406. }
  26407. setupOutgoingLight() {
  26408. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  26409. }
  26410. setupNormal() {
  26411. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26412. }
  26413. setupEnvironment( /*builder*/ ) {
  26414. let node = null;
  26415. if ( this.envNode ) {
  26416. node = this.envNode;
  26417. } else if ( this.envMap ) {
  26418. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  26419. }
  26420. return node;
  26421. }
  26422. setupLightMap( builder ) {
  26423. let node = null;
  26424. if ( builder.material.lightMap ) {
  26425. node = new IrradianceNode( materialLightMap );
  26426. }
  26427. return node;
  26428. }
  26429. setupLights( builder ) {
  26430. const materialLightsNode = [];
  26431. //
  26432. const envNode = this.setupEnvironment( builder );
  26433. if ( envNode && envNode.isLightingNode ) {
  26434. materialLightsNode.push( envNode );
  26435. }
  26436. const lightMapNode = this.setupLightMap( builder );
  26437. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26438. materialLightsNode.push( lightMapNode );
  26439. }
  26440. if ( this.aoNode !== null || builder.material.aoMap ) {
  26441. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26442. materialLightsNode.push( new AONode( aoNode ) );
  26443. }
  26444. let lightsN = this.lightsNode || builder.lightsNode;
  26445. if ( materialLightsNode.length > 0 ) {
  26446. lightsN = lights( [ ...lightsN.getLights(), ...materialLightsNode ] );
  26447. }
  26448. return lightsN;
  26449. }
  26450. setupLightingModel( /*builder*/ ) {
  26451. // Interface function.
  26452. }
  26453. setupLighting( builder ) {
  26454. const { material } = builder;
  26455. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26456. // OUTGOING LIGHT
  26457. const lights = this.lights === true || this.lightsNode !== null;
  26458. const lightsNode = lights ? this.setupLights( builder ) : null;
  26459. let outgoingLightNode = this.setupOutgoingLight( builder );
  26460. if ( lightsNode && lightsNode.getScope().getLights().length > 0 ) {
  26461. const lightingModel = this.setupLightingModel( builder );
  26462. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26463. } else if ( backdropNode !== null ) {
  26464. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26465. }
  26466. // EMISSIVE
  26467. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26468. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26469. outgoingLightNode = outgoingLightNode.add( emissive );
  26470. }
  26471. return outgoingLightNode;
  26472. }
  26473. setupOutput( builder, outputNode ) {
  26474. // FOG
  26475. if ( this.fog === true ) {
  26476. const fogNode = builder.fogNode;
  26477. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26478. }
  26479. return outputNode;
  26480. }
  26481. setDefaultValues( material ) {
  26482. // This approach is to reuse the native refreshUniforms*
  26483. // and turn available the use of features like transmission and environment in core
  26484. for ( const property in material ) {
  26485. const value = material[ property ];
  26486. if ( this[ property ] === undefined ) {
  26487. this[ property ] = value;
  26488. if ( value && value.clone ) this[ property ] = value.clone();
  26489. }
  26490. }
  26491. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26492. for ( const key in descriptors ) {
  26493. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26494. descriptors[ key ].get !== undefined ) {
  26495. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26496. }
  26497. }
  26498. }
  26499. toJSON( meta ) {
  26500. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26501. if ( isRoot ) {
  26502. meta = {
  26503. textures: {},
  26504. images: {},
  26505. nodes: {}
  26506. };
  26507. }
  26508. const data = Material.prototype.toJSON.call( this, meta );
  26509. const nodeChildren = getNodeChildren( this );
  26510. data.inputNodes = {};
  26511. for ( const { property, childNode } of nodeChildren ) {
  26512. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26513. }
  26514. // TODO: Copied from Object3D.toJSON
  26515. function extractFromCache( cache ) {
  26516. const values = [];
  26517. for ( const key in cache ) {
  26518. const data = cache[ key ];
  26519. delete data.metadata;
  26520. values.push( data );
  26521. }
  26522. return values;
  26523. }
  26524. if ( isRoot ) {
  26525. const textures = extractFromCache( meta.textures );
  26526. const images = extractFromCache( meta.images );
  26527. const nodes = extractFromCache( meta.nodes );
  26528. if ( textures.length > 0 ) data.textures = textures;
  26529. if ( images.length > 0 ) data.images = images;
  26530. if ( nodes.length > 0 ) data.nodes = nodes;
  26531. }
  26532. return data;
  26533. }
  26534. copy( source ) {
  26535. this.lightsNode = source.lightsNode;
  26536. this.envNode = source.envNode;
  26537. this.colorNode = source.colorNode;
  26538. this.normalNode = source.normalNode;
  26539. this.opacityNode = source.opacityNode;
  26540. this.backdropNode = source.backdropNode;
  26541. this.backdropAlphaNode = source.backdropAlphaNode;
  26542. this.alphaTestNode = source.alphaTestNode;
  26543. this.positionNode = source.positionNode;
  26544. this.depthNode = source.depthNode;
  26545. this.shadowNode = source.shadowNode;
  26546. this.shadowPositionNode = source.shadowPositionNode;
  26547. this.outputNode = source.outputNode;
  26548. this.mrtNode = source.mrtNode;
  26549. this.fragmentNode = source.fragmentNode;
  26550. this.vertexNode = source.vertexNode;
  26551. return super.copy( source );
  26552. }
  26553. }
  26554. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  26555. class InstancedPointsNodeMaterial extends NodeMaterial {
  26556. static get type() {
  26557. return 'InstancedPointsNodeMaterial';
  26558. }
  26559. constructor( params = {} ) {
  26560. super();
  26561. this.lights = false;
  26562. this.useAlphaToCoverage = true;
  26563. this.useColor = params.vertexColors;
  26564. this.pointWidth = 1;
  26565. this.pointColorNode = null;
  26566. this.pointWidthNode = null;
  26567. this.setDefaultValues( _defaultValues$e );
  26568. this.setValues( params );
  26569. }
  26570. setup( builder ) {
  26571. this.setupShaders( builder );
  26572. super.setup( builder );
  26573. }
  26574. setupShaders( { renderer } ) {
  26575. const useAlphaToCoverage = this.alphaToCoverage;
  26576. const useColor = this.useColor;
  26577. this.vertexNode = Fn( () => {
  26578. const instancePosition = attribute( 'instancePosition' ).xyz;
  26579. // camera space
  26580. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  26581. const aspect = viewport.z.div( viewport.w );
  26582. // clip space
  26583. const clipPos = cameraProjectionMatrix.mul( mvPos );
  26584. // offset in ndc space
  26585. const offset = positionGeometry.xy.toVar();
  26586. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  26587. offset.assign( offset.div( viewport.z ) );
  26588. offset.y.assign( offset.y.mul( aspect ) );
  26589. // back to clip space
  26590. offset.assign( offset.mul( clipPos.w ) );
  26591. //clipPos.xy += offset;
  26592. clipPos.addAssign( vec4( offset, 0, 0 ) );
  26593. return clipPos;
  26594. } )();
  26595. this.fragmentNode = Fn( () => {
  26596. const alpha = float( 1 ).toVar();
  26597. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  26598. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  26599. const dlen = float( len2.fwidth() ).toVar();
  26600. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26601. } else {
  26602. len2.greaterThan( 1.0 ).discard();
  26603. }
  26604. let pointColorNode;
  26605. if ( this.pointColorNode ) {
  26606. pointColorNode = this.pointColorNode;
  26607. } else {
  26608. if ( useColor ) {
  26609. const instanceColor = attribute( 'instanceColor' );
  26610. pointColorNode = instanceColor.mul( materialColor );
  26611. } else {
  26612. pointColorNode = materialColor;
  26613. }
  26614. }
  26615. alpha.mulAssign( materialOpacity );
  26616. return vec4( pointColorNode, alpha );
  26617. } )();
  26618. }
  26619. get alphaToCoverage() {
  26620. return this.useAlphaToCoverage;
  26621. }
  26622. set alphaToCoverage( value ) {
  26623. if ( this.useAlphaToCoverage !== value ) {
  26624. this.useAlphaToCoverage = value;
  26625. this.needsUpdate = true;
  26626. }
  26627. }
  26628. }
  26629. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  26630. class LineBasicNodeMaterial extends NodeMaterial {
  26631. static get type() {
  26632. return 'LineBasicNodeMaterial';
  26633. }
  26634. constructor( parameters ) {
  26635. super();
  26636. this.isLineBasicNodeMaterial = true;
  26637. this.lights = false;
  26638. this.setDefaultValues( _defaultValues$d );
  26639. this.setValues( parameters );
  26640. }
  26641. }
  26642. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  26643. class LineDashedNodeMaterial extends NodeMaterial {
  26644. static get type() {
  26645. return 'LineDashedNodeMaterial';
  26646. }
  26647. constructor( parameters ) {
  26648. super();
  26649. this.isLineDashedNodeMaterial = true;
  26650. this.lights = false;
  26651. this.setDefaultValues( _defaultValues$c );
  26652. this.offsetNode = null;
  26653. this.dashScaleNode = null;
  26654. this.dashSizeNode = null;
  26655. this.gapSizeNode = null;
  26656. this.setValues( parameters );
  26657. }
  26658. setupVariants() {
  26659. const offsetNode = this.offsetNode;
  26660. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  26661. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  26662. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  26663. dashSize.assign( dashSizeNode );
  26664. gapSize.assign( gapSizeNode );
  26665. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  26666. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  26667. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  26668. }
  26669. }
  26670. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  26671. class Line2NodeMaterial extends NodeMaterial {
  26672. static get type() {
  26673. return 'Line2NodeMaterial';
  26674. }
  26675. constructor( params = {} ) {
  26676. super();
  26677. this.lights = false;
  26678. this.setDefaultValues( _defaultValues$b );
  26679. this.useAlphaToCoverage = true;
  26680. this.useColor = params.vertexColors;
  26681. this.useDash = params.dashed;
  26682. this.useWorldUnits = false;
  26683. this.dashOffset = 0;
  26684. this.lineWidth = 1;
  26685. this.lineColorNode = null;
  26686. this.offsetNode = null;
  26687. this.dashScaleNode = null;
  26688. this.dashSizeNode = null;
  26689. this.gapSizeNode = null;
  26690. this.setValues( params );
  26691. }
  26692. setup( builder ) {
  26693. this.setupShaders( builder );
  26694. super.setup( builder );
  26695. }
  26696. setupShaders( { renderer } ) {
  26697. const useAlphaToCoverage = this.alphaToCoverage;
  26698. const useColor = this.useColor;
  26699. const useDash = this.dashed;
  26700. const useWorldUnits = this.worldUnits;
  26701. const trimSegment = Fn( ( { start, end } ) => {
  26702. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  26703. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  26704. const nearEstimate = b.mul( - 0.5 ).div( a );
  26705. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  26706. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  26707. } ).setLayout( {
  26708. name: 'trimSegment',
  26709. type: 'vec4',
  26710. inputs: [
  26711. { name: 'start', type: 'vec4' },
  26712. { name: 'end', type: 'vec4' }
  26713. ]
  26714. } );
  26715. this.vertexNode = Fn( () => {
  26716. const instanceStart = attribute( 'instanceStart' );
  26717. const instanceEnd = attribute( 'instanceEnd' );
  26718. // camera space
  26719. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  26720. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  26721. if ( useWorldUnits ) {
  26722. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  26723. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  26724. }
  26725. const aspect = viewport.z.div( viewport.w );
  26726. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  26727. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  26728. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  26729. // perhaps there is a more elegant solution -- WestLangley
  26730. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  26731. If( perspective, () => {
  26732. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  26733. end.assign( trimSegment( { start: start, end: end } ) );
  26734. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  26735. start.assign( trimSegment( { start: end, end: start } ) );
  26736. } );
  26737. } );
  26738. // clip space
  26739. const clipStart = cameraProjectionMatrix.mul( start );
  26740. const clipEnd = cameraProjectionMatrix.mul( end );
  26741. // ndc space
  26742. const ndcStart = clipStart.xyz.div( clipStart.w );
  26743. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  26744. // direction
  26745. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  26746. // account for clip-space aspect ratio
  26747. dir.x.assign( dir.x.mul( aspect ) );
  26748. dir.assign( dir.normalize() );
  26749. const clip = vec4().toVar();
  26750. if ( useWorldUnits ) {
  26751. // get the offset direction as perpendicular to the view vector
  26752. const worldDir = end.xyz.sub( start.xyz ).normalize();
  26753. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  26754. const worldUp = worldDir.cross( tmpFwd ).normalize();
  26755. const worldFwd = worldDir.cross( worldUp );
  26756. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  26757. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  26758. // height offset
  26759. const hw = materialLineWidth.mul( 0.5 );
  26760. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  26761. // don't extend the line if we're rendering dashes because we
  26762. // won't be rendering the endcaps
  26763. if ( ! useDash ) {
  26764. // cap extension
  26765. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  26766. // add width to the box
  26767. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  26768. // endcaps
  26769. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  26770. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  26771. } );
  26772. }
  26773. // project the worldpos
  26774. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  26775. // shift the depth of the projected points so the line
  26776. // segments overlap neatly
  26777. const clipPose = vec3().toVar();
  26778. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  26779. clip.z.assign( clipPose.z.mul( clip.w ) );
  26780. } else {
  26781. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  26782. // undo aspect ratio adjustment
  26783. dir.x.assign( dir.x.div( aspect ) );
  26784. offset.x.assign( offset.x.div( aspect ) );
  26785. // sign flip
  26786. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  26787. // endcaps
  26788. If( positionGeometry.y.lessThan( 0.0 ), () => {
  26789. offset.assign( offset.sub( dir ) );
  26790. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  26791. offset.assign( offset.add( dir ) );
  26792. } );
  26793. // adjust for linewidth
  26794. offset.assign( offset.mul( materialLineWidth ) );
  26795. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  26796. offset.assign( offset.div( viewport.w ) );
  26797. // select end
  26798. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  26799. // back to clip space
  26800. offset.assign( offset.mul( clip.w ) );
  26801. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  26802. }
  26803. return clip;
  26804. } )();
  26805. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  26806. const p13 = p1.sub( p3 );
  26807. const p43 = p4.sub( p3 );
  26808. const p21 = p2.sub( p1 );
  26809. const d1343 = p13.dot( p43 );
  26810. const d4321 = p43.dot( p21 );
  26811. const d1321 = p13.dot( p21 );
  26812. const d4343 = p43.dot( p43 );
  26813. const d2121 = p21.dot( p21 );
  26814. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  26815. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  26816. const mua = numer.div( denom ).clamp();
  26817. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  26818. return vec2( mua, mub );
  26819. } );
  26820. this.fragmentNode = Fn( () => {
  26821. const vUv = uv();
  26822. if ( useDash ) {
  26823. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  26824. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  26825. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  26826. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  26827. dashSize.assign( dashSizeNode );
  26828. gapSize.assign( gapSizeNode );
  26829. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  26830. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  26831. const lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  26832. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  26833. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  26834. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  26835. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  26836. }
  26837. const alpha = float( 1 ).toVar( 'alpha' );
  26838. if ( useWorldUnits ) {
  26839. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  26840. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  26841. // Find the closest points on the view ray and the line segment
  26842. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  26843. const lineDir = worldEnd.sub( worldStart );
  26844. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  26845. const p1 = worldStart.add( lineDir.mul( params.x ) );
  26846. const p2 = rayEnd.mul( params.y );
  26847. const delta = p1.sub( p2 );
  26848. const len = delta.length();
  26849. const norm = len.div( materialLineWidth );
  26850. if ( ! useDash ) {
  26851. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  26852. const dnorm = norm.fwidth();
  26853. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  26854. } else {
  26855. norm.greaterThan( 0.5 ).discard();
  26856. }
  26857. }
  26858. } else {
  26859. // round endcaps
  26860. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  26861. const a = vUv.x;
  26862. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  26863. const len2 = a.mul( a ).add( b.mul( b ) );
  26864. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  26865. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  26866. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26867. } );
  26868. } else {
  26869. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  26870. const a = vUv.x;
  26871. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  26872. const len2 = a.mul( a ).add( b.mul( b ) );
  26873. len2.greaterThan( 1.0 ).discard();
  26874. } );
  26875. }
  26876. }
  26877. let lineColorNode;
  26878. if ( this.lineColorNode ) {
  26879. lineColorNode = this.lineColorNode;
  26880. } else {
  26881. if ( useColor ) {
  26882. const instanceColorStart = attribute( 'instanceColorStart' );
  26883. const instanceColorEnd = attribute( 'instanceColorEnd' );
  26884. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  26885. lineColorNode = instanceColor.mul( materialColor );
  26886. } else {
  26887. lineColorNode = materialColor;
  26888. }
  26889. }
  26890. return vec4( lineColorNode, alpha );
  26891. } )();
  26892. }
  26893. get worldUnits() {
  26894. return this.useWorldUnits;
  26895. }
  26896. set worldUnits( value ) {
  26897. if ( this.useWorldUnits !== value ) {
  26898. this.useWorldUnits = value;
  26899. this.needsUpdate = true;
  26900. }
  26901. }
  26902. get dashed() {
  26903. return this.useDash;
  26904. }
  26905. set dashed( value ) {
  26906. if ( this.useDash !== value ) {
  26907. this.useDash = value;
  26908. this.needsUpdate = true;
  26909. }
  26910. }
  26911. get alphaToCoverage() {
  26912. return this.useAlphaToCoverage;
  26913. }
  26914. set alphaToCoverage( value ) {
  26915. if ( this.useAlphaToCoverage !== value ) {
  26916. this.useAlphaToCoverage = value;
  26917. this.needsUpdate = true;
  26918. }
  26919. }
  26920. }
  26921. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  26922. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  26923. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  26924. class MeshNormalNodeMaterial extends NodeMaterial {
  26925. static get type() {
  26926. return 'MeshNormalNodeMaterial';
  26927. }
  26928. constructor( parameters ) {
  26929. super();
  26930. this.lights = false;
  26931. this.isMeshNormalNodeMaterial = true;
  26932. this.setDefaultValues( _defaultValues$a );
  26933. this.setValues( parameters );
  26934. }
  26935. setupDiffuseColor() {
  26936. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26937. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  26938. }
  26939. }
  26940. class EquirectUVNode extends TempNode {
  26941. static get type() {
  26942. return 'EquirectUVNode';
  26943. }
  26944. constructor( dirNode = positionWorldDirection ) {
  26945. super( 'vec2' );
  26946. this.dirNode = dirNode;
  26947. }
  26948. setup() {
  26949. const dir = this.dirNode;
  26950. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  26951. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  26952. return vec2( u, v );
  26953. }
  26954. }
  26955. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  26956. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  26957. class CubeRenderTarget extends WebGLCubeRenderTarget {
  26958. constructor( size = 1, options = {} ) {
  26959. super( size, options );
  26960. this.isCubeRenderTarget = true;
  26961. }
  26962. fromEquirectangularTexture( renderer, texture$1 ) {
  26963. const currentMinFilter = texture$1.minFilter;
  26964. const currentGenerateMipmaps = texture$1.generateMipmaps;
  26965. texture$1.generateMipmaps = true;
  26966. this.texture.type = texture$1.type;
  26967. this.texture.colorSpace = texture$1.colorSpace;
  26968. this.texture.generateMipmaps = texture$1.generateMipmaps;
  26969. this.texture.minFilter = texture$1.minFilter;
  26970. this.texture.magFilter = texture$1.magFilter;
  26971. const geometry = new BoxGeometry( 5, 5, 5 );
  26972. const uvNode = equirectUV( positionWorldDirection );
  26973. const material = new NodeMaterial();
  26974. material.colorNode = texture( texture$1, uvNode, 0 );
  26975. material.side = BackSide;
  26976. material.blending = NoBlending;
  26977. const mesh = new Mesh( geometry, material );
  26978. const scene = new Scene();
  26979. scene.add( mesh );
  26980. // Avoid blurred poles
  26981. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  26982. const camera = new CubeCamera( 1, 10, this );
  26983. const currentMRT = renderer.getMRT();
  26984. renderer.setMRT( null );
  26985. camera.update( renderer, scene );
  26986. renderer.setMRT( currentMRT );
  26987. texture$1.minFilter = currentMinFilter;
  26988. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  26989. mesh.geometry.dispose();
  26990. mesh.material.dispose();
  26991. return this;
  26992. }
  26993. }
  26994. const _cache$1 = new WeakMap();
  26995. class CubeMapNode extends TempNode {
  26996. static get type() {
  26997. return 'CubeMapNode';
  26998. }
  26999. constructor( envNode ) {
  27000. super( 'vec3' );
  27001. this.envNode = envNode;
  27002. this._cubeTexture = null;
  27003. this._cubeTextureNode = cubeTexture();
  27004. const defaultTexture = new CubeTexture();
  27005. defaultTexture.isRenderTargetTexture = true;
  27006. this._defaultTexture = defaultTexture;
  27007. this.updateBeforeType = NodeUpdateType.RENDER;
  27008. }
  27009. updateBefore( frame ) {
  27010. const { renderer, material } = frame;
  27011. const envNode = this.envNode;
  27012. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  27013. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  27014. if ( texture && texture.isTexture ) {
  27015. const mapping = texture.mapping;
  27016. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  27017. // check for converted cubemap map
  27018. if ( _cache$1.has( texture ) ) {
  27019. const cubeMap = _cache$1.get( texture );
  27020. mapTextureMapping( cubeMap, texture.mapping );
  27021. this._cubeTexture = cubeMap;
  27022. } else {
  27023. // create cube map from equirectangular map
  27024. const image = texture.image;
  27025. if ( isEquirectangularMapReady$1( image ) ) {
  27026. const renderTarget = new CubeRenderTarget( image.height );
  27027. renderTarget.fromEquirectangularTexture( renderer, texture );
  27028. mapTextureMapping( renderTarget.texture, texture.mapping );
  27029. this._cubeTexture = renderTarget.texture;
  27030. _cache$1.set( texture, renderTarget.texture );
  27031. texture.addEventListener( 'dispose', onTextureDispose );
  27032. } else {
  27033. // default cube texture as fallback when equirectangular texture is not yet loaded
  27034. this._cubeTexture = this._defaultTexture;
  27035. }
  27036. }
  27037. //
  27038. this._cubeTextureNode.value = this._cubeTexture;
  27039. } else {
  27040. // envNode already refers to a cube map
  27041. this._cubeTextureNode = this.envNode;
  27042. }
  27043. }
  27044. }
  27045. }
  27046. setup( builder ) {
  27047. this.updateBefore( builder );
  27048. return this._cubeTextureNode;
  27049. }
  27050. }
  27051. function isEquirectangularMapReady$1( image ) {
  27052. if ( image === null || image === undefined ) return false;
  27053. return image.height > 0;
  27054. }
  27055. function onTextureDispose( event ) {
  27056. const texture = event.target;
  27057. texture.removeEventListener( 'dispose', onTextureDispose );
  27058. const renderTarget = _cache$1.get( texture );
  27059. if ( renderTarget !== undefined ) {
  27060. _cache$1.delete( texture );
  27061. renderTarget.dispose();
  27062. }
  27063. }
  27064. function mapTextureMapping( texture, mapping ) {
  27065. if ( mapping === EquirectangularReflectionMapping ) {
  27066. texture.mapping = CubeReflectionMapping;
  27067. } else if ( mapping === EquirectangularRefractionMapping ) {
  27068. texture.mapping = CubeRefractionMapping;
  27069. }
  27070. }
  27071. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  27072. class BasicEnvironmentNode extends LightingNode {
  27073. static get type() {
  27074. return 'BasicEnvironmentNode';
  27075. }
  27076. constructor( envNode = null ) {
  27077. super();
  27078. this.envNode = envNode;
  27079. }
  27080. setup( builder ) {
  27081. // environment property is used in the finish() method of BasicLightingModel
  27082. builder.context.environment = cubeMapNode( this.envNode );
  27083. }
  27084. }
  27085. class BasicLightMapNode extends LightingNode {
  27086. static get type() {
  27087. return 'BasicLightMapNode';
  27088. }
  27089. constructor( lightMapNode = null ) {
  27090. super();
  27091. this.lightMapNode = lightMapNode;
  27092. }
  27093. setup( builder ) {
  27094. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  27095. const RECIPROCAL_PI = float( 1 / Math.PI );
  27096. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  27097. }
  27098. }
  27099. class LightingModel {
  27100. start( /*input, stack, builder*/ ) { }
  27101. finish( /*input, stack, builder*/ ) { }
  27102. direct( /*input, stack, builder*/ ) { }
  27103. directRectArea( /*input, stack, builder*/ ) {}
  27104. indirect( /*input, stack, builder*/ ) { }
  27105. ambientOcclusion( /*input, stack, builder*/ ) { }
  27106. }
  27107. class BasicLightingModel extends LightingModel {
  27108. constructor() {
  27109. super();
  27110. }
  27111. indirect( context, stack, builder ) {
  27112. const ambientOcclusion = context.ambientOcclusion;
  27113. const reflectedLight = context.reflectedLight;
  27114. const irradianceLightMap = builder.context.irradianceLightMap;
  27115. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  27116. // accumulation (baked indirect lighting only)
  27117. if ( irradianceLightMap ) {
  27118. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  27119. } else {
  27120. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  27121. }
  27122. // modulation
  27123. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27124. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  27125. }
  27126. finish( context, stack, builder ) {
  27127. const material = builder.material;
  27128. const outgoingLight = context.outgoingLight;
  27129. const envNode = builder.context.environment;
  27130. if ( envNode ) {
  27131. switch ( material.combine ) {
  27132. case MultiplyOperation:
  27133. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  27134. break;
  27135. case MixOperation:
  27136. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  27137. break;
  27138. case AddOperation:
  27139. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  27140. break;
  27141. default:
  27142. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  27143. break;
  27144. }
  27145. }
  27146. }
  27147. }
  27148. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  27149. class MeshBasicNodeMaterial extends NodeMaterial {
  27150. static get type() {
  27151. return 'MeshBasicNodeMaterial';
  27152. }
  27153. constructor( parameters ) {
  27154. super();
  27155. this.isMeshBasicNodeMaterial = true;
  27156. this.lights = true;
  27157. this.setDefaultValues( _defaultValues$9 );
  27158. this.setValues( parameters );
  27159. }
  27160. setupNormal() {
  27161. return normalView; // see #28839
  27162. }
  27163. setupEnvironment( builder ) {
  27164. const envNode = super.setupEnvironment( builder );
  27165. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27166. }
  27167. setupLightMap( builder ) {
  27168. let node = null;
  27169. if ( builder.material.lightMap ) {
  27170. node = new BasicLightMapNode( materialLightMap );
  27171. }
  27172. return node;
  27173. }
  27174. setupOutgoingLight() {
  27175. return diffuseColor.rgb;
  27176. }
  27177. setupLightingModel() {
  27178. return new BasicLightingModel();
  27179. }
  27180. }
  27181. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  27182. // Original approximation by Christophe Schlick '94
  27183. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  27184. // Optimized variant (presented by Epic at SIGGRAPH '13)
  27185. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  27186. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  27187. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  27188. } ); // validated
  27189. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  27190. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  27191. } ); // validated
  27192. const G_BlinnPhong_Implicit = () => float( 0.25 );
  27193. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  27194. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  27195. } );
  27196. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27197. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27198. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27199. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27200. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  27201. const G = G_BlinnPhong_Implicit();
  27202. const D = D_BlinnPhong( { dotNH } );
  27203. return F.mul( G ).mul( D );
  27204. } );
  27205. class PhongLightingModel extends BasicLightingModel {
  27206. constructor( specular = true ) {
  27207. super();
  27208. this.specular = specular;
  27209. }
  27210. direct( { lightDirection, lightColor, reflectedLight } ) {
  27211. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27212. const irradiance = dotNL.mul( lightColor );
  27213. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  27214. if ( this.specular === true ) {
  27215. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  27216. }
  27217. }
  27218. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  27219. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  27220. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27221. }
  27222. }
  27223. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  27224. class MeshLambertNodeMaterial extends NodeMaterial {
  27225. static get type() {
  27226. return 'MeshLambertNodeMaterial';
  27227. }
  27228. constructor( parameters ) {
  27229. super();
  27230. this.isMeshLambertNodeMaterial = true;
  27231. this.lights = true;
  27232. this.setDefaultValues( _defaultValues$8 );
  27233. this.setValues( parameters );
  27234. }
  27235. setupEnvironment( builder ) {
  27236. const envNode = super.setupEnvironment( builder );
  27237. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27238. }
  27239. setupLightingModel( /*builder*/ ) {
  27240. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  27241. }
  27242. }
  27243. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  27244. class MeshPhongNodeMaterial extends NodeMaterial {
  27245. static get type() {
  27246. return 'MeshPhongNodeMaterial';
  27247. }
  27248. constructor( parameters ) {
  27249. super();
  27250. this.isMeshPhongNodeMaterial = true;
  27251. this.lights = true;
  27252. this.shininessNode = null;
  27253. this.specularNode = null;
  27254. this.setDefaultValues( _defaultValues$7 );
  27255. this.setValues( parameters );
  27256. }
  27257. setupEnvironment( builder ) {
  27258. const envNode = super.setupEnvironment( builder );
  27259. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27260. }
  27261. setupLightingModel( /*builder*/ ) {
  27262. return new PhongLightingModel();
  27263. }
  27264. setupVariants() {
  27265. // SHININESS
  27266. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  27267. shininess.assign( shininessNode );
  27268. // SPECULAR COLOR
  27269. const specularNode = this.specularNode || materialSpecular;
  27270. specularColor.assign( specularNode );
  27271. }
  27272. copy( source ) {
  27273. this.shininessNode = source.shininessNode;
  27274. this.specularNode = source.specularNode;
  27275. return super.copy( source );
  27276. }
  27277. }
  27278. const getGeometryRoughness = /*@__PURE__*/ Fn( () => {
  27279. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  27280. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  27281. return geometryRoughness;
  27282. } );
  27283. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  27284. const { roughness } = inputs;
  27285. const geometryRoughness = getGeometryRoughness();
  27286. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  27287. roughnessFactor = roughnessFactor.add( geometryRoughness );
  27288. roughnessFactor = roughnessFactor.min( 1.0 );
  27289. return roughnessFactor;
  27290. } );
  27291. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  27292. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27293. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  27294. const a2 = alpha.pow2();
  27295. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  27296. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  27297. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  27298. } ).setLayout( {
  27299. name: 'V_GGX_SmithCorrelated',
  27300. type: 'float',
  27301. inputs: [
  27302. { name: 'alpha', type: 'float' },
  27303. { name: 'dotNL', type: 'float' },
  27304. { name: 'dotNV', type: 'float' }
  27305. ]
  27306. } ); // validated
  27307. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27308. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  27309. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  27310. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  27311. const v = div( 0.5, gv.add( gl ) );
  27312. return v.saturate();
  27313. } ).setLayout( {
  27314. name: 'V_GGX_SmithCorrelated_Anisotropic',
  27315. type: 'float',
  27316. inputs: [
  27317. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27318. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27319. { name: 'dotTV', type: 'float', qualifier: 'in' },
  27320. { name: 'dotBV', type: 'float', qualifier: 'in' },
  27321. { name: 'dotTL', type: 'float', qualifier: 'in' },
  27322. { name: 'dotBL', type: 'float', qualifier: 'in' },
  27323. { name: 'dotNV', type: 'float', qualifier: 'in' },
  27324. { name: 'dotNL', type: 'float', qualifier: 'in' }
  27325. ]
  27326. } );
  27327. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  27328. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  27329. // alpha is "roughness squared" in Disney’s reparameterization
  27330. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  27331. const a2 = alpha.pow2();
  27332. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  27333. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  27334. } ).setLayout( {
  27335. name: 'D_GGX',
  27336. type: 'float',
  27337. inputs: [
  27338. { name: 'alpha', type: 'float' },
  27339. { name: 'dotNH', type: 'float' }
  27340. ]
  27341. } ); // validated
  27342. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  27343. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27344. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  27345. const a2 = alphaT.mul( alphaB );
  27346. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  27347. const v2 = v.dot( v );
  27348. const w2 = a2.div( v2 );
  27349. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  27350. } ).setLayout( {
  27351. name: 'D_GGX_Anisotropic',
  27352. type: 'float',
  27353. inputs: [
  27354. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27355. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27356. { name: 'dotNH', type: 'float', qualifier: 'in' },
  27357. { name: 'dotTH', type: 'float', qualifier: 'in' },
  27358. { name: 'dotBH', type: 'float', qualifier: 'in' }
  27359. ]
  27360. } );
  27361. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  27362. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  27363. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  27364. const normalView = inputs.normalView || transformedNormalView;
  27365. const alpha = roughness.pow2(); // UE4's roughness
  27366. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27367. const dotNL = normalView.dot( lightDirection ).clamp();
  27368. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27369. const dotNH = normalView.dot( halfDir ).clamp();
  27370. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27371. let F = F_Schlick( { f0, f90, dotVH } );
  27372. let V, D;
  27373. if ( defined( USE_IRIDESCENCE ) ) {
  27374. F = iridescence.mix( F, f );
  27375. }
  27376. if ( defined( USE_ANISOTROPY ) ) {
  27377. const dotTL = anisotropyT.dot( lightDirection );
  27378. const dotTV = anisotropyT.dot( positionViewDirection );
  27379. const dotTH = anisotropyT.dot( halfDir );
  27380. const dotBL = anisotropyB.dot( lightDirection );
  27381. const dotBV = anisotropyB.dot( positionViewDirection );
  27382. const dotBH = anisotropyB.dot( halfDir );
  27383. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  27384. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  27385. } else {
  27386. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  27387. D = D_GGX( { alpha, dotNH } );
  27388. }
  27389. return F.mul( V ).mul( D );
  27390. } ); // validated
  27391. // Analytical approximation of the DFG LUT, one half of the
  27392. // split-sum approximation used in indirect specular lighting.
  27393. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  27394. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  27395. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  27396. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  27397. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  27398. const r = roughness.mul( c0 ).add( c1 );
  27399. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  27400. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  27401. return fab;
  27402. } ).setLayout( {
  27403. name: 'DFGApprox',
  27404. type: 'vec2',
  27405. inputs: [
  27406. { name: 'roughness', type: 'float' },
  27407. { name: 'dotNV', type: 'vec3' }
  27408. ]
  27409. } );
  27410. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  27411. const { dotNV, specularColor, specularF90, roughness } = inputs;
  27412. const fab = DFGApprox( { dotNV, roughness } );
  27413. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  27414. } );
  27415. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  27416. const x = dotVH.oneMinus().saturate();
  27417. const x2 = x.mul( x );
  27418. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  27419. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  27420. } ).setLayout( {
  27421. name: 'Schlick_to_F0',
  27422. type: 'vec3',
  27423. inputs: [
  27424. { name: 'f', type: 'vec3' },
  27425. { name: 'f90', type: 'float' },
  27426. { name: 'dotVH', type: 'float' }
  27427. ]
  27428. } );
  27429. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27430. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  27431. const alpha = roughness.pow2();
  27432. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  27433. const invAlpha = float( 1.0 ).div( alpha );
  27434. const cos2h = dotNH.pow2();
  27435. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  27436. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  27437. } ).setLayout( {
  27438. name: 'D_Charlie',
  27439. type: 'float',
  27440. inputs: [
  27441. { name: 'roughness', type: 'float' },
  27442. { name: 'dotNH', type: 'float' }
  27443. ]
  27444. } );
  27445. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27446. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  27447. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  27448. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  27449. } ).setLayout( {
  27450. name: 'V_Neubelt',
  27451. type: 'float',
  27452. inputs: [
  27453. { name: 'dotNV', type: 'float' },
  27454. { name: 'dotNL', type: 'float' }
  27455. ]
  27456. } );
  27457. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27458. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27459. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27460. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  27461. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27462. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  27463. const V = V_Neubelt( { dotNV, dotNL } );
  27464. return sheen.mul( D ).mul( V );
  27465. } );
  27466. // Rect Area Light
  27467. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  27468. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  27469. // code: https://github.com/selfshadow/ltc_code/
  27470. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  27471. const LUT_SIZE = 64.0;
  27472. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  27473. const LUT_BIAS = 0.5 / LUT_SIZE;
  27474. const dotNV = N.dot( V ).saturate();
  27475. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  27476. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  27477. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  27478. return uv;
  27479. } ).setLayout( {
  27480. name: 'LTC_Uv',
  27481. type: 'vec2',
  27482. inputs: [
  27483. { name: 'N', type: 'vec3' },
  27484. { name: 'V', type: 'vec3' },
  27485. { name: 'roughness', type: 'float' }
  27486. ]
  27487. } );
  27488. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  27489. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  27490. // An approximation of the form factor of a horizon-clipped rectangle.
  27491. const l = f.length();
  27492. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  27493. } ).setLayout( {
  27494. name: 'LTC_ClippedSphereFormFactor',
  27495. type: 'float',
  27496. inputs: [
  27497. { name: 'f', type: 'vec3' }
  27498. ]
  27499. } );
  27500. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  27501. const x = v1.dot( v2 );
  27502. const y = x.abs().toVar();
  27503. // rational polynomial approximation to theta / sin( theta ) / 2PI
  27504. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  27505. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  27506. const v = a.div( b );
  27507. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  27508. return v1.cross( v2 ).mul( theta_sintheta );
  27509. } ).setLayout( {
  27510. name: 'LTC_EdgeVectorFormFactor',
  27511. type: 'vec3',
  27512. inputs: [
  27513. { name: 'v1', type: 'vec3' },
  27514. { name: 'v2', type: 'vec3' }
  27515. ]
  27516. } );
  27517. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  27518. // bail if point is on back side of plane of light
  27519. // assumes ccw winding order of light vertices
  27520. const v1 = p1.sub( p0 ).toVar();
  27521. const v2 = p3.sub( p0 ).toVar();
  27522. const lightNormal = v1.cross( v2 );
  27523. const result = vec3().toVar();
  27524. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  27525. // construct orthonormal basis around N
  27526. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  27527. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  27528. // compute transform
  27529. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  27530. // transform rect
  27531. // & project rect onto sphere
  27532. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  27533. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  27534. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  27535. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  27536. // calculate vector form factor
  27537. const vectorFormFactor = vec3( 0 ).toVar();
  27538. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  27539. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  27540. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  27541. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  27542. // adjust for horizon clipping
  27543. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  27544. } );
  27545. return result;
  27546. } ).setLayout( {
  27547. name: 'LTC_Evaluate',
  27548. type: 'vec3',
  27549. inputs: [
  27550. { name: 'N', type: 'vec3' },
  27551. { name: 'V', type: 'vec3' },
  27552. { name: 'P', type: 'vec3' },
  27553. { name: 'mInv', type: 'mat3' },
  27554. { name: 'p0', type: 'vec3' },
  27555. { name: 'p1', type: 'vec3' },
  27556. { name: 'p2', type: 'vec3' },
  27557. { name: 'p3', type: 'vec3' }
  27558. ]
  27559. } );
  27560. // Mipped Bicubic Texture Filtering by N8
  27561. // https://www.shadertoy.com/view/Dl2SDW
  27562. const bC = 1.0 / 6.0;
  27563. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  27564. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  27565. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  27566. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  27567. const g0 = ( a ) => w0( a ).add( w1( a ) );
  27568. const g1 = ( a ) => w2( a ).add( w3( a ) );
  27569. // h0 and h1 are the two offset functions
  27570. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  27571. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  27572. const bicubic = ( textureNode, texelSize, lod ) => {
  27573. const uv = textureNode.uvNode;
  27574. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  27575. const iuv = floor( uvScaled );
  27576. const fuv = fract( uvScaled );
  27577. const g0x = g0( fuv.x );
  27578. const g1x = g1( fuv.x );
  27579. const h0x = h0( fuv.x );
  27580. const h1x = h1( fuv.x );
  27581. const h0y = h0( fuv.y );
  27582. const h1y = h1( fuv.y );
  27583. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27584. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27585. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27586. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27587. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  27588. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  27589. return a.add( b );
  27590. };
  27591. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  27592. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  27593. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  27594. const fLodSizeInv = div( 1.0, fLodSize );
  27595. const cLodSizeInv = div( 1.0, cLodSize );
  27596. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  27597. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  27598. return fract( lodNode ).mix( fSample, cSample );
  27599. } );
  27600. //
  27601. // Transmission
  27602. //
  27603. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  27604. // Direction of refracted light.
  27605. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  27606. // Compute rotation-independant scaling of the model matrix.
  27607. const modelScale = vec3(
  27608. length( modelMatrix[ 0 ].xyz ),
  27609. length( modelMatrix[ 1 ].xyz ),
  27610. length( modelMatrix[ 2 ].xyz )
  27611. );
  27612. // The thickness is specified in local space.
  27613. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  27614. } ).setLayout( {
  27615. name: 'getVolumeTransmissionRay',
  27616. type: 'vec3',
  27617. inputs: [
  27618. { name: 'n', type: 'vec3' },
  27619. { name: 'v', type: 'vec3' },
  27620. { name: 'thickness', type: 'float' },
  27621. { name: 'ior', type: 'float' },
  27622. { name: 'modelMatrix', type: 'mat4' }
  27623. ]
  27624. } );
  27625. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  27626. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  27627. // an IOR of 1.5 results in the default amount of microfacet refraction.
  27628. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  27629. } ).setLayout( {
  27630. name: 'applyIorToRoughness',
  27631. type: 'float',
  27632. inputs: [
  27633. { name: 'roughness', type: 'float' },
  27634. { name: 'ior', type: 'float' }
  27635. ]
  27636. } );
  27637. const singleViewportMipTexture = /*@__PURE__*/ viewportMipTexture();
  27638. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ] ) => {
  27639. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  27640. //const transmissionSample = viewportMipTexture( fragCoord );
  27641. const lod = log2( float( screenSize.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  27642. return textureBicubic( transmissionSample, lod );
  27643. } );
  27644. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  27645. If( attenuationDistance.notEqual( 0 ), () => {
  27646. // Compute light attenuation using Beer's law.
  27647. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  27648. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  27649. return transmittance;
  27650. } );
  27651. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  27652. return vec3( 1.0 );
  27653. } ).setLayout( {
  27654. name: 'volumeAttenuation',
  27655. type: 'vec3',
  27656. inputs: [
  27657. { name: 'transmissionDistance', type: 'float' },
  27658. { name: 'attenuationColor', type: 'vec3' },
  27659. { name: 'attenuationDistance', type: 'float' }
  27660. ]
  27661. } );
  27662. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  27663. let transmittedLight, transmittance;
  27664. if ( dispersion ) {
  27665. transmittedLight = vec4().toVar();
  27666. transmittance = vec3().toVar();
  27667. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  27668. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  27669. Loop( { start: 0, end: 3 }, ( { i } ) => {
  27670. const ior = iors.element( i );
  27671. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  27672. const refractedRayExit = position.add( transmissionRay );
  27673. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  27674. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  27675. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  27676. refractionCoords.addAssign( 1.0 );
  27677. refractionCoords.divAssign( 2.0 );
  27678. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  27679. // Sample framebuffer to get pixel the refracted ray hits.
  27680. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  27681. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  27682. transmittedLight.a.addAssign( transmissionSample.a );
  27683. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  27684. } );
  27685. transmittedLight.a.divAssign( 3.0 );
  27686. } else {
  27687. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  27688. const refractedRayExit = position.add( transmissionRay );
  27689. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  27690. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  27691. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  27692. refractionCoords.addAssign( 1.0 );
  27693. refractionCoords.divAssign( 2.0 );
  27694. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  27695. // Sample framebuffer to get pixel the refracted ray hits.
  27696. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  27697. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  27698. }
  27699. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  27700. const dotNV = n.dot( v ).clamp();
  27701. // Get the specular component.
  27702. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  27703. dotNV,
  27704. specularColor,
  27705. specularF90,
  27706. roughness
  27707. } ) );
  27708. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  27709. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  27710. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  27711. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  27712. } );
  27713. //
  27714. // Iridescence
  27715. //
  27716. // XYZ to linear-sRGB color space
  27717. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  27718. 3.2404542, - 0.9692660, 0.0556434,
  27719. - 1.5371385, 1.8760108, - 0.2040259,
  27720. - 0.4985314, 0.0415560, 1.0572252
  27721. );
  27722. // Assume air interface for top
  27723. // Note: We don't handle the case fresnel0 == 1
  27724. const Fresnel0ToIor = ( fresnel0 ) => {
  27725. const sqrtF0 = fresnel0.sqrt();
  27726. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  27727. };
  27728. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  27729. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  27730. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  27731. };
  27732. // Fresnel equations for dielectric/dielectric interfaces.
  27733. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  27734. // Evaluation XYZ sensitivity curves in Fourier space
  27735. const evalSensitivity = ( OPD, shift ) => {
  27736. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  27737. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  27738. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  27739. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  27740. 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() );
  27741. 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() );
  27742. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  27743. const rgb = XYZ_TO_REC709.mul( xyz );
  27744. return rgb;
  27745. };
  27746. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  27747. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  27748. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  27749. // Evaluate the cosTheta on the base layer (Snell law)
  27750. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  27751. // Handle TIR:
  27752. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  27753. /*if ( cosTheta2Sq < 0.0 ) {
  27754. return vec3( 1.0 );
  27755. }*/
  27756. const cosTheta2 = cosTheta2Sq.sqrt();
  27757. // First interface
  27758. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  27759. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  27760. //const R21 = R12;
  27761. const T121 = R12.oneMinus();
  27762. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  27763. const phi21 = float( Math.PI ).sub( phi12 );
  27764. // Second interface
  27765. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  27766. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  27767. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  27768. const phi23 = vec3(
  27769. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  27770. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  27771. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  27772. );
  27773. // Phase shift
  27774. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  27775. const phi = vec3( phi21 ).add( phi23 );
  27776. // Compound terms
  27777. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  27778. const r123 = R123.sqrt();
  27779. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  27780. // Reflectance term for m = 0 (DC term amplitude)
  27781. const C0 = R12.add( Rs );
  27782. let I = C0;
  27783. // Reflectance term for m > 0 (pairs of diracs)
  27784. let Cm = Rs.sub( T121 );
  27785. for ( let m = 1; m <= 2; ++ m ) {
  27786. Cm = Cm.mul( r123 );
  27787. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  27788. I = I.add( Cm.mul( Sm ) );
  27789. }
  27790. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  27791. return I.max( vec3( 0.0 ) );
  27792. } ).setLayout( {
  27793. name: 'evalIridescence',
  27794. type: 'vec3',
  27795. inputs: [
  27796. { name: 'outsideIOR', type: 'float' },
  27797. { name: 'eta2', type: 'float' },
  27798. { name: 'cosTheta1', type: 'float' },
  27799. { name: 'thinFilmThickness', type: 'float' },
  27800. { name: 'baseF0', type: 'vec3' }
  27801. ]
  27802. } );
  27803. //
  27804. // Sheen
  27805. //
  27806. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  27807. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  27808. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  27809. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  27810. const dotNV = normal.dot( viewDir ).saturate();
  27811. const r2 = roughness.pow2();
  27812. const a = select(
  27813. roughness.lessThan( 0.25 ),
  27814. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  27815. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  27816. );
  27817. const b = select(
  27818. roughness.lessThan( 0.25 ),
  27819. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  27820. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  27821. );
  27822. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  27823. return DG.mul( 1.0 / Math.PI ).saturate();
  27824. } );
  27825. const clearcoatF0 = vec3( 0.04 );
  27826. const clearcoatF90 = float( 1 );
  27827. //
  27828. class PhysicalLightingModel extends LightingModel {
  27829. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  27830. super();
  27831. this.clearcoat = clearcoat;
  27832. this.sheen = sheen;
  27833. this.iridescence = iridescence;
  27834. this.anisotropy = anisotropy;
  27835. this.transmission = transmission;
  27836. this.dispersion = dispersion;
  27837. this.clearcoatRadiance = null;
  27838. this.clearcoatSpecularDirect = null;
  27839. this.clearcoatSpecularIndirect = null;
  27840. this.sheenSpecularDirect = null;
  27841. this.sheenSpecularIndirect = null;
  27842. this.iridescenceFresnel = null;
  27843. this.iridescenceF0 = null;
  27844. }
  27845. start( context ) {
  27846. if ( this.clearcoat === true ) {
  27847. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  27848. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  27849. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  27850. }
  27851. if ( this.sheen === true ) {
  27852. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  27853. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  27854. }
  27855. if ( this.iridescence === true ) {
  27856. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  27857. this.iridescenceFresnel = evalIridescence( {
  27858. outsideIOR: float( 1.0 ),
  27859. eta2: iridescenceIOR,
  27860. cosTheta1: dotNVi,
  27861. thinFilmThickness: iridescenceThickness,
  27862. baseF0: specularColor
  27863. } );
  27864. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  27865. }
  27866. if ( this.transmission === true ) {
  27867. const position = positionWorld;
  27868. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  27869. const n = transformedNormalWorld;
  27870. context.backdrop = getIBLVolumeRefraction(
  27871. n,
  27872. v,
  27873. roughness,
  27874. diffuseColor,
  27875. specularColor,
  27876. specularF90, // specularF90
  27877. position, // positionWorld
  27878. modelWorldMatrix, // modelMatrix
  27879. cameraViewMatrix, // viewMatrix
  27880. cameraProjectionMatrix, // projMatrix
  27881. ior,
  27882. thickness,
  27883. attenuationColor,
  27884. attenuationDistance,
  27885. this.dispersion ? dispersion : null
  27886. );
  27887. context.backdropAlpha = transmission;
  27888. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  27889. }
  27890. }
  27891. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  27892. // Approximates multiscattering in order to preserve energy.
  27893. // http://www.jcgt.org/published/0008/01/03/
  27894. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  27895. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27896. const fab = DFGApprox( { roughness, dotNV } );
  27897. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  27898. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  27899. const Ess = fab.x.add( fab.y );
  27900. const Ems = Ess.oneMinus();
  27901. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  27902. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  27903. singleScatter.addAssign( FssEss );
  27904. multiScatter.addAssign( Fms.mul( Ems ) );
  27905. }
  27906. direct( { lightDirection, lightColor, reflectedLight } ) {
  27907. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27908. const irradiance = dotNL.mul( lightColor );
  27909. if ( this.sheen === true ) {
  27910. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  27911. }
  27912. if ( this.clearcoat === true ) {
  27913. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  27914. const ccIrradiance = dotNLcc.mul( lightColor );
  27915. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  27916. }
  27917. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  27918. 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 } ) ) );
  27919. }
  27920. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  27921. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  27922. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  27923. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  27924. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  27925. const N = transformedNormalView;
  27926. const V = positionViewDirection;
  27927. const P = positionView.toVar();
  27928. const uv = LTC_Uv( { N, V, roughness } );
  27929. const t1 = ltc_1.uv( uv ).toVar();
  27930. const t2 = ltc_2.uv( uv ).toVar();
  27931. const mInv = mat3(
  27932. vec3( t1.x, 0, t1.y ),
  27933. vec3( 0, 1, 0 ),
  27934. vec3( t1.z, 0, t1.w )
  27935. ).toVar();
  27936. // LTC Fresnel Approximation by Stephen Hill
  27937. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  27938. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  27939. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  27940. 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 } ) ) );
  27941. }
  27942. indirect( context, stack, builder ) {
  27943. this.indirectDiffuse( context, stack, builder );
  27944. this.indirectSpecular( context, stack, builder );
  27945. this.ambientOcclusion( context, stack, builder );
  27946. }
  27947. indirectDiffuse( { irradiance, reflectedLight } ) {
  27948. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  27949. }
  27950. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  27951. if ( this.sheen === true ) {
  27952. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  27953. sheen,
  27954. IBLSheenBRDF( {
  27955. normal: transformedNormalView,
  27956. viewDir: positionViewDirection,
  27957. roughness: sheenRoughness
  27958. } )
  27959. ) );
  27960. }
  27961. if ( this.clearcoat === true ) {
  27962. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  27963. const clearcoatEnv = EnvironmentBRDF( {
  27964. dotNV: dotNVcc,
  27965. specularColor: clearcoatF0,
  27966. specularF90: clearcoatF90,
  27967. roughness: clearcoatRoughness
  27968. } );
  27969. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  27970. }
  27971. // Both indirect specular and indirect diffuse light accumulate here
  27972. const singleScattering = vec3().toVar( 'singleScattering' );
  27973. const multiScattering = vec3().toVar( 'multiScattering' );
  27974. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  27975. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  27976. const totalScattering = singleScattering.add( multiScattering );
  27977. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  27978. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  27979. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  27980. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  27981. }
  27982. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  27983. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27984. const aoNV = dotNV.add( ambientOcclusion );
  27985. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  27986. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  27987. if ( this.clearcoat === true ) {
  27988. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  27989. }
  27990. if ( this.sheen === true ) {
  27991. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  27992. }
  27993. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27994. reflectedLight.indirectSpecular.mulAssign( aoNode );
  27995. }
  27996. finish( context ) {
  27997. const { outgoingLight } = context;
  27998. if ( this.clearcoat === true ) {
  27999. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28000. const Fcc = F_Schlick( {
  28001. dotVH: dotNVcc,
  28002. f0: clearcoatF0,
  28003. f90: clearcoatF90
  28004. } );
  28005. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  28006. outgoingLight.assign( clearcoatLight );
  28007. }
  28008. if ( this.sheen === true ) {
  28009. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  28010. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  28011. outgoingLight.assign( sheenLight );
  28012. }
  28013. }
  28014. }
  28015. // These defines must match with PMREMGenerator
  28016. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  28017. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  28018. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  28019. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  28020. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  28021. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  28022. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  28023. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  28024. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  28025. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  28026. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  28027. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  28028. // These shader functions convert between the UV coordinates of a single face of
  28029. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  28030. // sampling a textureCube (not generally normalized ).
  28031. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  28032. const absDirection = vec3( abs( direction ) ).toVar();
  28033. const face = float( - 1.0 ).toVar();
  28034. If( absDirection.x.greaterThan( absDirection.z ), () => {
  28035. If( absDirection.x.greaterThan( absDirection.y ), () => {
  28036. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  28037. } ).Else( () => {
  28038. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28039. } );
  28040. } ).Else( () => {
  28041. If( absDirection.z.greaterThan( absDirection.y ), () => {
  28042. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  28043. } ).Else( () => {
  28044. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28045. } );
  28046. } );
  28047. return face;
  28048. } ).setLayout( {
  28049. name: 'getFace',
  28050. type: 'float',
  28051. inputs: [
  28052. { name: 'direction', type: 'vec3' }
  28053. ]
  28054. } );
  28055. // RH coordinate system; PMREM face-indexing convention
  28056. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  28057. const uv = vec2().toVar();
  28058. If( face.equal( 0.0 ), () => {
  28059. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  28060. } ).ElseIf( face.equal( 1.0 ), () => {
  28061. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  28062. } ).ElseIf( face.equal( 2.0 ), () => {
  28063. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  28064. } ).ElseIf( face.equal( 3.0 ), () => {
  28065. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  28066. } ).ElseIf( face.equal( 4.0 ), () => {
  28067. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  28068. } ).Else( () => {
  28069. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  28070. } );
  28071. return mul( 0.5, uv.add( 1.0 ) );
  28072. } ).setLayout( {
  28073. name: 'getUV',
  28074. type: 'vec2',
  28075. inputs: [
  28076. { name: 'direction', type: 'vec3' },
  28077. { name: 'face', type: 'float' }
  28078. ]
  28079. } );
  28080. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  28081. const mip = float( 0.0 ).toVar();
  28082. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  28083. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  28084. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  28085. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  28086. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  28087. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  28088. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  28089. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  28090. } ).Else( () => {
  28091. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  28092. } );
  28093. return mip;
  28094. } ).setLayout( {
  28095. name: 'roughnessToMip',
  28096. type: 'float',
  28097. inputs: [
  28098. { name: 'roughness', type: 'float' }
  28099. ]
  28100. } );
  28101. // RH coordinate system; PMREM face-indexing convention
  28102. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  28103. const uv = uv_immutable.toVar();
  28104. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  28105. const direction = vec3( uv, 1.0 ).toVar();
  28106. If( face.equal( 0.0 ), () => {
  28107. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  28108. } ).ElseIf( face.equal( 1.0 ), () => {
  28109. direction.assign( direction.xzy );
  28110. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  28111. } ).ElseIf( face.equal( 2.0 ), () => {
  28112. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  28113. } ).ElseIf( face.equal( 3.0 ), () => {
  28114. direction.assign( direction.zyx );
  28115. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  28116. } ).ElseIf( face.equal( 4.0 ), () => {
  28117. direction.assign( direction.xzy );
  28118. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  28119. } ).ElseIf( face.equal( 5.0 ), () => {
  28120. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  28121. } );
  28122. return direction;
  28123. } ).setLayout( {
  28124. name: 'getDirection',
  28125. type: 'vec3',
  28126. inputs: [
  28127. { name: 'uv', type: 'vec2' },
  28128. { name: 'face', type: 'float' }
  28129. ]
  28130. } );
  28131. //
  28132. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28133. const roughness = float( roughness_immutable );
  28134. const sampleDir = vec3( sampleDir_immutable );
  28135. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  28136. const mipF = fract( mip );
  28137. const mipInt = floor( mip );
  28138. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28139. If( mipF.notEqual( 0.0 ), () => {
  28140. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28141. color0.assign( mix( color0, color1, mipF ) );
  28142. } );
  28143. return color0;
  28144. } );
  28145. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28146. const mipInt = float( mipInt_immutable ).toVar();
  28147. const direction = vec3( direction_immutable );
  28148. const face = float( getFace( direction ) ).toVar();
  28149. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  28150. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  28151. const faceSize = float( exp2( mipInt ) ).toVar();
  28152. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  28153. If( face.greaterThan( 2.0 ), () => {
  28154. uv.y.addAssign( faceSize );
  28155. face.subAssign( 3.0 );
  28156. } );
  28157. uv.x.addAssign( face.mul( faceSize ) );
  28158. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  28159. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  28160. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  28161. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  28162. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  28163. } );
  28164. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28165. const cosTheta = cos( theta );
  28166. // Rodrigues' axis-angle rotation
  28167. const sampleDirection = outputDirection.mul( cosTheta )
  28168. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  28169. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  28170. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  28171. } );
  28172. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28173. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  28174. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  28175. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  28176. } );
  28177. axis.assign( normalize( axis ) );
  28178. const gl_FragColor = vec3().toVar();
  28179. 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 } ) ) );
  28180. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  28181. If( i.greaterThanEqual( samples ), () => {
  28182. Break();
  28183. } );
  28184. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  28185. 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 } ) ) );
  28186. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28187. } );
  28188. return vec4( gl_FragColor, 1 );
  28189. } );
  28190. let _generator = null;
  28191. const _cache = new WeakMap();
  28192. function _generateCubeUVSize( imageHeight ) {
  28193. const maxMip = Math.log2( imageHeight ) - 2;
  28194. const texelHeight = 1.0 / imageHeight;
  28195. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  28196. return { texelWidth, texelHeight, maxMip };
  28197. }
  28198. function _getPMREMFromTexture( texture ) {
  28199. let cacheTexture = _cache.get( texture );
  28200. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  28201. if ( pmremVersion !== texture.pmremVersion ) {
  28202. const image = texture.image;
  28203. if ( texture.isCubeTexture ) {
  28204. if ( isCubeMapReady( image ) ) {
  28205. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  28206. } else {
  28207. return null;
  28208. }
  28209. } else {
  28210. if ( isEquirectangularMapReady( image ) ) {
  28211. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  28212. } else {
  28213. return null;
  28214. }
  28215. }
  28216. cacheTexture.pmremVersion = texture.pmremVersion;
  28217. _cache.set( texture, cacheTexture );
  28218. }
  28219. return cacheTexture.texture;
  28220. }
  28221. class PMREMNode extends TempNode {
  28222. static get type() {
  28223. return 'PMREMNode';
  28224. }
  28225. constructor( value, uvNode = null, levelNode = null ) {
  28226. super( 'vec3' );
  28227. this._value = value;
  28228. this._pmrem = null;
  28229. this.uvNode = uvNode;
  28230. this.levelNode = levelNode;
  28231. this._generator = null;
  28232. const defaultTexture = new Texture();
  28233. defaultTexture.isRenderTargetTexture = true;
  28234. this._texture = texture( defaultTexture );
  28235. this._width = uniform( 0 );
  28236. this._height = uniform( 0 );
  28237. this._maxMip = uniform( 0 );
  28238. this.updateBeforeType = NodeUpdateType.RENDER;
  28239. }
  28240. set value( value ) {
  28241. this._value = value;
  28242. this._pmrem = null;
  28243. }
  28244. get value() {
  28245. return this._value;
  28246. }
  28247. updateFromTexture( texture ) {
  28248. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  28249. this._texture.value = texture;
  28250. this._width.value = cubeUVSize.texelWidth;
  28251. this._height.value = cubeUVSize.texelHeight;
  28252. this._maxMip.value = cubeUVSize.maxMip;
  28253. }
  28254. updateBefore() {
  28255. let pmrem = this._pmrem;
  28256. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  28257. const texture = this._value;
  28258. if ( pmremVersion !== texture.pmremVersion ) {
  28259. if ( texture.isPMREMTexture === true ) {
  28260. pmrem = texture;
  28261. } else {
  28262. pmrem = _getPMREMFromTexture( texture );
  28263. }
  28264. if ( pmrem !== null ) {
  28265. this._pmrem = pmrem;
  28266. this.updateFromTexture( pmrem );
  28267. }
  28268. }
  28269. }
  28270. setup( builder ) {
  28271. if ( _generator === null ) {
  28272. _generator = builder.createPMREMGenerator();
  28273. }
  28274. //
  28275. this.updateBefore( builder );
  28276. //
  28277. let uvNode = this.uvNode;
  28278. if ( uvNode === null && builder.context.getUV ) {
  28279. uvNode = builder.context.getUV( this );
  28280. }
  28281. //
  28282. const texture = this.value;
  28283. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  28284. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  28285. }
  28286. //
  28287. let levelNode = this.levelNode;
  28288. if ( levelNode === null && builder.context.getTextureLevel ) {
  28289. levelNode = builder.context.getTextureLevel( this );
  28290. }
  28291. //
  28292. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  28293. }
  28294. }
  28295. function isCubeMapReady( image ) {
  28296. if ( image === null || image === undefined ) return false;
  28297. let count = 0;
  28298. const length = 6;
  28299. for ( let i = 0; i < length; i ++ ) {
  28300. if ( image[ i ] !== undefined ) count ++;
  28301. }
  28302. return count === length;
  28303. }
  28304. function isEquirectangularMapReady( image ) {
  28305. if ( image === null || image === undefined ) return false;
  28306. return image.height > 0;
  28307. }
  28308. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  28309. const _envNodeCache = new WeakMap();
  28310. class EnvironmentNode extends LightingNode {
  28311. static get type() {
  28312. return 'EnvironmentNode';
  28313. }
  28314. constructor( envNode = null ) {
  28315. super();
  28316. this.envNode = envNode;
  28317. }
  28318. setup( builder ) {
  28319. const { material } = builder;
  28320. let envNode = this.envNode;
  28321. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  28322. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  28323. let cacheEnvNode = _envNodeCache.get( value );
  28324. if ( cacheEnvNode === undefined ) {
  28325. cacheEnvNode = pmremTexture( value );
  28326. _envNodeCache.set( value, cacheEnvNode );
  28327. }
  28328. envNode = cacheEnvNode;
  28329. }
  28330. //
  28331. const envMap = material.envMap;
  28332. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  28333. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  28334. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  28335. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  28336. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  28337. const isolateRadiance = cache( radiance );
  28338. const isolateIrradiance = cache( irradiance );
  28339. //
  28340. builder.context.radiance.addAssign( isolateRadiance );
  28341. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  28342. //
  28343. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  28344. if ( clearcoatRadiance ) {
  28345. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  28346. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  28347. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  28348. }
  28349. }
  28350. }
  28351. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  28352. let reflectVec = null;
  28353. return {
  28354. getUV: () => {
  28355. if ( reflectVec === null ) {
  28356. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  28357. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  28358. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  28359. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  28360. }
  28361. return reflectVec;
  28362. },
  28363. getTextureLevel: () => {
  28364. return roughnessNode;
  28365. }
  28366. };
  28367. };
  28368. const createIrradianceContext = ( normalWorldNode ) => {
  28369. return {
  28370. getUV: () => {
  28371. return normalWorldNode;
  28372. },
  28373. getTextureLevel: () => {
  28374. return float( 1.0 );
  28375. }
  28376. };
  28377. };
  28378. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  28379. class MeshStandardNodeMaterial extends NodeMaterial {
  28380. static get type() {
  28381. return 'MeshStandardNodeMaterial';
  28382. }
  28383. constructor( parameters ) {
  28384. super();
  28385. this.isMeshStandardNodeMaterial = true;
  28386. this.lights = true;
  28387. this.emissiveNode = null;
  28388. this.metalnessNode = null;
  28389. this.roughnessNode = null;
  28390. this.setDefaultValues( _defaultValues$6 );
  28391. this.setValues( parameters );
  28392. }
  28393. setupEnvironment( builder ) {
  28394. let envNode = super.setupEnvironment( builder );
  28395. if ( envNode === null && builder.environmentNode ) {
  28396. envNode = builder.environmentNode;
  28397. }
  28398. return envNode ? new EnvironmentNode( envNode ) : null;
  28399. }
  28400. setupLightingModel( /*builder*/ ) {
  28401. return new PhysicalLightingModel();
  28402. }
  28403. setupSpecular() {
  28404. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  28405. specularColor.assign( specularColorNode );
  28406. specularF90.assign( 1.0 );
  28407. }
  28408. setupVariants() {
  28409. // METALNESS
  28410. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  28411. metalness.assign( metalnessNode );
  28412. // ROUGHNESS
  28413. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  28414. roughnessNode = getRoughness( { roughness: roughnessNode } );
  28415. roughness.assign( roughnessNode );
  28416. // SPECULAR COLOR
  28417. this.setupSpecular();
  28418. // DIFFUSE COLOR
  28419. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  28420. }
  28421. copy( source ) {
  28422. this.emissiveNode = source.emissiveNode;
  28423. this.metalnessNode = source.metalnessNode;
  28424. this.roughnessNode = source.roughnessNode;
  28425. return super.copy( source );
  28426. }
  28427. }
  28428. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  28429. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  28430. static get type() {
  28431. return 'MeshPhysicalNodeMaterial';
  28432. }
  28433. constructor( parameters ) {
  28434. super();
  28435. this.isMeshPhysicalNodeMaterial = true;
  28436. this.clearcoatNode = null;
  28437. this.clearcoatRoughnessNode = null;
  28438. this.clearcoatNormalNode = null;
  28439. this.sheenNode = null;
  28440. this.sheenRoughnessNode = null;
  28441. this.iridescenceNode = null;
  28442. this.iridescenceIORNode = null;
  28443. this.iridescenceThicknessNode = null;
  28444. this.specularIntensityNode = null;
  28445. this.specularColorNode = null;
  28446. this.iorNode = null;
  28447. this.transmissionNode = null;
  28448. this.thicknessNode = null;
  28449. this.attenuationDistanceNode = null;
  28450. this.attenuationColorNode = null;
  28451. this.dispersionNode = null;
  28452. this.anisotropyNode = null;
  28453. this.setDefaultValues( _defaultValues$5 );
  28454. this.setValues( parameters );
  28455. }
  28456. get useClearcoat() {
  28457. return this.clearcoat > 0 || this.clearcoatNode !== null;
  28458. }
  28459. get useIridescence() {
  28460. return this.iridescence > 0 || this.iridescenceNode !== null;
  28461. }
  28462. get useSheen() {
  28463. return this.sheen > 0 || this.sheenNode !== null;
  28464. }
  28465. get useAnisotropy() {
  28466. return this.anisotropy > 0 || this.anisotropyNode !== null;
  28467. }
  28468. get useTransmission() {
  28469. return this.transmission > 0 || this.transmissionNode !== null;
  28470. }
  28471. get useDispersion() {
  28472. return this.dispersion > 0 || this.dispersionNode !== null;
  28473. }
  28474. setupSpecular() {
  28475. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  28476. ior.assign( iorNode );
  28477. 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 ) );
  28478. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  28479. }
  28480. setupLightingModel( /*builder*/ ) {
  28481. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  28482. }
  28483. setupVariants( builder ) {
  28484. super.setupVariants( builder );
  28485. // CLEARCOAT
  28486. if ( this.useClearcoat ) {
  28487. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  28488. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  28489. clearcoat.assign( clearcoatNode );
  28490. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  28491. }
  28492. // SHEEN
  28493. if ( this.useSheen ) {
  28494. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  28495. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  28496. sheen.assign( sheenNode );
  28497. sheenRoughness.assign( sheenRoughnessNode );
  28498. }
  28499. // IRIDESCENCE
  28500. if ( this.useIridescence ) {
  28501. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  28502. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  28503. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  28504. iridescence.assign( iridescenceNode );
  28505. iridescenceIOR.assign( iridescenceIORNode );
  28506. iridescenceThickness.assign( iridescenceThicknessNode );
  28507. }
  28508. // ANISOTROPY
  28509. if ( this.useAnisotropy ) {
  28510. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  28511. anisotropy.assign( anisotropyV.length() );
  28512. If( anisotropy.equal( 0.0 ), () => {
  28513. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  28514. } ).Else( () => {
  28515. anisotropyV.divAssign( vec2( anisotropy ) );
  28516. anisotropy.assign( anisotropy.saturate() );
  28517. } );
  28518. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  28519. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  28520. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  28521. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  28522. }
  28523. // TRANSMISSION
  28524. if ( this.useTransmission ) {
  28525. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  28526. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  28527. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  28528. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  28529. transmission.assign( transmissionNode );
  28530. thickness.assign( thicknessNode );
  28531. attenuationDistance.assign( attenuationDistanceNode );
  28532. attenuationColor.assign( attenuationColorNode );
  28533. if ( this.useDispersion ) {
  28534. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  28535. dispersion.assign( dispersionNode );
  28536. }
  28537. }
  28538. }
  28539. setupClearcoatNormal() {
  28540. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  28541. }
  28542. setup( builder ) {
  28543. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  28544. super.setup( builder );
  28545. }
  28546. copy( source ) {
  28547. this.clearcoatNode = source.clearcoatNode;
  28548. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  28549. this.clearcoatNormalNode = source.clearcoatNormalNode;
  28550. this.sheenNode = source.sheenNode;
  28551. this.sheenRoughnessNode = source.sheenRoughnessNode;
  28552. this.iridescenceNode = source.iridescenceNode;
  28553. this.iridescenceIORNode = source.iridescenceIORNode;
  28554. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  28555. this.specularIntensityNode = source.specularIntensityNode;
  28556. this.specularColorNode = source.specularColorNode;
  28557. this.transmissionNode = source.transmissionNode;
  28558. this.thicknessNode = source.thicknessNode;
  28559. this.attenuationDistanceNode = source.attenuationDistanceNode;
  28560. this.attenuationColorNode = source.attenuationColorNode;
  28561. this.dispersionNode = source.dispersionNode;
  28562. this.anisotropyNode = source.anisotropyNode;
  28563. return super.copy( source );
  28564. }
  28565. }
  28566. class SSSLightingModel extends PhysicalLightingModel {
  28567. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  28568. super( useClearcoat, useSheen, useIridescence );
  28569. this.useSSS = useSSS;
  28570. }
  28571. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28572. if ( this.useSSS === true ) {
  28573. const material = builder.material;
  28574. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  28575. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  28576. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  28577. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  28578. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  28579. }
  28580. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  28581. }
  28582. }
  28583. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  28584. static get type() {
  28585. return 'MeshSSSNodeMaterial';
  28586. }
  28587. constructor( parameters ) {
  28588. super( parameters );
  28589. this.thicknessColorNode = null;
  28590. this.thicknessDistortionNode = float( 0.1 );
  28591. this.thicknessAmbientNode = float( 0.0 );
  28592. this.thicknessAttenuationNode = float( .1 );
  28593. this.thicknessPowerNode = float( 2.0 );
  28594. this.thicknessScaleNode = float( 10.0 );
  28595. }
  28596. get useSSS() {
  28597. return this.thicknessColorNode !== null;
  28598. }
  28599. setupLightingModel( /*builder*/ ) {
  28600. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  28601. }
  28602. copy( source ) {
  28603. this.thicknessColorNode = source.thicknessColorNode;
  28604. this.thicknessDistortionNode = source.thicknessDistortionNode;
  28605. this.thicknessAmbientNode = source.thicknessAmbientNode;
  28606. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  28607. this.thicknessPowerNode = source.thicknessPowerNode;
  28608. this.thicknessScaleNode = source.thicknessScaleNode;
  28609. return super.copy( source );
  28610. }
  28611. }
  28612. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  28613. // dotNL will be from -1.0 to 1.0
  28614. const dotNL = normal.dot( lightDirection );
  28615. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  28616. if ( builder.material.gradientMap ) {
  28617. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  28618. return vec3( gradientMap.r );
  28619. } else {
  28620. const fw = coord.fwidth().mul( 0.5 );
  28621. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  28622. }
  28623. } );
  28624. class ToonLightingModel extends LightingModel {
  28625. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28626. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  28627. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28628. }
  28629. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  28630. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28631. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28632. }
  28633. }
  28634. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  28635. class MeshToonNodeMaterial extends NodeMaterial {
  28636. static get type() {
  28637. return 'MeshToonNodeMaterial';
  28638. }
  28639. constructor( parameters ) {
  28640. super();
  28641. this.isMeshToonNodeMaterial = true;
  28642. this.lights = true;
  28643. this.setDefaultValues( _defaultValues$4 );
  28644. this.setValues( parameters );
  28645. }
  28646. setupLightingModel( /*builder*/ ) {
  28647. return new ToonLightingModel();
  28648. }
  28649. }
  28650. class MatcapUVNode extends TempNode {
  28651. static get type() {
  28652. return 'MatcapUVNode';
  28653. }
  28654. constructor() {
  28655. super( 'vec2' );
  28656. }
  28657. setup() {
  28658. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  28659. const y = positionViewDirection.cross( x );
  28660. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  28661. }
  28662. }
  28663. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  28664. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  28665. class MeshMatcapNodeMaterial extends NodeMaterial {
  28666. static get type() {
  28667. return 'MeshMatcapNodeMaterial';
  28668. }
  28669. constructor( parameters ) {
  28670. super();
  28671. this.lights = false;
  28672. this.isMeshMatcapNodeMaterial = true;
  28673. this.setDefaultValues( _defaultValues$3 );
  28674. this.setValues( parameters );
  28675. }
  28676. setupVariants( builder ) {
  28677. const uv = matcapUV;
  28678. let matcapColor;
  28679. if ( builder.material.matcap ) {
  28680. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  28681. } else {
  28682. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  28683. }
  28684. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  28685. }
  28686. }
  28687. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  28688. class PointsNodeMaterial extends NodeMaterial {
  28689. static get type() {
  28690. return 'PointsNodeMaterial';
  28691. }
  28692. constructor( parameters ) {
  28693. super();
  28694. this.isPointsNodeMaterial = true;
  28695. this.lights = false;
  28696. this.transparent = true;
  28697. this.sizeNode = null;
  28698. this.setDefaultValues( _defaultValues$2 );
  28699. this.setValues( parameters );
  28700. }
  28701. copy( source ) {
  28702. this.sizeNode = source.sizeNode;
  28703. return super.copy( source );
  28704. }
  28705. }
  28706. class RotateNode extends TempNode {
  28707. static get type() {
  28708. return 'RotateNode';
  28709. }
  28710. constructor( positionNode, rotationNode ) {
  28711. super();
  28712. this.positionNode = positionNode;
  28713. this.rotationNode = rotationNode;
  28714. }
  28715. getNodeType( builder ) {
  28716. return this.positionNode.getNodeType( builder );
  28717. }
  28718. setup( builder ) {
  28719. const { rotationNode, positionNode } = this;
  28720. const nodeType = this.getNodeType( builder );
  28721. if ( nodeType === 'vec2' ) {
  28722. const cosAngle = rotationNode.cos();
  28723. const sinAngle = rotationNode.sin();
  28724. const rotationMatrix = mat2(
  28725. cosAngle, sinAngle,
  28726. sinAngle.negate(), cosAngle
  28727. );
  28728. return rotationMatrix.mul( positionNode );
  28729. } else {
  28730. const rotation = rotationNode;
  28731. 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 ) );
  28732. 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 ) );
  28733. 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 ) );
  28734. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  28735. }
  28736. }
  28737. }
  28738. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  28739. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  28740. class SpriteNodeMaterial extends NodeMaterial {
  28741. static get type() {
  28742. return 'SpriteNodeMaterial';
  28743. }
  28744. constructor( parameters ) {
  28745. super();
  28746. this.isSpriteNodeMaterial = true;
  28747. this.lights = false;
  28748. this.positionNode = null;
  28749. this.rotationNode = null;
  28750. this.scaleNode = null;
  28751. this.setDefaultValues( _defaultValues$1 );
  28752. this.setValues( parameters );
  28753. }
  28754. setupPosition( { object, context } ) {
  28755. // < VERTEX STAGE >
  28756. const { positionNode, rotationNode, scaleNode } = this;
  28757. const vertex = positionLocal;
  28758. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  28759. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  28760. if ( scaleNode !== null ) {
  28761. scale = scale.mul( scaleNode );
  28762. }
  28763. let alignedPosition = vertex.xy;
  28764. if ( object.center && object.center.isVector2 === true ) {
  28765. alignedPosition = alignedPosition.sub( uniform( object.center ).sub( 0.5 ) );
  28766. }
  28767. alignedPosition = alignedPosition.mul( scale );
  28768. const rotation = float( rotationNode || materialRotation );
  28769. const rotatedPosition = rotate( alignedPosition, rotation );
  28770. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  28771. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  28772. context.vertex = vertex;
  28773. return modelViewProjection;
  28774. }
  28775. copy( source ) {
  28776. this.positionNode = source.positionNode;
  28777. this.rotationNode = source.rotationNode;
  28778. this.scaleNode = source.scaleNode;
  28779. return super.copy( source );
  28780. }
  28781. }
  28782. class ShadowMaskModel extends LightingModel {
  28783. constructor() {
  28784. super();
  28785. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  28786. }
  28787. direct( { shadowMask } ) {
  28788. this.shadowNode.mulAssign( shadowMask );
  28789. }
  28790. finish( context ) {
  28791. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  28792. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  28793. }
  28794. }
  28795. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  28796. class ShadowNodeMaterial extends NodeMaterial {
  28797. static get type() {
  28798. return 'ShadowNodeMaterial';
  28799. }
  28800. constructor( parameters ) {
  28801. super();
  28802. this.isShadowNodeMaterial = true;
  28803. this.lights = true;
  28804. this.setDefaultValues( _defaultValues );
  28805. this.setValues( parameters );
  28806. }
  28807. setupLightingModel( /*builder*/ ) {
  28808. return new ShadowMaskModel();
  28809. }
  28810. }
  28811. const normal = Fn( ( { texture, uv } ) => {
  28812. const epsilon = 0.0001;
  28813. const ret = vec3().temp();
  28814. If( uv.x.lessThan( epsilon ), () => {
  28815. ret.assign( vec3( 1, 0, 0 ) );
  28816. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  28817. ret.assign( vec3( 0, 1, 0 ) );
  28818. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  28819. ret.assign( vec3( 0, 0, 1 ) );
  28820. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  28821. ret.assign( vec3( - 1, 0, 0 ) );
  28822. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  28823. ret.assign( vec3( 0, - 1, 0 ) );
  28824. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  28825. ret.assign( vec3( 0, 0, - 1 ) );
  28826. } ).Else( () => {
  28827. const step = 0.01;
  28828. const x = texture.uv( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  28829. const y = texture.uv( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  28830. const z = texture.uv( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  28831. ret.assign( vec3( x, y, z ) );
  28832. } );
  28833. return ret.normalize();
  28834. } );
  28835. class Texture3DNode extends TextureNode {
  28836. static get type() {
  28837. return 'Texture3DNode';
  28838. }
  28839. constructor( value, uvNode = null, levelNode = null ) {
  28840. super( value, uvNode, levelNode );
  28841. this.isTexture3DNode = true;
  28842. }
  28843. getInputType( /*builder*/ ) {
  28844. return 'texture3D';
  28845. }
  28846. getDefaultUV() {
  28847. return vec3( 0.5, 0.5, 0.5 );
  28848. }
  28849. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  28850. setupUV( builder, uvNode ) {
  28851. return uvNode;
  28852. }
  28853. generateUV( builder, uvNode ) {
  28854. return uvNode.build( builder, 'vec3' );
  28855. }
  28856. normal( uvNode ) {
  28857. return normal( { texture: this, uv: uvNode } );
  28858. }
  28859. }
  28860. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  28861. class VolumeNodeMaterial extends NodeMaterial {
  28862. static get type() {
  28863. return 'VolumeNodeMaterial';
  28864. }
  28865. constructor( params = {} ) {
  28866. super();
  28867. this.lights = false;
  28868. this.isVolumeNodeMaterial = true;
  28869. this.testNode = null;
  28870. this.setValues( params );
  28871. }
  28872. setup( builder ) {
  28873. const map = texture3D( this.map, null, 0 );
  28874. const hitBox = Fn( ( { orig, dir } ) => {
  28875. const box_min = vec3( - 0.5 );
  28876. const box_max = vec3( 0.5 );
  28877. const inv_dir = dir.reciprocal();
  28878. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  28879. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  28880. const tmin = min$1( tmin_tmp, tmax_tmp );
  28881. const tmax = max$1( tmin_tmp, tmax_tmp );
  28882. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  28883. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  28884. return vec2( t0, t1 );
  28885. } );
  28886. this.fragmentNode = Fn( () => {
  28887. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  28888. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  28889. const rayDir = vDirection.normalize();
  28890. const bounds = property( 'vec2', 'bounds' ).assign( hitBox( { orig: vOrigin, dir: rayDir } ) );
  28891. bounds.x.greaterThan( bounds.y ).discard();
  28892. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  28893. const p = property( 'vec3', 'p' ).assign( vOrigin.add( bounds.x.mul( rayDir ) ) );
  28894. const inc = property( 'vec3', 'inc' ).assign( vec3( rayDir.abs().reciprocal() ) );
  28895. const delta = property( 'float', 'delta' ).assign( min$1( inc.x, min$1( inc.y, inc.z ) ) );
  28896. delta.divAssign( materialReference( 'steps', 'float' ) );
  28897. const ac = property( 'vec4', 'ac' ).assign( vec4( materialReference( 'base', 'color' ), 0.0 ) );
  28898. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  28899. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  28900. if ( this.testNode !== null ) {
  28901. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  28902. } else {
  28903. // default to show surface of mesh
  28904. ac.a.assign( 1 );
  28905. Break();
  28906. }
  28907. p.addAssign( rayDir.mul( delta ) );
  28908. } );
  28909. ac.a.equal( 0 ).discard();
  28910. return vec4( ac );
  28911. } )();
  28912. super.setup( builder );
  28913. }
  28914. }
  28915. class Animation {
  28916. constructor( nodes, info ) {
  28917. this.nodes = nodes;
  28918. this.info = info;
  28919. this.animationLoop = null;
  28920. this.requestId = null;
  28921. this._init();
  28922. }
  28923. _init() {
  28924. const update = ( time, frame ) => {
  28925. this.requestId = self.requestAnimationFrame( update );
  28926. if ( this.info.autoReset === true ) this.info.reset();
  28927. this.nodes.nodeFrame.update();
  28928. this.info.frame = this.nodes.nodeFrame.frameId;
  28929. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  28930. };
  28931. update();
  28932. }
  28933. dispose() {
  28934. self.cancelAnimationFrame( this.requestId );
  28935. this.requestId = null;
  28936. }
  28937. setAnimationLoop( callback ) {
  28938. this.animationLoop = callback;
  28939. }
  28940. }
  28941. class ChainMap {
  28942. constructor() {
  28943. this.weakMap = new WeakMap();
  28944. }
  28945. get( keys ) {
  28946. let map = this.weakMap;
  28947. for ( let i = 0; i < keys.length; i ++ ) {
  28948. map = map.get( keys[ i ] );
  28949. if ( map === undefined ) return undefined;
  28950. }
  28951. return map.get( keys[ keys.length - 1 ] );
  28952. }
  28953. set( keys, value ) {
  28954. let map = this.weakMap;
  28955. for ( let i = 0; i < keys.length; i ++ ) {
  28956. const key = keys[ i ];
  28957. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  28958. map = map.get( key );
  28959. }
  28960. return map.set( keys[ keys.length - 1 ], value );
  28961. }
  28962. delete( keys ) {
  28963. let map = this.weakMap;
  28964. for ( let i = 0; i < keys.length; i ++ ) {
  28965. map = map.get( keys[ i ] );
  28966. if ( map === undefined ) return false;
  28967. }
  28968. return map.delete( keys[ keys.length - 1 ] );
  28969. }
  28970. }
  28971. const _plane = /*@__PURE__*/ new Plane();
  28972. class ClippingContext {
  28973. constructor() {
  28974. this.version = 0;
  28975. this.globalClippingCount = 0;
  28976. this.localClippingCount = 0;
  28977. this.localClippingEnabled = false;
  28978. this.localClipIntersection = false;
  28979. this.planes = [];
  28980. this.parentVersion = 0;
  28981. this.viewNormalMatrix = new Matrix3();
  28982. this.cacheKey = '';
  28983. }
  28984. projectPlanes( source, offset ) {
  28985. const l = source.length;
  28986. const planes = this.planes;
  28987. for ( let i = 0; i < l; i ++ ) {
  28988. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  28989. const v = planes[ offset + i ];
  28990. const normal = _plane.normal;
  28991. v.x = - normal.x;
  28992. v.y = - normal.y;
  28993. v.z = - normal.z;
  28994. v.w = _plane.constant;
  28995. }
  28996. }
  28997. updateGlobal( renderer, camera ) {
  28998. const rendererClippingPlanes = renderer.clippingPlanes;
  28999. this.viewMatrix = camera.matrixWorldInverse;
  29000. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  29001. let update = false;
  29002. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  29003. const l = rendererClippingPlanes.length;
  29004. if ( l !== this.globalClippingCount ) {
  29005. const planes = [];
  29006. for ( let i = 0; i < l; i ++ ) {
  29007. planes.push( new Vector4() );
  29008. }
  29009. this.globalClippingCount = l;
  29010. this.planes = planes;
  29011. update = true;
  29012. }
  29013. this.projectPlanes( rendererClippingPlanes, 0 );
  29014. } else if ( this.globalClippingCount !== 0 ) {
  29015. this.globalClippingCount = 0;
  29016. this.planes = [];
  29017. update = true;
  29018. }
  29019. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  29020. this.localClippingEnabled = renderer.localClippingEnabled;
  29021. update = true;
  29022. }
  29023. if ( update ) {
  29024. this.version ++;
  29025. this.cacheKey = `${ this.globalClippingCount }:${ this.localClippingEnabled === undefined ? false : this.localClippingEnabled }:`;
  29026. }
  29027. }
  29028. update( parent, material ) {
  29029. let update = false;
  29030. if ( this !== parent && parent.version !== this.parentVersion ) {
  29031. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  29032. this.localClippingEnabled = parent.localClippingEnabled;
  29033. this.planes = Array.from( parent.planes );
  29034. this.parentVersion = parent.version;
  29035. this.viewMatrix = parent.viewMatrix;
  29036. this.viewNormalMatrix = parent.viewNormalMatrix;
  29037. update = true;
  29038. }
  29039. if ( this.localClippingEnabled ) {
  29040. const localClippingPlanes = material.clippingPlanes;
  29041. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  29042. const l = localClippingPlanes.length;
  29043. const planes = this.planes;
  29044. const offset = this.globalClippingCount;
  29045. if ( update || l !== this.localClippingCount ) {
  29046. planes.length = offset + l;
  29047. for ( let i = 0; i < l; i ++ ) {
  29048. planes[ offset + i ] = new Vector4();
  29049. }
  29050. this.localClippingCount = l;
  29051. update = true;
  29052. }
  29053. this.projectPlanes( localClippingPlanes, offset );
  29054. } else if ( this.localClippingCount !== 0 ) {
  29055. this.localClippingCount = 0;
  29056. update = true;
  29057. }
  29058. if ( this.localClipIntersection !== material.clipIntersection ) {
  29059. this.localClipIntersection = material.clipIntersection;
  29060. update = true;
  29061. }
  29062. }
  29063. if ( update ) {
  29064. this.version += parent.version;
  29065. this.cacheKey = parent.cacheKey + `:${ this.localClippingCount }:${ this.localClipIntersection === undefined ? false : this.localClipIntersection }`;
  29066. }
  29067. }
  29068. }
  29069. let _id$7 = 0;
  29070. function getKeys( obj ) {
  29071. const keys = Object.keys( obj );
  29072. let proto = Object.getPrototypeOf( obj );
  29073. while ( proto ) {
  29074. const descriptors = Object.getOwnPropertyDescriptors( proto );
  29075. for ( const key in descriptors ) {
  29076. if ( descriptors[ key ] !== undefined ) {
  29077. const descriptor = descriptors[ key ];
  29078. if ( descriptor && typeof descriptor.get === 'function' ) {
  29079. keys.push( key );
  29080. }
  29081. }
  29082. }
  29083. proto = Object.getPrototypeOf( proto );
  29084. }
  29085. return keys;
  29086. }
  29087. class RenderObject {
  29088. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  29089. this._nodes = nodes;
  29090. this._geometries = geometries;
  29091. this.id = _id$7 ++;
  29092. this.renderer = renderer;
  29093. this.object = object;
  29094. this.material = material;
  29095. this.scene = scene;
  29096. this.camera = camera;
  29097. this.lightsNode = lightsNode;
  29098. this.context = renderContext;
  29099. this.geometry = object.geometry;
  29100. this.version = material.version;
  29101. this.drawRange = null;
  29102. this.attributes = null;
  29103. this.pipeline = null;
  29104. this.vertexBuffers = null;
  29105. this.drawParams = null;
  29106. this.bundle = null;
  29107. this.updateClipping( renderContext.clippingContext );
  29108. this.clippingContextVersion = this.clippingContext.version;
  29109. this.initialNodesCacheKey = this.getDynamicCacheKey();
  29110. this.initialCacheKey = this.getCacheKey();
  29111. this._nodeBuilderState = null;
  29112. this._bindings = null;
  29113. this._monitor = null;
  29114. this.onDispose = null;
  29115. this.isRenderObject = true;
  29116. this.onMaterialDispose = () => {
  29117. this.dispose();
  29118. };
  29119. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  29120. }
  29121. updateClipping( parent ) {
  29122. const material = this.material;
  29123. let clippingContext = this.clippingContext;
  29124. if ( Array.isArray( material.clippingPlanes ) ) {
  29125. if ( clippingContext === parent || ! clippingContext ) {
  29126. clippingContext = new ClippingContext();
  29127. this.clippingContext = clippingContext;
  29128. }
  29129. clippingContext.update( parent, material );
  29130. } else if ( this.clippingContext !== parent ) {
  29131. this.clippingContext = parent;
  29132. }
  29133. }
  29134. get clippingNeedsUpdate() {
  29135. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  29136. this.clippingContextVersion = this.clippingContext.version;
  29137. return true;
  29138. }
  29139. getNodeBuilderState() {
  29140. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  29141. }
  29142. getMonitor() {
  29143. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  29144. }
  29145. getBindings() {
  29146. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  29147. }
  29148. getIndex() {
  29149. return this._geometries.getIndex( this );
  29150. }
  29151. getChainArray() {
  29152. return [ this.object, this.material, this.context, this.lightsNode ];
  29153. }
  29154. getAttributes() {
  29155. if ( this.attributes !== null ) return this.attributes;
  29156. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  29157. const geometry = this.geometry;
  29158. const attributes = [];
  29159. const vertexBuffers = new Set();
  29160. for ( const nodeAttribute of nodeAttributes ) {
  29161. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  29162. if ( attribute === undefined ) continue;
  29163. attributes.push( attribute );
  29164. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  29165. vertexBuffers.add( bufferAttribute );
  29166. }
  29167. this.attributes = attributes;
  29168. this.vertexBuffers = Array.from( vertexBuffers.values() );
  29169. return attributes;
  29170. }
  29171. getVertexBuffers() {
  29172. if ( this.vertexBuffers === null ) this.getAttributes();
  29173. return this.vertexBuffers;
  29174. }
  29175. getDrawParameters() {
  29176. const { object, material, geometry, group, drawRange } = this;
  29177. const drawParams = this.drawParams || ( this.drawParams = {
  29178. vertexCount: 0,
  29179. firstVertex: 0,
  29180. instanceCount: 0,
  29181. firstInstance: 0
  29182. } );
  29183. const index = this.getIndex();
  29184. const hasIndex = ( index !== null );
  29185. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  29186. if ( instanceCount === 0 ) return null;
  29187. drawParams.instanceCount = instanceCount;
  29188. if ( object.isBatchedMesh === true ) return drawParams;
  29189. let rangeFactor = 1;
  29190. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  29191. rangeFactor = 2;
  29192. }
  29193. let firstVertex = drawRange.start * rangeFactor;
  29194. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  29195. if ( group !== null ) {
  29196. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  29197. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  29198. }
  29199. const itemCount = hasIndex === true ? index.count : geometry.attributes.position.count;
  29200. firstVertex = Math.max( firstVertex, 0 );
  29201. lastVertex = Math.min( lastVertex, itemCount );
  29202. const count = lastVertex - firstVertex;
  29203. if ( count < 0 || count === Infinity ) return null;
  29204. drawParams.vertexCount = count;
  29205. drawParams.firstVertex = firstVertex;
  29206. return drawParams;
  29207. }
  29208. getGeometryCacheKey() {
  29209. const { geometry } = this;
  29210. let cacheKey = '';
  29211. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  29212. const attribute = geometry.attributes[ name ];
  29213. cacheKey += name + ',';
  29214. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  29215. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  29216. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  29217. if ( attribute.normalized ) cacheKey += 'n,';
  29218. }
  29219. if ( geometry.index ) {
  29220. cacheKey += 'index,';
  29221. }
  29222. return cacheKey;
  29223. }
  29224. getMaterialCacheKey() {
  29225. const { object, material } = this;
  29226. let cacheKey = material.customProgramCacheKey();
  29227. for ( const property of getKeys( material ) ) {
  29228. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  29229. const value = material[ property ];
  29230. let valueKey;
  29231. if ( value !== null ) {
  29232. // some material values require a formatting
  29233. const type = typeof value;
  29234. if ( type === 'number' ) {
  29235. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  29236. } else if ( type === 'object' ) {
  29237. valueKey = '{';
  29238. if ( value.isTexture ) {
  29239. valueKey += value.mapping;
  29240. }
  29241. valueKey += '}';
  29242. } else {
  29243. valueKey = String( value );
  29244. }
  29245. } else {
  29246. valueKey = String( value );
  29247. }
  29248. cacheKey += /*property + ':' +*/ valueKey + ',';
  29249. }
  29250. cacheKey += this.clippingContext.cacheKey + ',';
  29251. if ( object.geometry ) {
  29252. cacheKey += this.getGeometryCacheKey();
  29253. }
  29254. if ( object.skeleton ) {
  29255. cacheKey += object.skeleton.bones.length + ',';
  29256. }
  29257. if ( object.morphTargetInfluences ) {
  29258. cacheKey += object.morphTargetInfluences.length + ',';
  29259. }
  29260. if ( object.isBatchedMesh ) {
  29261. cacheKey += object._matricesTexture.uuid + ',';
  29262. if ( object._colorsTexture !== null ) {
  29263. cacheKey += object._colorsTexture.uuid + ',';
  29264. }
  29265. }
  29266. if ( object.count > 1 ) {
  29267. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  29268. cacheKey += object.uuid + ',';
  29269. }
  29270. return cacheKey;
  29271. }
  29272. get needsUpdate() {
  29273. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  29274. }
  29275. getDynamicCacheKey() {
  29276. // Environment Nodes Cache Key
  29277. return this.object.receiveShadow + ',' + this._nodes.getCacheKey( this.scene, this.lightsNode );
  29278. }
  29279. getCacheKey() {
  29280. return this.getMaterialCacheKey() + ',' + this.getDynamicCacheKey();
  29281. }
  29282. dispose() {
  29283. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  29284. this.onDispose();
  29285. }
  29286. }
  29287. const chainArray = [];
  29288. class RenderObjects {
  29289. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  29290. this.renderer = renderer;
  29291. this.nodes = nodes;
  29292. this.geometries = geometries;
  29293. this.pipelines = pipelines;
  29294. this.bindings = bindings;
  29295. this.info = info;
  29296. this.chainMaps = {};
  29297. }
  29298. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  29299. const chainMap = this.getChainMap( passId );
  29300. // reuse chainArray
  29301. chainArray[ 0 ] = object;
  29302. chainArray[ 1 ] = material;
  29303. chainArray[ 2 ] = renderContext;
  29304. chainArray[ 3 ] = lightsNode;
  29305. let renderObject = chainMap.get( chainArray );
  29306. if ( renderObject === undefined ) {
  29307. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  29308. chainMap.set( chainArray, renderObject );
  29309. } else {
  29310. renderObject.updateClipping( renderContext.clippingContext );
  29311. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  29312. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  29313. renderObject.dispose();
  29314. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  29315. } else {
  29316. renderObject.version = material.version;
  29317. }
  29318. }
  29319. }
  29320. return renderObject;
  29321. }
  29322. getChainMap( passId = 'default' ) {
  29323. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  29324. }
  29325. dispose() {
  29326. this.chainMaps = {};
  29327. }
  29328. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  29329. const chainMap = this.getChainMap( passId );
  29330. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  29331. renderObject.onDispose = () => {
  29332. this.pipelines.delete( renderObject );
  29333. this.bindings.delete( renderObject );
  29334. this.nodes.delete( renderObject );
  29335. chainMap.delete( renderObject.getChainArray() );
  29336. };
  29337. return renderObject;
  29338. }
  29339. }
  29340. class DataMap {
  29341. constructor() {
  29342. this.data = new WeakMap();
  29343. }
  29344. get( object ) {
  29345. let map = this.data.get( object );
  29346. if ( map === undefined ) {
  29347. map = {};
  29348. this.data.set( object, map );
  29349. }
  29350. return map;
  29351. }
  29352. delete( object ) {
  29353. let map;
  29354. if ( this.data.has( object ) ) {
  29355. map = this.data.get( object );
  29356. this.data.delete( object );
  29357. }
  29358. return map;
  29359. }
  29360. has( object ) {
  29361. return this.data.has( object );
  29362. }
  29363. dispose() {
  29364. this.data = new WeakMap();
  29365. }
  29366. }
  29367. const AttributeType = {
  29368. VERTEX: 1,
  29369. INDEX: 2,
  29370. STORAGE: 4
  29371. };
  29372. // size of a chunk in bytes (STD140 layout)
  29373. const GPU_CHUNK_BYTES = 16;
  29374. // @TODO: Move to src/constants.js
  29375. const BlendColorFactor = 211;
  29376. const OneMinusBlendColorFactor = 212;
  29377. class Attributes extends DataMap {
  29378. constructor( backend ) {
  29379. super();
  29380. this.backend = backend;
  29381. }
  29382. delete( attribute ) {
  29383. const attributeData = super.delete( attribute );
  29384. if ( attributeData !== undefined ) {
  29385. this.backend.destroyAttribute( attribute );
  29386. }
  29387. return attributeData;
  29388. }
  29389. update( attribute, type ) {
  29390. const data = this.get( attribute );
  29391. if ( data.version === undefined ) {
  29392. if ( type === AttributeType.VERTEX ) {
  29393. this.backend.createAttribute( attribute );
  29394. } else if ( type === AttributeType.INDEX ) {
  29395. this.backend.createIndexAttribute( attribute );
  29396. } else if ( type === AttributeType.STORAGE ) {
  29397. this.backend.createStorageAttribute( attribute );
  29398. }
  29399. data.version = this._getBufferAttribute( attribute ).version;
  29400. } else {
  29401. const bufferAttribute = this._getBufferAttribute( attribute );
  29402. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  29403. this.backend.updateAttribute( attribute );
  29404. data.version = bufferAttribute.version;
  29405. }
  29406. }
  29407. }
  29408. _getBufferAttribute( attribute ) {
  29409. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  29410. return attribute;
  29411. }
  29412. }
  29413. function arrayNeedsUint32( array ) {
  29414. // assumes larger values usually on last
  29415. for ( let i = array.length - 1; i >= 0; -- i ) {
  29416. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  29417. }
  29418. return false;
  29419. }
  29420. function getWireframeVersion( geometry ) {
  29421. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  29422. }
  29423. function getWireframeIndex( geometry ) {
  29424. const indices = [];
  29425. const geometryIndex = geometry.index;
  29426. const geometryPosition = geometry.attributes.position;
  29427. if ( geometryIndex !== null ) {
  29428. const array = geometryIndex.array;
  29429. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  29430. const a = array[ i + 0 ];
  29431. const b = array[ i + 1 ];
  29432. const c = array[ i + 2 ];
  29433. indices.push( a, b, b, c, c, a );
  29434. }
  29435. } else {
  29436. const array = geometryPosition.array;
  29437. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  29438. const a = i + 0;
  29439. const b = i + 1;
  29440. const c = i + 2;
  29441. indices.push( a, b, b, c, c, a );
  29442. }
  29443. }
  29444. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  29445. attribute.version = getWireframeVersion( geometry );
  29446. return attribute;
  29447. }
  29448. class Geometries extends DataMap {
  29449. constructor( attributes, info ) {
  29450. super();
  29451. this.attributes = attributes;
  29452. this.info = info;
  29453. this.wireframes = new WeakMap();
  29454. this.attributeCall = new WeakMap();
  29455. }
  29456. has( renderObject ) {
  29457. const geometry = renderObject.geometry;
  29458. return super.has( geometry ) && this.get( geometry ).initialized === true;
  29459. }
  29460. updateForRender( renderObject ) {
  29461. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  29462. this.updateAttributes( renderObject );
  29463. }
  29464. initGeometry( renderObject ) {
  29465. const geometry = renderObject.geometry;
  29466. const geometryData = this.get( geometry );
  29467. geometryData.initialized = true;
  29468. this.info.memory.geometries ++;
  29469. const onDispose = () => {
  29470. this.info.memory.geometries --;
  29471. const index = geometry.index;
  29472. const geometryAttributes = renderObject.getAttributes();
  29473. if ( index !== null ) {
  29474. this.attributes.delete( index );
  29475. }
  29476. for ( const geometryAttribute of geometryAttributes ) {
  29477. this.attributes.delete( geometryAttribute );
  29478. }
  29479. const wireframeAttribute = this.wireframes.get( geometry );
  29480. if ( wireframeAttribute !== undefined ) {
  29481. this.attributes.delete( wireframeAttribute );
  29482. }
  29483. geometry.removeEventListener( 'dispose', onDispose );
  29484. };
  29485. geometry.addEventListener( 'dispose', onDispose );
  29486. }
  29487. updateAttributes( renderObject ) {
  29488. const attributes = renderObject.getAttributes();
  29489. for ( const attribute of attributes ) {
  29490. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  29491. this.updateAttribute( attribute, AttributeType.STORAGE );
  29492. } else {
  29493. this.updateAttribute( attribute, AttributeType.VERTEX );
  29494. }
  29495. }
  29496. const index = this.getIndex( renderObject );
  29497. if ( index !== null ) {
  29498. this.updateAttribute( index, AttributeType.INDEX );
  29499. }
  29500. }
  29501. updateAttribute( attribute, type ) {
  29502. const callId = this.info.render.calls;
  29503. if ( ! attribute.isInterleavedBufferAttribute ) {
  29504. if ( this.attributeCall.get( attribute ) !== callId ) {
  29505. this.attributes.update( attribute, type );
  29506. this.attributeCall.set( attribute, callId );
  29507. }
  29508. } else {
  29509. if ( this.attributeCall.get( attribute ) === undefined ) {
  29510. this.attributes.update( attribute, type );
  29511. this.attributeCall.set( attribute, callId );
  29512. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  29513. this.attributes.update( attribute, type );
  29514. this.attributeCall.set( attribute.data, callId );
  29515. this.attributeCall.set( attribute, callId );
  29516. }
  29517. }
  29518. }
  29519. getIndex( renderObject ) {
  29520. const { geometry, material } = renderObject;
  29521. let index = geometry.index;
  29522. if ( material.wireframe === true ) {
  29523. const wireframes = this.wireframes;
  29524. let wireframeAttribute = wireframes.get( geometry );
  29525. if ( wireframeAttribute === undefined ) {
  29526. wireframeAttribute = getWireframeIndex( geometry );
  29527. wireframes.set( geometry, wireframeAttribute );
  29528. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  29529. this.attributes.delete( wireframeAttribute );
  29530. wireframeAttribute = getWireframeIndex( geometry );
  29531. wireframes.set( geometry, wireframeAttribute );
  29532. }
  29533. index = wireframeAttribute;
  29534. }
  29535. return index;
  29536. }
  29537. }
  29538. class Info {
  29539. constructor() {
  29540. this.autoReset = true;
  29541. this.frame = 0;
  29542. this.calls = 0;
  29543. this.render = {
  29544. calls: 0,
  29545. frameCalls: 0,
  29546. drawCalls: 0,
  29547. triangles: 0,
  29548. points: 0,
  29549. lines: 0,
  29550. timestamp: 0,
  29551. previousFrameCalls: 0,
  29552. timestampCalls: 0
  29553. };
  29554. this.compute = {
  29555. calls: 0,
  29556. frameCalls: 0,
  29557. timestamp: 0,
  29558. previousFrameCalls: 0,
  29559. timestampCalls: 0
  29560. };
  29561. this.memory = {
  29562. geometries: 0,
  29563. textures: 0
  29564. };
  29565. }
  29566. update( object, count, instanceCount ) {
  29567. this.render.drawCalls ++;
  29568. if ( object.isMesh || object.isSprite ) {
  29569. this.render.triangles += instanceCount * ( count / 3 );
  29570. } else if ( object.isPoints ) {
  29571. this.render.points += instanceCount * count;
  29572. } else if ( object.isLineSegments ) {
  29573. this.render.lines += instanceCount * ( count / 2 );
  29574. } else if ( object.isLine ) {
  29575. this.render.lines += instanceCount * ( count - 1 );
  29576. } else {
  29577. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  29578. }
  29579. }
  29580. updateTimestamp( type, time ) {
  29581. if ( this[ type ].timestampCalls === 0 ) {
  29582. this[ type ].timestamp = 0;
  29583. }
  29584. this[ type ].timestamp += time;
  29585. this[ type ].timestampCalls ++;
  29586. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  29587. this[ type ].timestampCalls = 0;
  29588. }
  29589. }
  29590. reset() {
  29591. const previousRenderFrameCalls = this.render.frameCalls;
  29592. this.render.previousFrameCalls = previousRenderFrameCalls;
  29593. const previousComputeFrameCalls = this.compute.frameCalls;
  29594. this.compute.previousFrameCalls = previousComputeFrameCalls;
  29595. this.render.drawCalls = 0;
  29596. this.render.frameCalls = 0;
  29597. this.compute.frameCalls = 0;
  29598. this.render.triangles = 0;
  29599. this.render.points = 0;
  29600. this.render.lines = 0;
  29601. }
  29602. dispose() {
  29603. this.reset();
  29604. this.calls = 0;
  29605. this.render.calls = 0;
  29606. this.compute.calls = 0;
  29607. this.render.timestamp = 0;
  29608. this.compute.timestamp = 0;
  29609. this.memory.geometries = 0;
  29610. this.memory.textures = 0;
  29611. }
  29612. }
  29613. class Pipeline {
  29614. constructor( cacheKey ) {
  29615. this.cacheKey = cacheKey;
  29616. this.usedTimes = 0;
  29617. }
  29618. }
  29619. class RenderPipeline extends Pipeline {
  29620. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  29621. super( cacheKey );
  29622. this.vertexProgram = vertexProgram;
  29623. this.fragmentProgram = fragmentProgram;
  29624. }
  29625. }
  29626. class ComputePipeline extends Pipeline {
  29627. constructor( cacheKey, computeProgram ) {
  29628. super( cacheKey );
  29629. this.computeProgram = computeProgram;
  29630. this.isComputePipeline = true;
  29631. }
  29632. }
  29633. let _id$6 = 0;
  29634. class ProgrammableStage {
  29635. constructor( code, type, transforms = null, attributes = null ) {
  29636. this.id = _id$6 ++;
  29637. this.code = code;
  29638. this.stage = type;
  29639. this.transforms = transforms;
  29640. this.attributes = attributes;
  29641. this.usedTimes = 0;
  29642. }
  29643. }
  29644. class Pipelines extends DataMap {
  29645. constructor( backend, nodes ) {
  29646. super();
  29647. this.backend = backend;
  29648. this.nodes = nodes;
  29649. this.bindings = null; // set by the bindings
  29650. this.caches = new Map();
  29651. this.programs = {
  29652. vertex: new Map(),
  29653. fragment: new Map(),
  29654. compute: new Map()
  29655. };
  29656. }
  29657. getForCompute( computeNode, bindings ) {
  29658. const { backend } = this;
  29659. const data = this.get( computeNode );
  29660. if ( this._needsComputeUpdate( computeNode ) ) {
  29661. const previousPipeline = data.pipeline;
  29662. if ( previousPipeline ) {
  29663. previousPipeline.usedTimes --;
  29664. previousPipeline.computeProgram.usedTimes --;
  29665. }
  29666. // get shader
  29667. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  29668. // programmable stage
  29669. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  29670. if ( stageCompute === undefined ) {
  29671. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  29672. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  29673. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  29674. backend.createProgram( stageCompute );
  29675. }
  29676. // determine compute pipeline
  29677. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  29678. let pipeline = this.caches.get( cacheKey );
  29679. if ( pipeline === undefined ) {
  29680. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  29681. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  29682. }
  29683. // keep track of all used times
  29684. pipeline.usedTimes ++;
  29685. stageCompute.usedTimes ++;
  29686. //
  29687. data.version = computeNode.version;
  29688. data.pipeline = pipeline;
  29689. }
  29690. return data.pipeline;
  29691. }
  29692. getForRender( renderObject, promises = null ) {
  29693. const { backend } = this;
  29694. const data = this.get( renderObject );
  29695. if ( this._needsRenderUpdate( renderObject ) ) {
  29696. const previousPipeline = data.pipeline;
  29697. if ( previousPipeline ) {
  29698. previousPipeline.usedTimes --;
  29699. previousPipeline.vertexProgram.usedTimes --;
  29700. previousPipeline.fragmentProgram.usedTimes --;
  29701. }
  29702. // get shader
  29703. const nodeBuilderState = renderObject.getNodeBuilderState();
  29704. // programmable stages
  29705. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  29706. if ( stageVertex === undefined ) {
  29707. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  29708. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  29709. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  29710. backend.createProgram( stageVertex );
  29711. }
  29712. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  29713. if ( stageFragment === undefined ) {
  29714. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  29715. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  29716. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  29717. backend.createProgram( stageFragment );
  29718. }
  29719. // determine render pipeline
  29720. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  29721. let pipeline = this.caches.get( cacheKey );
  29722. if ( pipeline === undefined ) {
  29723. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  29724. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  29725. } else {
  29726. renderObject.pipeline = pipeline;
  29727. }
  29728. // keep track of all used times
  29729. pipeline.usedTimes ++;
  29730. stageVertex.usedTimes ++;
  29731. stageFragment.usedTimes ++;
  29732. //
  29733. data.pipeline = pipeline;
  29734. }
  29735. return data.pipeline;
  29736. }
  29737. delete( object ) {
  29738. const pipeline = this.get( object ).pipeline;
  29739. if ( pipeline ) {
  29740. // pipeline
  29741. pipeline.usedTimes --;
  29742. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  29743. // programs
  29744. if ( pipeline.isComputePipeline ) {
  29745. pipeline.computeProgram.usedTimes --;
  29746. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  29747. } else {
  29748. pipeline.fragmentProgram.usedTimes --;
  29749. pipeline.vertexProgram.usedTimes --;
  29750. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  29751. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  29752. }
  29753. }
  29754. return super.delete( object );
  29755. }
  29756. dispose() {
  29757. super.dispose();
  29758. this.caches = new Map();
  29759. this.programs = {
  29760. vertex: new Map(),
  29761. fragment: new Map(),
  29762. compute: new Map()
  29763. };
  29764. }
  29765. updateForRender( renderObject ) {
  29766. this.getForRender( renderObject );
  29767. }
  29768. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  29769. // check for existing pipeline
  29770. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  29771. let pipeline = this.caches.get( cacheKey );
  29772. if ( pipeline === undefined ) {
  29773. pipeline = new ComputePipeline( cacheKey, stageCompute );
  29774. this.caches.set( cacheKey, pipeline );
  29775. this.backend.createComputePipeline( pipeline, bindings );
  29776. }
  29777. return pipeline;
  29778. }
  29779. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  29780. // check for existing pipeline
  29781. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  29782. let pipeline = this.caches.get( cacheKey );
  29783. if ( pipeline === undefined ) {
  29784. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  29785. this.caches.set( cacheKey, pipeline );
  29786. renderObject.pipeline = pipeline;
  29787. this.backend.createRenderPipeline( renderObject, promises );
  29788. }
  29789. return pipeline;
  29790. }
  29791. _getComputeCacheKey( computeNode, stageCompute ) {
  29792. return computeNode.id + ',' + stageCompute.id;
  29793. }
  29794. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  29795. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  29796. }
  29797. _releasePipeline( pipeline ) {
  29798. this.caches.delete( pipeline.cacheKey );
  29799. }
  29800. _releaseProgram( program ) {
  29801. const code = program.code;
  29802. const stage = program.stage;
  29803. this.programs[ stage ].delete( code );
  29804. }
  29805. _needsComputeUpdate( computeNode ) {
  29806. const data = this.get( computeNode );
  29807. return data.pipeline === undefined || data.version !== computeNode.version;
  29808. }
  29809. _needsRenderUpdate( renderObject ) {
  29810. const data = this.get( renderObject );
  29811. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  29812. }
  29813. }
  29814. class Bindings extends DataMap {
  29815. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  29816. super();
  29817. this.backend = backend;
  29818. this.textures = textures;
  29819. this.pipelines = pipelines;
  29820. this.attributes = attributes;
  29821. this.nodes = nodes;
  29822. this.info = info;
  29823. this.pipelines.bindings = this; // assign bindings to pipelines
  29824. }
  29825. getForRender( renderObject ) {
  29826. const bindings = renderObject.getBindings();
  29827. for ( const bindGroup of bindings ) {
  29828. const groupData = this.get( bindGroup );
  29829. if ( groupData.bindGroup === undefined ) {
  29830. // each object defines an array of bindings (ubos, textures, samplers etc.)
  29831. this._init( bindGroup );
  29832. this.backend.createBindings( bindGroup, bindings );
  29833. groupData.bindGroup = bindGroup;
  29834. }
  29835. }
  29836. return bindings;
  29837. }
  29838. getForCompute( computeNode ) {
  29839. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  29840. for ( const bindGroup of bindings ) {
  29841. const groupData = this.get( bindGroup );
  29842. if ( groupData.bindGroup === undefined ) {
  29843. this._init( bindGroup );
  29844. this.backend.createBindings( bindGroup, bindings );
  29845. groupData.bindGroup = bindGroup;
  29846. }
  29847. }
  29848. return bindings;
  29849. }
  29850. updateForCompute( computeNode ) {
  29851. this._updateBindings( this.getForCompute( computeNode ) );
  29852. }
  29853. updateForRender( renderObject ) {
  29854. this._updateBindings( this.getForRender( renderObject ) );
  29855. }
  29856. _updateBindings( bindings ) {
  29857. for ( const bindGroup of bindings ) {
  29858. this._update( bindGroup, bindings );
  29859. }
  29860. }
  29861. _init( bindGroup ) {
  29862. for ( const binding of bindGroup.bindings ) {
  29863. if ( binding.isSampledTexture ) {
  29864. this.textures.updateTexture( binding.texture );
  29865. } else if ( binding.isStorageBuffer ) {
  29866. const attribute = binding.attribute;
  29867. this.attributes.update( attribute, AttributeType.STORAGE );
  29868. }
  29869. }
  29870. }
  29871. _update( bindGroup, bindings ) {
  29872. const { backend } = this;
  29873. let needsBindingsUpdate = false;
  29874. // iterate over all bindings and check if buffer updates or a new binding group is required
  29875. for ( const binding of bindGroup.bindings ) {
  29876. if ( binding.isNodeUniformsGroup ) {
  29877. const updated = this.nodes.updateGroup( binding );
  29878. if ( ! updated ) continue;
  29879. }
  29880. if ( binding.isUniformBuffer ) {
  29881. const updated = binding.update();
  29882. if ( updated ) {
  29883. backend.updateBinding( binding );
  29884. }
  29885. } else if ( binding.isSampler ) {
  29886. binding.update();
  29887. } else if ( binding.isSampledTexture ) {
  29888. if ( binding.needsBindingsUpdate( this.textures.get( binding.texture ).generation ) ) needsBindingsUpdate = true;
  29889. const updated = binding.update();
  29890. const texture = binding.texture;
  29891. if ( updated ) {
  29892. this.textures.updateTexture( texture );
  29893. }
  29894. const textureData = backend.get( texture );
  29895. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  29896. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  29897. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  29898. this.textures.updateTexture( texture );
  29899. needsBindingsUpdate = true;
  29900. }
  29901. if ( texture.isStorageTexture === true ) {
  29902. const textureData = this.get( texture );
  29903. if ( binding.store === true ) {
  29904. textureData.needsMipmap = true;
  29905. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  29906. this.backend.generateMipmaps( texture );
  29907. textureData.needsMipmap = false;
  29908. }
  29909. }
  29910. }
  29911. }
  29912. if ( needsBindingsUpdate === true ) {
  29913. this.backend.updateBindings( bindGroup, bindings );
  29914. }
  29915. }
  29916. }
  29917. class NodeAttribute {
  29918. constructor( name, type, node = null ) {
  29919. this.isNodeAttribute = true;
  29920. this.name = name;
  29921. this.type = type;
  29922. this.node = node;
  29923. }
  29924. }
  29925. class NodeUniform {
  29926. constructor( name, type, node ) {
  29927. this.isNodeUniform = true;
  29928. this.name = name;
  29929. this.type = type;
  29930. this.node = node.getSelf();
  29931. }
  29932. get value() {
  29933. return this.node.value;
  29934. }
  29935. set value( val ) {
  29936. this.node.value = val;
  29937. }
  29938. get id() {
  29939. return this.node.id;
  29940. }
  29941. get groupNode() {
  29942. return this.node.groupNode;
  29943. }
  29944. }
  29945. class NodeVar {
  29946. constructor( name, type ) {
  29947. this.isNodeVar = true;
  29948. this.name = name;
  29949. this.type = type;
  29950. }
  29951. }
  29952. class NodeVarying extends NodeVar {
  29953. constructor( name, type ) {
  29954. super( name, type );
  29955. this.needsInterpolation = false;
  29956. this.isNodeVarying = true;
  29957. }
  29958. }
  29959. class NodeCode {
  29960. constructor( name, type, code = '' ) {
  29961. this.name = name;
  29962. this.type = type;
  29963. this.code = code;
  29964. Object.defineProperty( this, 'isNodeCode', { value: true } );
  29965. }
  29966. }
  29967. let id$1 = 0;
  29968. class NodeCache {
  29969. constructor( parent = null ) {
  29970. this.id = id$1 ++;
  29971. this.nodesData = new WeakMap();
  29972. this.parent = parent;
  29973. }
  29974. getData( node ) {
  29975. let data = this.nodesData.get( node );
  29976. if ( data === undefined && this.parent !== null ) {
  29977. data = this.parent.getData( node );
  29978. }
  29979. return data;
  29980. }
  29981. setData( node, data ) {
  29982. this.nodesData.set( node, data );
  29983. }
  29984. }
  29985. class ParameterNode extends PropertyNode {
  29986. static get type() {
  29987. return 'ParameterNode';
  29988. }
  29989. constructor( nodeType, name = null ) {
  29990. super( nodeType, name );
  29991. this.isParameterNode = true;
  29992. }
  29993. getHash() {
  29994. return this.uuid;
  29995. }
  29996. generate() {
  29997. return this.name;
  29998. }
  29999. }
  30000. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  30001. class CodeNode extends Node {
  30002. static get type() {
  30003. return 'CodeNode';
  30004. }
  30005. constructor( code = '', includes = [], language = '' ) {
  30006. super( 'code' );
  30007. this.isCodeNode = true;
  30008. this.code = code;
  30009. this.language = language;
  30010. this.includes = includes;
  30011. }
  30012. isGlobal() {
  30013. return true;
  30014. }
  30015. setIncludes( includes ) {
  30016. this.includes = includes;
  30017. return this;
  30018. }
  30019. getIncludes( /*builder*/ ) {
  30020. return this.includes;
  30021. }
  30022. generate( builder ) {
  30023. const includes = this.getIncludes( builder );
  30024. for ( const include of includes ) {
  30025. include.build( builder );
  30026. }
  30027. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  30028. nodeCode.code = this.code;
  30029. return nodeCode.code;
  30030. }
  30031. serialize( data ) {
  30032. super.serialize( data );
  30033. data.code = this.code;
  30034. data.language = this.language;
  30035. }
  30036. deserialize( data ) {
  30037. super.deserialize( data );
  30038. this.code = data.code;
  30039. this.language = data.language;
  30040. }
  30041. }
  30042. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  30043. const js = ( src, includes ) => code( src, includes, 'js' );
  30044. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  30045. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  30046. class FunctionNode extends CodeNode {
  30047. static get type() {
  30048. return 'FunctionNode';
  30049. }
  30050. constructor( code = '', includes = [], language = '' ) {
  30051. super( code, includes, language );
  30052. }
  30053. getNodeType( builder ) {
  30054. return this.getNodeFunction( builder ).type;
  30055. }
  30056. getInputs( builder ) {
  30057. return this.getNodeFunction( builder ).inputs;
  30058. }
  30059. getNodeFunction( builder ) {
  30060. const nodeData = builder.getDataFromNode( this );
  30061. let nodeFunction = nodeData.nodeFunction;
  30062. if ( nodeFunction === undefined ) {
  30063. nodeFunction = builder.parser.parseFunction( this.code );
  30064. nodeData.nodeFunction = nodeFunction;
  30065. }
  30066. return nodeFunction;
  30067. }
  30068. generate( builder, output ) {
  30069. super.generate( builder );
  30070. const nodeFunction = this.getNodeFunction( builder );
  30071. const name = nodeFunction.name;
  30072. const type = nodeFunction.type;
  30073. const nodeCode = builder.getCodeFromNode( this, type );
  30074. if ( name !== '' ) {
  30075. // use a custom property name
  30076. nodeCode.name = name;
  30077. }
  30078. const propertyName = builder.getPropertyName( nodeCode );
  30079. const code = this.getNodeFunction( builder ).getCode( propertyName );
  30080. nodeCode.code = code + '\n';
  30081. if ( output === 'property' ) {
  30082. return propertyName;
  30083. } else {
  30084. return builder.format( `${ propertyName }()`, type, output );
  30085. }
  30086. }
  30087. }
  30088. const nativeFn = ( code, includes = [], language = '' ) => {
  30089. for ( let i = 0; i < includes.length; i ++ ) {
  30090. const include = includes[ i ];
  30091. // TSL Function: glslFn, wgslFn
  30092. if ( typeof include === 'function' ) {
  30093. includes[ i ] = include.functionNode;
  30094. }
  30095. }
  30096. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  30097. const fn = ( ...params ) => functionNode.call( ...params );
  30098. fn.functionNode = functionNode;
  30099. return fn;
  30100. };
  30101. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  30102. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  30103. class Uniform {
  30104. constructor( name, value ) {
  30105. this.name = name;
  30106. this.value = value;
  30107. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  30108. this.itemSize = 0;
  30109. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  30110. }
  30111. setValue( value ) {
  30112. this.value = value;
  30113. }
  30114. getValue() {
  30115. return this.value;
  30116. }
  30117. }
  30118. class NumberUniform extends Uniform {
  30119. constructor( name, value = 0 ) {
  30120. super( name, value );
  30121. this.isNumberUniform = true;
  30122. this.boundary = 4;
  30123. this.itemSize = 1;
  30124. }
  30125. }
  30126. class Vector2Uniform extends Uniform {
  30127. constructor( name, value = new Vector2() ) {
  30128. super( name, value );
  30129. this.isVector2Uniform = true;
  30130. this.boundary = 8;
  30131. this.itemSize = 2;
  30132. }
  30133. }
  30134. class Vector3Uniform extends Uniform {
  30135. constructor( name, value = new Vector3() ) {
  30136. super( name, value );
  30137. this.isVector3Uniform = true;
  30138. this.boundary = 16;
  30139. this.itemSize = 3;
  30140. }
  30141. }
  30142. class Vector4Uniform extends Uniform {
  30143. constructor( name, value = new Vector4() ) {
  30144. super( name, value );
  30145. this.isVector4Uniform = true;
  30146. this.boundary = 16;
  30147. this.itemSize = 4;
  30148. }
  30149. }
  30150. class ColorUniform extends Uniform {
  30151. constructor( name, value = new Color() ) {
  30152. super( name, value );
  30153. this.isColorUniform = true;
  30154. this.boundary = 16;
  30155. this.itemSize = 3;
  30156. }
  30157. }
  30158. class Matrix3Uniform extends Uniform {
  30159. constructor( name, value = new Matrix3() ) {
  30160. super( name, value );
  30161. this.isMatrix3Uniform = true;
  30162. this.boundary = 48;
  30163. this.itemSize = 12;
  30164. }
  30165. }
  30166. class Matrix4Uniform extends Uniform {
  30167. constructor( name, value = new Matrix4() ) {
  30168. super( name, value );
  30169. this.isMatrix4Uniform = true;
  30170. this.boundary = 64;
  30171. this.itemSize = 16;
  30172. }
  30173. }
  30174. class NumberNodeUniform extends NumberUniform {
  30175. constructor( nodeUniform ) {
  30176. super( nodeUniform.name, nodeUniform.value );
  30177. this.nodeUniform = nodeUniform;
  30178. }
  30179. getValue() {
  30180. return this.nodeUniform.value;
  30181. }
  30182. }
  30183. class Vector2NodeUniform extends Vector2Uniform {
  30184. constructor( nodeUniform ) {
  30185. super( nodeUniform.name, nodeUniform.value );
  30186. this.nodeUniform = nodeUniform;
  30187. }
  30188. getValue() {
  30189. return this.nodeUniform.value;
  30190. }
  30191. }
  30192. class Vector3NodeUniform extends Vector3Uniform {
  30193. constructor( nodeUniform ) {
  30194. super( nodeUniform.name, nodeUniform.value );
  30195. this.nodeUniform = nodeUniform;
  30196. }
  30197. getValue() {
  30198. return this.nodeUniform.value;
  30199. }
  30200. }
  30201. class Vector4NodeUniform extends Vector4Uniform {
  30202. constructor( nodeUniform ) {
  30203. super( nodeUniform.name, nodeUniform.value );
  30204. this.nodeUniform = nodeUniform;
  30205. }
  30206. getValue() {
  30207. return this.nodeUniform.value;
  30208. }
  30209. }
  30210. class ColorNodeUniform extends ColorUniform {
  30211. constructor( nodeUniform ) {
  30212. super( nodeUniform.name, nodeUniform.value );
  30213. this.nodeUniform = nodeUniform;
  30214. }
  30215. getValue() {
  30216. return this.nodeUniform.value;
  30217. }
  30218. }
  30219. class Matrix3NodeUniform extends Matrix3Uniform {
  30220. constructor( nodeUniform ) {
  30221. super( nodeUniform.name, nodeUniform.value );
  30222. this.nodeUniform = nodeUniform;
  30223. }
  30224. getValue() {
  30225. return this.nodeUniform.value;
  30226. }
  30227. }
  30228. class Matrix4NodeUniform extends Matrix4Uniform {
  30229. constructor( nodeUniform ) {
  30230. super( nodeUniform.name, nodeUniform.value );
  30231. this.nodeUniform = nodeUniform;
  30232. }
  30233. getValue() {
  30234. return this.nodeUniform.value;
  30235. }
  30236. }
  30237. class StackNode extends Node {
  30238. static get type() {
  30239. return 'StackNode';
  30240. }
  30241. constructor( parent = null ) {
  30242. super();
  30243. this.nodes = [];
  30244. this.outputNode = null;
  30245. this.parent = parent;
  30246. this._currentCond = null;
  30247. this.isStackNode = true;
  30248. }
  30249. getNodeType( builder ) {
  30250. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  30251. }
  30252. add( node ) {
  30253. this.nodes.push( node );
  30254. return this;
  30255. }
  30256. If( boolNode, method ) {
  30257. const methodNode = new ShaderNode( method );
  30258. this._currentCond = select( boolNode, methodNode );
  30259. return this.add( this._currentCond );
  30260. }
  30261. ElseIf( boolNode, method ) {
  30262. const methodNode = new ShaderNode( method );
  30263. const ifNode = select( boolNode, methodNode );
  30264. this._currentCond.elseNode = ifNode;
  30265. this._currentCond = ifNode;
  30266. return this;
  30267. }
  30268. Else( method ) {
  30269. this._currentCond.elseNode = new ShaderNode( method );
  30270. return this;
  30271. }
  30272. build( builder, ...params ) {
  30273. const previousStack = getCurrentStack();
  30274. setCurrentStack( this );
  30275. for ( const node of this.nodes ) {
  30276. node.build( builder, 'void' );
  30277. }
  30278. setCurrentStack( previousStack );
  30279. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  30280. }
  30281. //
  30282. else( ...params ) { // @deprecated, r168
  30283. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  30284. return this.Else( ...params );
  30285. }
  30286. elseif( ...params ) { // @deprecated, r168
  30287. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  30288. return this.ElseIf( ...params );
  30289. }
  30290. }
  30291. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  30292. const LOD_MIN = 4;
  30293. // The standard deviations (radians) associated with the extra mips. These are
  30294. // chosen to approximate a Trowbridge-Reitz distribution function times the
  30295. // geometric shadowing function. These sigma values squared must match the
  30296. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  30297. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  30298. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  30299. // samples and exit early, but not recompile the shader.
  30300. const MAX_SAMPLES = 20;
  30301. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  30302. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  30303. const _clearColor$2 = /*@__PURE__*/ new Color();
  30304. let _oldTarget = null;
  30305. let _oldActiveCubeFace = 0;
  30306. let _oldActiveMipmapLevel = 0;
  30307. // Golden Ratio
  30308. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  30309. const INV_PHI = 1 / PHI;
  30310. // Vertices of a dodecahedron (except the opposites, which represent the
  30311. // same axis), used as axis directions evenly spread on a sphere.
  30312. const _axisDirections = [
  30313. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  30314. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  30315. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  30316. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  30317. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  30318. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  30319. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  30320. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  30321. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  30322. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  30323. ];
  30324. //
  30325. // WebGPU Face indices
  30326. const _faceLib = [
  30327. 3, 1, 5,
  30328. 0, 4, 2
  30329. ];
  30330. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  30331. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  30332. /**
  30333. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  30334. * (PMREM) from a cubeMap environment texture. This allows different levels of
  30335. * blur to be quickly accessed based on material roughness. It is packed into a
  30336. * special CubeUV format that allows us to perform custom interpolation so that
  30337. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  30338. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  30339. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  30340. * higher roughness levels. In this way we maintain resolution to smoothly
  30341. * interpolate diffuse lighting while limiting sampling computation.
  30342. *
  30343. * Paper: Fast, Accurate Image-Based Lighting
  30344. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  30345. */
  30346. class PMREMGenerator {
  30347. constructor( renderer ) {
  30348. this._renderer = renderer;
  30349. this._pingPongRenderTarget = null;
  30350. this._lodMax = 0;
  30351. this._cubeSize = 0;
  30352. this._lodPlanes = [];
  30353. this._sizeLods = [];
  30354. this._sigmas = [];
  30355. this._lodMeshes = [];
  30356. this._blurMaterial = null;
  30357. this._cubemapMaterial = null;
  30358. this._equirectMaterial = null;
  30359. this._backgroundBox = null;
  30360. }
  30361. /**
  30362. * Generates a PMREM from a supplied Scene, which can be faster than using an
  30363. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  30364. * in radians to be applied to the scene before PMREM generation. Optional near
  30365. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  30366. * is placed at the origin).
  30367. */
  30368. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  30369. _oldTarget = this._renderer.getRenderTarget();
  30370. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  30371. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  30372. this._setSize( 256 );
  30373. const cubeUVRenderTarget = this._allocateTargets();
  30374. cubeUVRenderTarget.depthBuffer = true;
  30375. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  30376. if ( sigma > 0 ) {
  30377. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  30378. }
  30379. this._applyPMREM( cubeUVRenderTarget );
  30380. this._cleanup( cubeUVRenderTarget );
  30381. return cubeUVRenderTarget;
  30382. }
  30383. /**
  30384. * Generates a PMREM from an equirectangular texture, which can be either LDR
  30385. * or HDR. The ideal input image size is 1k (1024 x 512),
  30386. * as this matches best with the 256 x 256 cubemap output.
  30387. */
  30388. fromEquirectangular( equirectangular, renderTarget = null ) {
  30389. return this._fromTexture( equirectangular, renderTarget );
  30390. }
  30391. /**
  30392. * Generates a PMREM from an cubemap texture, which can be either LDR
  30393. * or HDR. The ideal input cube size is 256 x 256,
  30394. * as this matches best with the 256 x 256 cubemap output.
  30395. */
  30396. fromCubemap( cubemap, renderTarget = null ) {
  30397. return this._fromTexture( cubemap, renderTarget );
  30398. }
  30399. /**
  30400. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  30401. * your texture's network fetch for increased concurrency.
  30402. */
  30403. async compileCubemapShader() {
  30404. if ( this._cubemapMaterial === null ) {
  30405. this._cubemapMaterial = _getCubemapMaterial();
  30406. await this._compileMaterial( this._cubemapMaterial );
  30407. }
  30408. }
  30409. /**
  30410. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  30411. * your texture's network fetch for increased concurrency.
  30412. */
  30413. async compileEquirectangularShader() {
  30414. if ( this._equirectMaterial === null ) {
  30415. this._equirectMaterial = _getEquirectMaterial();
  30416. await this._compileMaterial( this._equirectMaterial );
  30417. }
  30418. }
  30419. /**
  30420. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  30421. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  30422. * one of them will cause any others to also become unusable.
  30423. */
  30424. dispose() {
  30425. this._dispose();
  30426. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  30427. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  30428. if ( this._backgroundBox !== null ) {
  30429. this._backgroundBox.geometry.dispose();
  30430. this._backgroundBox.material.dispose();
  30431. }
  30432. }
  30433. // private interface
  30434. _setSize( cubeSize ) {
  30435. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  30436. this._cubeSize = Math.pow( 2, this._lodMax );
  30437. }
  30438. _dispose() {
  30439. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  30440. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  30441. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  30442. this._lodPlanes[ i ].dispose();
  30443. }
  30444. }
  30445. _cleanup( outputTarget ) {
  30446. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  30447. outputTarget.scissorTest = false;
  30448. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  30449. }
  30450. _fromTexture( texture, renderTarget ) {
  30451. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  30452. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  30453. } else { // Equirectangular
  30454. this._setSize( texture.image.width / 4 );
  30455. }
  30456. _oldTarget = this._renderer.getRenderTarget();
  30457. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  30458. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  30459. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  30460. this._textureToCubeUV( texture, cubeUVRenderTarget );
  30461. this._applyPMREM( cubeUVRenderTarget );
  30462. this._cleanup( cubeUVRenderTarget );
  30463. return cubeUVRenderTarget;
  30464. }
  30465. _allocateTargets() {
  30466. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  30467. const height = 4 * this._cubeSize;
  30468. const params = {
  30469. magFilter: LinearFilter,
  30470. minFilter: LinearFilter,
  30471. generateMipmaps: false,
  30472. type: HalfFloatType,
  30473. format: RGBAFormat,
  30474. colorSpace: LinearSRGBColorSpace,
  30475. //depthBuffer: false
  30476. };
  30477. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  30478. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  30479. if ( this._pingPongRenderTarget !== null ) {
  30480. this._dispose();
  30481. }
  30482. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  30483. const { _lodMax } = this;
  30484. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  30485. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  30486. }
  30487. return cubeUVRenderTarget;
  30488. }
  30489. async _compileMaterial( material ) {
  30490. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  30491. await this._renderer.compile( tmpMesh, _flatCamera );
  30492. }
  30493. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  30494. const cubeCamera = _cubeCamera;
  30495. cubeCamera.near = near;
  30496. cubeCamera.far = far;
  30497. // px, py, pz, nx, ny, nz
  30498. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  30499. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  30500. const renderer = this._renderer;
  30501. const originalAutoClear = renderer.autoClear;
  30502. renderer.getClearColor( _clearColor$2 );
  30503. renderer.autoClear = false;
  30504. let backgroundBox = this._backgroundBox;
  30505. if ( backgroundBox === null ) {
  30506. const backgroundMaterial = new MeshBasicMaterial( {
  30507. name: 'PMREM.Background',
  30508. side: BackSide,
  30509. depthWrite: false,
  30510. depthTest: false
  30511. } );
  30512. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  30513. }
  30514. let useSolidColor = false;
  30515. const background = scene.background;
  30516. if ( background ) {
  30517. if ( background.isColor ) {
  30518. backgroundBox.material.color.copy( background );
  30519. scene.background = null;
  30520. useSolidColor = true;
  30521. }
  30522. } else {
  30523. backgroundBox.material.color.copy( _clearColor$2 );
  30524. useSolidColor = true;
  30525. }
  30526. renderer.setRenderTarget( cubeUVRenderTarget );
  30527. renderer.clear();
  30528. if ( useSolidColor ) {
  30529. renderer.render( backgroundBox, cubeCamera );
  30530. }
  30531. for ( let i = 0; i < 6; i ++ ) {
  30532. const col = i % 3;
  30533. if ( col === 0 ) {
  30534. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30535. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  30536. } else if ( col === 1 ) {
  30537. cubeCamera.up.set( 0, 0, upSign[ i ] );
  30538. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  30539. } else {
  30540. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30541. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  30542. }
  30543. const size = this._cubeSize;
  30544. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  30545. renderer.render( scene, cubeCamera );
  30546. }
  30547. renderer.autoClear = originalAutoClear;
  30548. scene.background = background;
  30549. }
  30550. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  30551. const renderer = this._renderer;
  30552. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  30553. if ( isCubeTexture ) {
  30554. if ( this._cubemapMaterial === null ) {
  30555. this._cubemapMaterial = _getCubemapMaterial( texture );
  30556. }
  30557. } else {
  30558. if ( this._equirectMaterial === null ) {
  30559. this._equirectMaterial = _getEquirectMaterial( texture );
  30560. }
  30561. }
  30562. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  30563. material.fragmentNode.value = texture;
  30564. const mesh = this._lodMeshes[ 0 ];
  30565. mesh.material = material;
  30566. const size = this._cubeSize;
  30567. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  30568. renderer.setRenderTarget( cubeUVRenderTarget );
  30569. renderer.render( mesh, _flatCamera );
  30570. }
  30571. _applyPMREM( cubeUVRenderTarget ) {
  30572. const renderer = this._renderer;
  30573. const autoClear = renderer.autoClear;
  30574. renderer.autoClear = false;
  30575. const n = this._lodPlanes.length;
  30576. for ( let i = 1; i < n; i ++ ) {
  30577. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  30578. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  30579. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  30580. }
  30581. renderer.autoClear = autoClear;
  30582. }
  30583. /**
  30584. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  30585. * vertically and horizontally, but this breaks down on a cube. Here we apply
  30586. * the blur latitudinally (around the poles), and then longitudinally (towards
  30587. * the poles) to approximate the orthogonally-separable blur. It is least
  30588. * accurate at the poles, but still does a decent job.
  30589. */
  30590. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  30591. const pingPongRenderTarget = this._pingPongRenderTarget;
  30592. this._halfBlur(
  30593. cubeUVRenderTarget,
  30594. pingPongRenderTarget,
  30595. lodIn,
  30596. lodOut,
  30597. sigma,
  30598. 'latitudinal',
  30599. poleAxis );
  30600. this._halfBlur(
  30601. pingPongRenderTarget,
  30602. cubeUVRenderTarget,
  30603. lodOut,
  30604. lodOut,
  30605. sigma,
  30606. 'longitudinal',
  30607. poleAxis );
  30608. }
  30609. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  30610. const renderer = this._renderer;
  30611. const blurMaterial = this._blurMaterial;
  30612. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  30613. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  30614. }
  30615. // Number of standard deviations at which to cut off the discrete approximation.
  30616. const STANDARD_DEVIATIONS = 3;
  30617. const blurMesh = this._lodMeshes[ lodOut ];
  30618. blurMesh.material = blurMaterial;
  30619. const blurUniforms = blurMaterial.uniforms;
  30620. const pixels = this._sizeLods[ lodIn ] - 1;
  30621. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  30622. const sigmaPixels = sigmaRadians / radiansPerPixel;
  30623. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  30624. if ( samples > MAX_SAMPLES ) {
  30625. console.warn( `sigmaRadians, ${
  30626. sigmaRadians}, is too large and will clip, as it requested ${
  30627. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  30628. }
  30629. const weights = [];
  30630. let sum = 0;
  30631. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  30632. const x = i / sigmaPixels;
  30633. const weight = Math.exp( - x * x / 2 );
  30634. weights.push( weight );
  30635. if ( i === 0 ) {
  30636. sum += weight;
  30637. } else if ( i < samples ) {
  30638. sum += 2 * weight;
  30639. }
  30640. }
  30641. for ( let i = 0; i < weights.length; i ++ ) {
  30642. weights[ i ] = weights[ i ] / sum;
  30643. }
  30644. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  30645. blurUniforms.envMap.value = targetIn.texture;
  30646. blurUniforms.samples.value = samples;
  30647. blurUniforms.weights.array = weights;
  30648. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  30649. if ( poleAxis ) {
  30650. blurUniforms.poleAxis.value = poleAxis;
  30651. }
  30652. const { _lodMax } = this;
  30653. blurUniforms.dTheta.value = radiansPerPixel;
  30654. blurUniforms.mipInt.value = _lodMax - lodIn;
  30655. const outputSize = this._sizeLods[ lodOut ];
  30656. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  30657. const y = 4 * ( this._cubeSize - outputSize );
  30658. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  30659. renderer.setRenderTarget( targetOut );
  30660. renderer.render( blurMesh, _flatCamera );
  30661. }
  30662. }
  30663. function _createPlanes( lodMax ) {
  30664. const lodPlanes = [];
  30665. const sizeLods = [];
  30666. const sigmas = [];
  30667. const lodMeshes = [];
  30668. let lod = lodMax;
  30669. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  30670. for ( let i = 0; i < totalLods; i ++ ) {
  30671. const sizeLod = Math.pow( 2, lod );
  30672. sizeLods.push( sizeLod );
  30673. let sigma = 1.0 / sizeLod;
  30674. if ( i > lodMax - LOD_MIN ) {
  30675. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  30676. } else if ( i === 0 ) {
  30677. sigma = 0;
  30678. }
  30679. sigmas.push( sigma );
  30680. const texelSize = 1.0 / ( sizeLod - 2 );
  30681. const min = - texelSize;
  30682. const max = 1 + texelSize;
  30683. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  30684. const cubeFaces = 6;
  30685. const vertices = 6;
  30686. const positionSize = 3;
  30687. const uvSize = 2;
  30688. const faceIndexSize = 1;
  30689. const position = new Float32Array( positionSize * vertices * cubeFaces );
  30690. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  30691. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  30692. for ( let face = 0; face < cubeFaces; face ++ ) {
  30693. const x = ( face % 3 ) * 2 / 3 - 1;
  30694. const y = face > 2 ? 0 : - 1;
  30695. const coordinates = [
  30696. x, y, 0,
  30697. x + 2 / 3, y, 0,
  30698. x + 2 / 3, y + 1, 0,
  30699. x, y, 0,
  30700. x + 2 / 3, y + 1, 0,
  30701. x, y + 1, 0
  30702. ];
  30703. const faceIdx = _faceLib[ face ];
  30704. position.set( coordinates, positionSize * vertices * faceIdx );
  30705. uv.set( uv1, uvSize * vertices * faceIdx );
  30706. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  30707. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  30708. }
  30709. const planes = new BufferGeometry();
  30710. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  30711. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  30712. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  30713. lodPlanes.push( planes );
  30714. lodMeshes.push( new Mesh( planes, null ) );
  30715. if ( lod > LOD_MIN ) {
  30716. lod --;
  30717. }
  30718. }
  30719. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  30720. }
  30721. function _createRenderTarget( width, height, params ) {
  30722. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  30723. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  30724. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  30725. cubeUVRenderTarget.texture.isPMREMTexture = true;
  30726. cubeUVRenderTarget.scissorTest = true;
  30727. return cubeUVRenderTarget;
  30728. }
  30729. function _setViewport( target, x, y, width, height ) {
  30730. target.viewport.set( x, y, width, height );
  30731. target.scissor.set( x, y, width, height );
  30732. }
  30733. function _getMaterial( type ) {
  30734. const material = new NodeMaterial();
  30735. material.depthTest = false;
  30736. material.depthWrite = false;
  30737. material.blending = NoBlending;
  30738. material.name = `PMREM_${ type }`;
  30739. return material;
  30740. }
  30741. function _getBlurShader( lodMax, width, height ) {
  30742. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  30743. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  30744. const dTheta = uniform( 0 );
  30745. const n = float( MAX_SAMPLES );
  30746. const latitudinal = uniform( 0 ); // false, bool
  30747. const samples = uniform( 1 ); // int
  30748. const envMap = texture( null );
  30749. const mipInt = uniform( 0 ); // int
  30750. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  30751. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  30752. const CUBEUV_MAX_MIP = float( lodMax );
  30753. const materialUniforms = {
  30754. n,
  30755. latitudinal,
  30756. weights,
  30757. poleAxis,
  30758. outputDirection,
  30759. dTheta,
  30760. samples,
  30761. envMap,
  30762. mipInt,
  30763. CUBEUV_TEXEL_WIDTH,
  30764. CUBEUV_TEXEL_HEIGHT,
  30765. CUBEUV_MAX_MIP
  30766. };
  30767. const material = _getMaterial( 'blur' );
  30768. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  30769. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  30770. return material;
  30771. }
  30772. function _getCubemapMaterial( envTexture ) {
  30773. const material = _getMaterial( 'cubemap' );
  30774. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  30775. return material;
  30776. }
  30777. function _getEquirectMaterial( envTexture ) {
  30778. const material = _getMaterial( 'equirect' );
  30779. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  30780. return material;
  30781. }
  30782. let _id$5 = 0;
  30783. class BindGroup {
  30784. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  30785. this.name = name;
  30786. this.bindings = bindings;
  30787. this.index = index;
  30788. this.bindingsReference = bindingsReference;
  30789. this.id = _id$5 ++;
  30790. }
  30791. }
  30792. const rendererCache = new WeakMap();
  30793. const typeFromLength = new Map( [
  30794. [ 2, 'vec2' ],
  30795. [ 3, 'vec3' ],
  30796. [ 4, 'vec4' ],
  30797. [ 9, 'mat3' ],
  30798. [ 16, 'mat4' ]
  30799. ] );
  30800. const typeFromArray = new Map( [
  30801. [ Int8Array, 'int' ],
  30802. [ Int16Array, 'int' ],
  30803. [ Int32Array, 'int' ],
  30804. [ Uint8Array, 'uint' ],
  30805. [ Uint16Array, 'uint' ],
  30806. [ Uint32Array, 'uint' ],
  30807. [ Float32Array, 'float' ]
  30808. ] );
  30809. const toFloat = ( value ) => {
  30810. value = Number( value );
  30811. return value + ( value % 1 ? '' : '.0' );
  30812. };
  30813. class NodeBuilder {
  30814. constructor( object, renderer, parser ) {
  30815. this.object = object;
  30816. this.material = ( object && object.material ) || null;
  30817. this.geometry = ( object && object.geometry ) || null;
  30818. this.renderer = renderer;
  30819. this.parser = parser;
  30820. this.scene = null;
  30821. this.camera = null;
  30822. this.nodes = [];
  30823. this.updateNodes = [];
  30824. this.updateBeforeNodes = [];
  30825. this.updateAfterNodes = [];
  30826. this.hashNodes = {};
  30827. this.monitor = null;
  30828. this.lightsNode = null;
  30829. this.environmentNode = null;
  30830. this.fogNode = null;
  30831. this.clippingContext = null;
  30832. this.vertexShader = null;
  30833. this.fragmentShader = null;
  30834. this.computeShader = null;
  30835. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  30836. this.flowCode = { vertex: '', fragment: '', compute: '' };
  30837. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  30838. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  30839. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  30840. this.bindingsIndexes = {};
  30841. this.bindGroups = null;
  30842. this.attributes = [];
  30843. this.bufferAttributes = [];
  30844. this.varyings = [];
  30845. this.codes = {};
  30846. this.vars = {};
  30847. this.flow = { code: '' };
  30848. this.chaining = [];
  30849. this.stack = stack();
  30850. this.stacks = [];
  30851. this.tab = '\t';
  30852. this.currentFunctionNode = null;
  30853. this.context = {
  30854. material: this.material
  30855. };
  30856. this.cache = new NodeCache();
  30857. this.globalCache = this.cache;
  30858. this.flowsData = new WeakMap();
  30859. this.shaderStage = null;
  30860. this.buildStage = null;
  30861. this.useComparisonMethod = false;
  30862. }
  30863. getBindGroupsCache() {
  30864. let bindGroupsCache = rendererCache.get( this.renderer );
  30865. if ( bindGroupsCache === undefined ) {
  30866. bindGroupsCache = new ChainMap();
  30867. rendererCache.set( this.renderer, bindGroupsCache );
  30868. }
  30869. return bindGroupsCache;
  30870. }
  30871. createRenderTarget( width, height, options ) {
  30872. return new RenderTarget( width, height, options );
  30873. }
  30874. createCubeRenderTarget( size, options ) {
  30875. return new CubeRenderTarget( size, options );
  30876. }
  30877. createPMREMGenerator() {
  30878. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  30879. return new PMREMGenerator( this.renderer );
  30880. }
  30881. includes( node ) {
  30882. return this.nodes.includes( node );
  30883. }
  30884. _getBindGroup( groupName, bindings ) {
  30885. const bindGroupsCache = this.getBindGroupsCache();
  30886. //
  30887. const bindingsArray = [];
  30888. let sharedGroup = true;
  30889. for ( const binding of bindings ) {
  30890. bindingsArray.push( binding );
  30891. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  30892. }
  30893. //
  30894. let bindGroup;
  30895. if ( sharedGroup ) {
  30896. bindGroup = bindGroupsCache.get( bindingsArray );
  30897. if ( bindGroup === undefined ) {
  30898. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30899. bindGroupsCache.set( bindingsArray, bindGroup );
  30900. }
  30901. } else {
  30902. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30903. }
  30904. return bindGroup;
  30905. }
  30906. getBindGroupArray( groupName, shaderStage ) {
  30907. const bindings = this.bindings[ shaderStage ];
  30908. let bindGroup = bindings[ groupName ];
  30909. if ( bindGroup === undefined ) {
  30910. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  30911. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  30912. }
  30913. bindings[ groupName ] = bindGroup = [];
  30914. }
  30915. return bindGroup;
  30916. }
  30917. getBindings() {
  30918. let bindingsGroups = this.bindGroups;
  30919. if ( bindingsGroups === null ) {
  30920. const groups = {};
  30921. const bindings = this.bindings;
  30922. for ( const shaderStage of shaderStages ) {
  30923. for ( const groupName in bindings[ shaderStage ] ) {
  30924. const uniforms = bindings[ shaderStage ][ groupName ];
  30925. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  30926. groupUniforms.push( ...uniforms );
  30927. }
  30928. }
  30929. bindingsGroups = [];
  30930. for ( const groupName in groups ) {
  30931. const group = groups[ groupName ];
  30932. const bindingsGroup = this._getBindGroup( groupName, group );
  30933. bindingsGroups.push( bindingsGroup );
  30934. }
  30935. this.bindGroups = bindingsGroups;
  30936. }
  30937. return bindingsGroups;
  30938. }
  30939. sortBindingGroups() {
  30940. const bindingsGroups = this.getBindings();
  30941. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  30942. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  30943. const bindingGroup = bindingsGroups[ i ];
  30944. this.bindingsIndexes[ bindingGroup.name ].group = i;
  30945. bindingGroup.index = i;
  30946. }
  30947. }
  30948. setHashNode( node, hash ) {
  30949. this.hashNodes[ hash ] = node;
  30950. }
  30951. addNode( node ) {
  30952. if ( this.nodes.includes( node ) === false ) {
  30953. this.nodes.push( node );
  30954. this.setHashNode( node, node.getHash( this ) );
  30955. }
  30956. }
  30957. buildUpdateNodes() {
  30958. for ( const node of this.nodes ) {
  30959. const updateType = node.getUpdateType();
  30960. const updateBeforeType = node.getUpdateBeforeType();
  30961. const updateAfterType = node.getUpdateAfterType();
  30962. if ( updateType !== NodeUpdateType.NONE ) {
  30963. this.updateNodes.push( node.getSelf() );
  30964. }
  30965. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  30966. this.updateBeforeNodes.push( node.getSelf() );
  30967. }
  30968. if ( updateAfterType !== NodeUpdateType.NONE ) {
  30969. this.updateAfterNodes.push( node.getSelf() );
  30970. }
  30971. }
  30972. }
  30973. get currentNode() {
  30974. return this.chaining[ this.chaining.length - 1 ];
  30975. }
  30976. isFilteredTexture( texture ) {
  30977. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  30978. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  30979. }
  30980. addChain( node ) {
  30981. /*
  30982. if ( this.chaining.indexOf( node ) !== - 1 ) {
  30983. console.warn( 'Recursive node: ', node );
  30984. }
  30985. */
  30986. this.chaining.push( node );
  30987. }
  30988. removeChain( node ) {
  30989. const lastChain = this.chaining.pop();
  30990. if ( lastChain !== node ) {
  30991. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  30992. }
  30993. }
  30994. getMethod( method ) {
  30995. return method;
  30996. }
  30997. getNodeFromHash( hash ) {
  30998. return this.hashNodes[ hash ];
  30999. }
  31000. addFlow( shaderStage, node ) {
  31001. this.flowNodes[ shaderStage ].push( node );
  31002. return node;
  31003. }
  31004. setContext( context ) {
  31005. this.context = context;
  31006. }
  31007. getContext() {
  31008. return this.context;
  31009. }
  31010. getSharedContext() {
  31011. ({ ...this.context });
  31012. return this.context;
  31013. }
  31014. setCache( cache ) {
  31015. this.cache = cache;
  31016. }
  31017. getCache() {
  31018. return this.cache;
  31019. }
  31020. getCacheFromNode( node, parent = true ) {
  31021. const data = this.getDataFromNode( node );
  31022. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  31023. return data.cache;
  31024. }
  31025. isAvailable( /*name*/ ) {
  31026. return false;
  31027. }
  31028. getVertexIndex() {
  31029. console.warn( 'Abstract function.' );
  31030. }
  31031. getInstanceIndex() {
  31032. console.warn( 'Abstract function.' );
  31033. }
  31034. getDrawIndex() {
  31035. console.warn( 'Abstract function.' );
  31036. }
  31037. getFrontFacing() {
  31038. console.warn( 'Abstract function.' );
  31039. }
  31040. getFragCoord() {
  31041. console.warn( 'Abstract function.' );
  31042. }
  31043. isFlipY() {
  31044. return false;
  31045. }
  31046. increaseUsage( node ) {
  31047. const nodeData = this.getDataFromNode( node );
  31048. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  31049. return nodeData.usageCount;
  31050. }
  31051. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  31052. console.warn( 'Abstract function.' );
  31053. }
  31054. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  31055. console.warn( 'Abstract function.' );
  31056. }
  31057. generateConst( type, value = null ) {
  31058. if ( value === null ) {
  31059. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  31060. else if ( type === 'bool' ) value = false;
  31061. else if ( type === 'color' ) value = new Color();
  31062. else if ( type === 'vec2' ) value = new Vector2();
  31063. else if ( type === 'vec3' ) value = new Vector3();
  31064. else if ( type === 'vec4' ) value = new Vector4();
  31065. }
  31066. if ( type === 'float' ) return toFloat( value );
  31067. if ( type === 'int' ) return `${ Math.round( value ) }`;
  31068. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  31069. if ( type === 'bool' ) return value ? 'true' : 'false';
  31070. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  31071. const typeLength = this.getTypeLength( type );
  31072. const componentType = this.getComponentType( type );
  31073. const generateConst = value => this.generateConst( componentType, value );
  31074. if ( typeLength === 2 ) {
  31075. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  31076. } else if ( typeLength === 3 ) {
  31077. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  31078. } else if ( typeLength === 4 ) {
  31079. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  31080. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  31081. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  31082. } else if ( typeLength > 4 ) {
  31083. return `${ this.getType( type ) }()`;
  31084. }
  31085. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  31086. }
  31087. getType( type ) {
  31088. if ( type === 'color' ) return 'vec3';
  31089. return type;
  31090. }
  31091. hasGeometryAttribute( name ) {
  31092. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  31093. }
  31094. getAttribute( name, type ) {
  31095. const attributes = this.attributes;
  31096. // find attribute
  31097. for ( const attribute of attributes ) {
  31098. if ( attribute.name === name ) {
  31099. return attribute;
  31100. }
  31101. }
  31102. // create a new if no exist
  31103. const attribute = new NodeAttribute( name, type );
  31104. attributes.push( attribute );
  31105. return attribute;
  31106. }
  31107. getPropertyName( node/*, shaderStage*/ ) {
  31108. return node.name;
  31109. }
  31110. isVector( type ) {
  31111. return /vec\d/.test( type );
  31112. }
  31113. isMatrix( type ) {
  31114. return /mat\d/.test( type );
  31115. }
  31116. isReference( type ) {
  31117. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  31118. }
  31119. needsToWorkingColorSpace( /*texture*/ ) {
  31120. return false;
  31121. }
  31122. getComponentTypeFromTexture( texture ) {
  31123. const type = texture.type;
  31124. if ( texture.isDataTexture ) {
  31125. if ( type === IntType ) return 'int';
  31126. if ( type === UnsignedIntType ) return 'uint';
  31127. }
  31128. return 'float';
  31129. }
  31130. getElementType( type ) {
  31131. if ( type === 'mat2' ) return 'vec2';
  31132. if ( type === 'mat3' ) return 'vec3';
  31133. if ( type === 'mat4' ) return 'vec4';
  31134. return this.getComponentType( type );
  31135. }
  31136. getComponentType( type ) {
  31137. type = this.getVectorType( type );
  31138. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  31139. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  31140. if ( componentType === null ) return null;
  31141. if ( componentType[ 1 ] === 'b' ) return 'bool';
  31142. if ( componentType[ 1 ] === 'i' ) return 'int';
  31143. if ( componentType[ 1 ] === 'u' ) return 'uint';
  31144. return 'float';
  31145. }
  31146. getVectorType( type ) {
  31147. if ( type === 'color' ) return 'vec3';
  31148. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  31149. return type;
  31150. }
  31151. getTypeFromLength( length, componentType = 'float' ) {
  31152. if ( length === 1 ) return componentType;
  31153. const baseType = typeFromLength.get( length );
  31154. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  31155. return prefix + baseType;
  31156. }
  31157. getTypeFromArray( array ) {
  31158. return typeFromArray.get( array.constructor );
  31159. }
  31160. getTypeFromAttribute( attribute ) {
  31161. let dataAttribute = attribute;
  31162. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  31163. const array = dataAttribute.array;
  31164. const itemSize = attribute.itemSize;
  31165. const normalized = attribute.normalized;
  31166. let arrayType;
  31167. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  31168. arrayType = this.getTypeFromArray( array );
  31169. }
  31170. return this.getTypeFromLength( itemSize, arrayType );
  31171. }
  31172. getTypeLength( type ) {
  31173. const vecType = this.getVectorType( type );
  31174. const vecNum = /vec([2-4])/.exec( vecType );
  31175. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  31176. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  31177. if ( /mat2/.test( type ) === true ) return 4;
  31178. if ( /mat3/.test( type ) === true ) return 9;
  31179. if ( /mat4/.test( type ) === true ) return 16;
  31180. return 0;
  31181. }
  31182. getVectorFromMatrix( type ) {
  31183. return type.replace( 'mat', 'vec' );
  31184. }
  31185. changeComponentType( type, newComponentType ) {
  31186. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  31187. }
  31188. getIntegerType( type ) {
  31189. const componentType = this.getComponentType( type );
  31190. if ( componentType === 'int' || componentType === 'uint' ) return type;
  31191. return this.changeComponentType( type, 'int' );
  31192. }
  31193. addStack() {
  31194. this.stack = stack( this.stack );
  31195. this.stacks.push( getCurrentStack() || this.stack );
  31196. setCurrentStack( this.stack );
  31197. return this.stack;
  31198. }
  31199. removeStack() {
  31200. const lastStack = this.stack;
  31201. this.stack = lastStack.parent;
  31202. setCurrentStack( this.stacks.pop() );
  31203. return lastStack;
  31204. }
  31205. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  31206. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  31207. let nodeData = cache.getData( node );
  31208. if ( nodeData === undefined ) {
  31209. nodeData = {};
  31210. cache.setData( node, nodeData );
  31211. }
  31212. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  31213. return nodeData[ shaderStage ];
  31214. }
  31215. getNodeProperties( node, shaderStage = 'any' ) {
  31216. const nodeData = this.getDataFromNode( node, shaderStage );
  31217. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  31218. }
  31219. getBufferAttributeFromNode( node, type ) {
  31220. const nodeData = this.getDataFromNode( node );
  31221. let bufferAttribute = nodeData.bufferAttribute;
  31222. if ( bufferAttribute === undefined ) {
  31223. const index = this.uniforms.index ++;
  31224. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  31225. this.bufferAttributes.push( bufferAttribute );
  31226. nodeData.bufferAttribute = bufferAttribute;
  31227. }
  31228. return bufferAttribute;
  31229. }
  31230. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  31231. const nodeData = this.getDataFromNode( node, shaderStage );
  31232. if ( nodeData.structType === undefined ) {
  31233. const index = this.structs.index ++;
  31234. node.name = `StructType${ index }`;
  31235. this.structs[ shaderStage ].push( node );
  31236. nodeData.structType = node;
  31237. }
  31238. return node;
  31239. }
  31240. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  31241. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31242. let nodeUniform = nodeData.uniform;
  31243. if ( nodeUniform === undefined ) {
  31244. const index = this.uniforms.index ++;
  31245. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  31246. this.uniforms[ shaderStage ].push( nodeUniform );
  31247. nodeData.uniform = nodeUniform;
  31248. }
  31249. return nodeUniform;
  31250. }
  31251. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  31252. const nodeData = this.getDataFromNode( node, shaderStage );
  31253. let nodeVar = nodeData.variable;
  31254. if ( nodeVar === undefined ) {
  31255. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  31256. if ( name === null ) name = 'nodeVar' + vars.length;
  31257. nodeVar = new NodeVar( name, type );
  31258. vars.push( nodeVar );
  31259. nodeData.variable = nodeVar;
  31260. }
  31261. return nodeVar;
  31262. }
  31263. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  31264. const nodeData = this.getDataFromNode( node, 'any' );
  31265. let nodeVarying = nodeData.varying;
  31266. if ( nodeVarying === undefined ) {
  31267. const varyings = this.varyings;
  31268. const index = varyings.length;
  31269. if ( name === null ) name = 'nodeVarying' + index;
  31270. nodeVarying = new NodeVarying( name, type );
  31271. varyings.push( nodeVarying );
  31272. nodeData.varying = nodeVarying;
  31273. }
  31274. return nodeVarying;
  31275. }
  31276. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  31277. const nodeData = this.getDataFromNode( node );
  31278. let nodeCode = nodeData.code;
  31279. if ( nodeCode === undefined ) {
  31280. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  31281. const index = codes.length;
  31282. nodeCode = new NodeCode( 'nodeCode' + index, type );
  31283. codes.push( nodeCode );
  31284. nodeData.code = nodeCode;
  31285. }
  31286. return nodeCode;
  31287. }
  31288. addLineFlowCode( code ) {
  31289. if ( code === '' ) return this;
  31290. code = this.tab + code;
  31291. if ( ! /;\s*$/.test( code ) ) {
  31292. code = code + ';\n';
  31293. }
  31294. this.flow.code += code;
  31295. return this;
  31296. }
  31297. addFlowCode( code ) {
  31298. this.flow.code += code;
  31299. return this;
  31300. }
  31301. addFlowTab() {
  31302. this.tab += '\t';
  31303. return this;
  31304. }
  31305. removeFlowTab() {
  31306. this.tab = this.tab.slice( 0, - 1 );
  31307. return this;
  31308. }
  31309. getFlowData( node/*, shaderStage*/ ) {
  31310. return this.flowsData.get( node );
  31311. }
  31312. flowNode( node ) {
  31313. const output = node.getNodeType( this );
  31314. const flowData = this.flowChildNode( node, output );
  31315. this.flowsData.set( node, flowData );
  31316. return flowData;
  31317. }
  31318. buildFunctionNode( shaderNode ) {
  31319. const fn = new FunctionNode();
  31320. const previous = this.currentFunctionNode;
  31321. this.currentFunctionNode = fn;
  31322. fn.code = this.buildFunctionCode( shaderNode );
  31323. this.currentFunctionNode = previous;
  31324. return fn;
  31325. }
  31326. flowShaderNode( shaderNode ) {
  31327. const layout = shaderNode.layout;
  31328. const inputs = {
  31329. [ Symbol.iterator ]() {
  31330. let index = 0;
  31331. const values = Object.values( this );
  31332. return {
  31333. next: () => ( {
  31334. value: values[ index ],
  31335. done: index ++ >= values.length
  31336. } )
  31337. };
  31338. }
  31339. };
  31340. for ( const input of layout.inputs ) {
  31341. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  31342. }
  31343. //
  31344. shaderNode.layout = null;
  31345. const callNode = shaderNode.call( inputs );
  31346. const flowData = this.flowStagesNode( callNode, layout.type );
  31347. shaderNode.layout = layout;
  31348. return flowData;
  31349. }
  31350. flowStagesNode( node, output = null ) {
  31351. const previousFlow = this.flow;
  31352. const previousVars = this.vars;
  31353. const previousCache = this.cache;
  31354. const previousBuildStage = this.buildStage;
  31355. const previousStack = this.stack;
  31356. const flow = {
  31357. code: ''
  31358. };
  31359. this.flow = flow;
  31360. this.vars = {};
  31361. this.cache = new NodeCache();
  31362. this.stack = stack();
  31363. for ( const buildStage of defaultBuildStages ) {
  31364. this.setBuildStage( buildStage );
  31365. flow.result = node.build( this, output );
  31366. }
  31367. flow.vars = this.getVars( this.shaderStage );
  31368. this.flow = previousFlow;
  31369. this.vars = previousVars;
  31370. this.cache = previousCache;
  31371. this.stack = previousStack;
  31372. this.setBuildStage( previousBuildStage );
  31373. return flow;
  31374. }
  31375. getFunctionOperator() {
  31376. return null;
  31377. }
  31378. flowChildNode( node, output = null ) {
  31379. const previousFlow = this.flow;
  31380. const flow = {
  31381. code: ''
  31382. };
  31383. this.flow = flow;
  31384. flow.result = node.build( this, output );
  31385. this.flow = previousFlow;
  31386. return flow;
  31387. }
  31388. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  31389. const previousShaderStage = this.shaderStage;
  31390. this.setShaderStage( shaderStage );
  31391. const flowData = this.flowChildNode( node, output );
  31392. if ( propertyName !== null ) {
  31393. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  31394. }
  31395. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  31396. this.setShaderStage( previousShaderStage );
  31397. return flowData;
  31398. }
  31399. getAttributesArray() {
  31400. return this.attributes.concat( this.bufferAttributes );
  31401. }
  31402. getAttributes( /*shaderStage*/ ) {
  31403. console.warn( 'Abstract function.' );
  31404. }
  31405. getVaryings( /*shaderStage*/ ) {
  31406. console.warn( 'Abstract function.' );
  31407. }
  31408. getVar( type, name ) {
  31409. return `${ this.getType( type ) } ${ name }`;
  31410. }
  31411. getVars( shaderStage ) {
  31412. let snippet = '';
  31413. const vars = this.vars[ shaderStage ];
  31414. if ( vars !== undefined ) {
  31415. for ( const variable of vars ) {
  31416. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31417. }
  31418. }
  31419. return snippet;
  31420. }
  31421. getUniforms( /*shaderStage*/ ) {
  31422. console.warn( 'Abstract function.' );
  31423. }
  31424. getCodes( shaderStage ) {
  31425. const codes = this.codes[ shaderStage ];
  31426. let code = '';
  31427. if ( codes !== undefined ) {
  31428. for ( const nodeCode of codes ) {
  31429. code += nodeCode.code + '\n';
  31430. }
  31431. }
  31432. return code;
  31433. }
  31434. getHash() {
  31435. return this.vertexShader + this.fragmentShader + this.computeShader;
  31436. }
  31437. setShaderStage( shaderStage ) {
  31438. this.shaderStage = shaderStage;
  31439. }
  31440. getShaderStage() {
  31441. return this.shaderStage;
  31442. }
  31443. setBuildStage( buildStage ) {
  31444. this.buildStage = buildStage;
  31445. }
  31446. getBuildStage() {
  31447. return this.buildStage;
  31448. }
  31449. buildCode() {
  31450. console.warn( 'Abstract function.' );
  31451. }
  31452. build() {
  31453. const { object, material, renderer } = this;
  31454. if ( material !== null ) {
  31455. let nodeMaterial = renderer.nodes.library.fromMaterial( material );
  31456. if ( nodeMaterial === null ) {
  31457. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  31458. nodeMaterial = new NodeMaterial();
  31459. }
  31460. nodeMaterial.build( this );
  31461. } else {
  31462. this.addFlow( 'compute', object );
  31463. }
  31464. // setup() -> stage 1: create possible new nodes and returns an output reference node
  31465. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  31466. // generate() -> stage 3: generate shader
  31467. for ( const buildStage of defaultBuildStages ) {
  31468. this.setBuildStage( buildStage );
  31469. if ( this.context.vertex && this.context.vertex.isNode ) {
  31470. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  31471. }
  31472. for ( const shaderStage of shaderStages ) {
  31473. this.setShaderStage( shaderStage );
  31474. const flowNodes = this.flowNodes[ shaderStage ];
  31475. for ( const node of flowNodes ) {
  31476. if ( buildStage === 'generate' ) {
  31477. this.flowNode( node );
  31478. } else {
  31479. node.build( this );
  31480. }
  31481. }
  31482. }
  31483. }
  31484. this.setBuildStage( null );
  31485. this.setShaderStage( null );
  31486. // stage 4: build code for a specific output
  31487. this.buildCode();
  31488. this.buildUpdateNodes();
  31489. return this;
  31490. }
  31491. getNodeUniform( uniformNode, type ) {
  31492. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  31493. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  31494. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  31495. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  31496. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  31497. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  31498. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  31499. throw new Error( `Uniform "${type}" not declared.` );
  31500. }
  31501. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  31502. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  31503. }
  31504. format( snippet, fromType, toType ) {
  31505. fromType = this.getVectorType( fromType );
  31506. toType = this.getVectorType( toType );
  31507. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  31508. return snippet;
  31509. }
  31510. const fromTypeLength = this.getTypeLength( fromType );
  31511. const toTypeLength = this.getTypeLength( toType );
  31512. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  31513. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  31514. }
  31515. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  31516. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  31517. }
  31518. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  31519. // @TODO: ignore for now
  31520. return snippet;
  31521. }
  31522. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  31523. // @TODO: ignore for now
  31524. return snippet;
  31525. }
  31526. if ( fromTypeLength === toTypeLength ) {
  31527. return `${ this.getType( toType ) }( ${ snippet } )`;
  31528. }
  31529. if ( fromTypeLength > toTypeLength ) {
  31530. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  31531. }
  31532. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  31533. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  31534. }
  31535. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  31536. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  31537. }
  31538. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  31539. // convert a number value to vector type, e.g:
  31540. // vec3( 1u ) -> vec3( float( 1u ) )
  31541. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  31542. }
  31543. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  31544. }
  31545. getSignature() {
  31546. return `// Three.js r${ REVISION } - Node System\n`;
  31547. }
  31548. }
  31549. class NodeFrame {
  31550. constructor() {
  31551. this.time = 0;
  31552. this.deltaTime = 0;
  31553. this.frameId = 0;
  31554. this.renderId = 0;
  31555. this.startTime = null;
  31556. this.updateMap = new WeakMap();
  31557. this.updateBeforeMap = new WeakMap();
  31558. this.updateAfterMap = new WeakMap();
  31559. this.renderer = null;
  31560. this.material = null;
  31561. this.camera = null;
  31562. this.object = null;
  31563. this.scene = null;
  31564. }
  31565. _getMaps( referenceMap, nodeRef ) {
  31566. let maps = referenceMap.get( nodeRef );
  31567. if ( maps === undefined ) {
  31568. maps = {
  31569. renderMap: new WeakMap(),
  31570. frameMap: new WeakMap()
  31571. };
  31572. referenceMap.set( nodeRef, maps );
  31573. }
  31574. return maps;
  31575. }
  31576. updateBeforeNode( node ) {
  31577. const updateType = node.getUpdateBeforeType();
  31578. const reference = node.updateReference( this );
  31579. if ( updateType === NodeUpdateType.FRAME ) {
  31580. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  31581. if ( frameMap.get( reference ) !== this.frameId ) {
  31582. if ( node.updateBefore( this ) !== false ) {
  31583. frameMap.set( reference, this.frameId );
  31584. }
  31585. }
  31586. } else if ( updateType === NodeUpdateType.RENDER ) {
  31587. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  31588. if ( renderMap.get( reference ) !== this.renderId ) {
  31589. if ( node.updateBefore( this ) !== false ) {
  31590. renderMap.set( reference, this.renderId );
  31591. }
  31592. }
  31593. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31594. node.updateBefore( this );
  31595. }
  31596. }
  31597. updateAfterNode( node ) {
  31598. const updateType = node.getUpdateAfterType();
  31599. const reference = node.updateReference( this );
  31600. if ( updateType === NodeUpdateType.FRAME ) {
  31601. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  31602. if ( frameMap.get( reference ) !== this.frameId ) {
  31603. if ( node.updateAfter( this ) !== false ) {
  31604. frameMap.set( reference, this.frameId );
  31605. }
  31606. }
  31607. } else if ( updateType === NodeUpdateType.RENDER ) {
  31608. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  31609. if ( renderMap.get( reference ) !== this.renderId ) {
  31610. if ( node.updateAfter( this ) !== false ) {
  31611. renderMap.set( reference, this.renderId );
  31612. }
  31613. }
  31614. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31615. node.updateAfter( this );
  31616. }
  31617. }
  31618. updateNode( node ) {
  31619. const updateType = node.getUpdateType();
  31620. const reference = node.updateReference( this );
  31621. if ( updateType === NodeUpdateType.FRAME ) {
  31622. const { frameMap } = this._getMaps( this.updateMap, reference );
  31623. if ( frameMap.get( reference ) !== this.frameId ) {
  31624. if ( node.update( this ) !== false ) {
  31625. frameMap.set( reference, this.frameId );
  31626. }
  31627. }
  31628. } else if ( updateType === NodeUpdateType.RENDER ) {
  31629. const { renderMap } = this._getMaps( this.updateMap, reference );
  31630. if ( renderMap.get( reference ) !== this.renderId ) {
  31631. if ( node.update( this ) !== false ) {
  31632. renderMap.set( reference, this.renderId );
  31633. }
  31634. }
  31635. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31636. node.update( this );
  31637. }
  31638. }
  31639. update() {
  31640. this.frameId ++;
  31641. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31642. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31643. this.lastTime = performance.now();
  31644. this.time += this.deltaTime;
  31645. }
  31646. }
  31647. class NodeFunctionInput {
  31648. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31649. this.type = type;
  31650. this.name = name;
  31651. this.count = count;
  31652. this.qualifier = qualifier;
  31653. this.isConst = isConst;
  31654. }
  31655. }
  31656. NodeFunctionInput.isNodeFunctionInput = true;
  31657. class StructTypeNode extends Node {
  31658. static get type() {
  31659. return 'StructTypeNode';
  31660. }
  31661. constructor( types ) {
  31662. super();
  31663. this.types = types;
  31664. this.isStructTypeNode = true;
  31665. }
  31666. getMemberTypes() {
  31667. return this.types;
  31668. }
  31669. }
  31670. class OutputStructNode extends Node {
  31671. static get type() {
  31672. return 'OutputStructNode';
  31673. }
  31674. constructor( ...members ) {
  31675. super();
  31676. this.members = members;
  31677. this.isOutputStructNode = true;
  31678. }
  31679. setup( builder ) {
  31680. super.setup( builder );
  31681. const members = this.members;
  31682. const types = [];
  31683. for ( let i = 0; i < members.length; i ++ ) {
  31684. types.push( members[ i ].getNodeType( builder ) );
  31685. }
  31686. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  31687. }
  31688. generate( builder, output ) {
  31689. const propertyName = builder.getOutputStructName();
  31690. const members = this.members;
  31691. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  31692. for ( let i = 0; i < members.length; i ++ ) {
  31693. const snippet = members[ i ].build( builder, output );
  31694. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }` );
  31695. }
  31696. return propertyName;
  31697. }
  31698. }
  31699. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  31700. function getTextureIndex( textures, name ) {
  31701. for ( let i = 0; i < textures.length; i ++ ) {
  31702. if ( textures[ i ].name === name ) {
  31703. return i;
  31704. }
  31705. }
  31706. return - 1;
  31707. }
  31708. class MRTNode extends OutputStructNode {
  31709. static get type() {
  31710. return 'MRTNode';
  31711. }
  31712. constructor( outputNodes ) {
  31713. super();
  31714. this.outputNodes = outputNodes;
  31715. this.isMRTNode = true;
  31716. }
  31717. has( name ) {
  31718. return this.outputNodes[ name ] !== undefined;
  31719. }
  31720. get( name ) {
  31721. return this.outputNodes[ name ];
  31722. }
  31723. merge( mrtNode ) {
  31724. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  31725. return mrt( outputs );
  31726. }
  31727. setup( builder ) {
  31728. const outputNodes = this.outputNodes;
  31729. const mrt = builder.renderer.getRenderTarget();
  31730. const members = [];
  31731. const textures = mrt.textures;
  31732. for ( const name in outputNodes ) {
  31733. const index = getTextureIndex( textures, name );
  31734. members[ index ] = vec4( outputNodes[ name ] );
  31735. }
  31736. this.members = members;
  31737. return super.setup( builder );
  31738. }
  31739. }
  31740. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  31741. class FunctionOverloadingNode extends Node {
  31742. static get type() {
  31743. return 'FunctionOverloadingNode';
  31744. }
  31745. constructor( functionNodes = [], ...parametersNodes ) {
  31746. super();
  31747. this.functionNodes = functionNodes;
  31748. this.parametersNodes = parametersNodes;
  31749. this._candidateFnCall = null;
  31750. this.global = true;
  31751. }
  31752. getNodeType() {
  31753. return this.functionNodes[ 0 ].shaderNode.layout.type;
  31754. }
  31755. setup( builder ) {
  31756. const params = this.parametersNodes;
  31757. let candidateFnCall = this._candidateFnCall;
  31758. if ( candidateFnCall === null ) {
  31759. let candidateFn = null;
  31760. let candidateScore = - 1;
  31761. for ( const functionNode of this.functionNodes ) {
  31762. const shaderNode = functionNode.shaderNode;
  31763. const layout = shaderNode.layout;
  31764. if ( layout === null ) {
  31765. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  31766. }
  31767. const inputs = layout.inputs;
  31768. if ( params.length === inputs.length ) {
  31769. let score = 0;
  31770. for ( let i = 0; i < params.length; i ++ ) {
  31771. const param = params[ i ];
  31772. const input = inputs[ i ];
  31773. if ( param.getNodeType( builder ) === input.type ) {
  31774. score ++;
  31775. } else {
  31776. score = 0;
  31777. }
  31778. }
  31779. if ( score > candidateScore ) {
  31780. candidateFn = functionNode;
  31781. candidateScore = score;
  31782. }
  31783. }
  31784. }
  31785. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  31786. }
  31787. return candidateFnCall;
  31788. }
  31789. }
  31790. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  31791. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  31792. class TimerNode extends UniformNode {
  31793. static get type() {
  31794. return 'TimerNode';
  31795. }
  31796. constructor( scope = TimerNode.LOCAL, scale = 1, value = 0 ) {
  31797. super( value );
  31798. this.scope = scope;
  31799. this.scale = scale;
  31800. this.updateType = NodeUpdateType.FRAME;
  31801. }
  31802. /*
  31803. @TODO:
  31804. getNodeType( builder ) {
  31805. const scope = this.scope;
  31806. if ( scope === TimerNode.FRAME ) {
  31807. return 'uint';
  31808. }
  31809. return 'float';
  31810. }
  31811. */
  31812. update( frame ) {
  31813. const scope = this.scope;
  31814. const scale = this.scale;
  31815. if ( scope === TimerNode.LOCAL ) {
  31816. this.value += frame.deltaTime * scale;
  31817. } else if ( scope === TimerNode.DELTA ) {
  31818. this.value = frame.deltaTime * scale;
  31819. } else if ( scope === TimerNode.FRAME ) {
  31820. this.value = frame.frameId;
  31821. } else {
  31822. // global
  31823. this.value = frame.time * scale;
  31824. }
  31825. }
  31826. serialize( data ) {
  31827. super.serialize( data );
  31828. data.scope = this.scope;
  31829. data.scale = this.scale;
  31830. }
  31831. deserialize( data ) {
  31832. super.deserialize( data );
  31833. this.scope = data.scope;
  31834. this.scale = data.scale;
  31835. }
  31836. }
  31837. TimerNode.LOCAL = 'local';
  31838. TimerNode.GLOBAL = 'global';
  31839. TimerNode.DELTA = 'delta';
  31840. TimerNode.FRAME = 'frame';
  31841. // @TODO: add support to use node in timeScale
  31842. const timerLocal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.LOCAL, timeScale, value ) );
  31843. const timerGlobal = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.GLOBAL, timeScale, value ) );
  31844. const timerDelta = ( timeScale, value = 0 ) => nodeObject( new TimerNode( TimerNode.DELTA, timeScale, value ) );
  31845. const frameId = /*@__PURE__*/ nodeImmutable( TimerNode, TimerNode.FRAME ).toUint();
  31846. class OscNode extends Node {
  31847. static get type() {
  31848. return 'OscNode';
  31849. }
  31850. constructor( method = OscNode.SINE, timeNode = timerLocal() ) {
  31851. super();
  31852. this.method = method;
  31853. this.timeNode = timeNode;
  31854. }
  31855. getNodeType( builder ) {
  31856. return this.timeNode.getNodeType( builder );
  31857. }
  31858. setup() {
  31859. const method = this.method;
  31860. const timeNode = nodeObject( this.timeNode );
  31861. let outputNode = null;
  31862. if ( method === OscNode.SINE ) {
  31863. outputNode = timeNode.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  31864. } else if ( method === OscNode.SQUARE ) {
  31865. outputNode = timeNode.fract().round();
  31866. } else if ( method === OscNode.TRIANGLE ) {
  31867. outputNode = timeNode.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  31868. } else if ( method === OscNode.SAWTOOTH ) {
  31869. outputNode = timeNode.fract();
  31870. }
  31871. return outputNode;
  31872. }
  31873. serialize( data ) {
  31874. super.serialize( data );
  31875. data.method = this.method;
  31876. }
  31877. deserialize( data ) {
  31878. super.deserialize( data );
  31879. this.method = data.method;
  31880. }
  31881. }
  31882. OscNode.SINE = 'sine';
  31883. OscNode.SQUARE = 'square';
  31884. OscNode.TRIANGLE = 'triangle';
  31885. OscNode.SAWTOOTH = 'sawtooth';
  31886. const oscSine = /*@__PURE__*/ nodeProxy( OscNode, OscNode.SINE );
  31887. const oscSquare = /*@__PURE__*/ nodeProxy( OscNode, OscNode.SQUARE );
  31888. const oscTriangle = /*@__PURE__*/ nodeProxy( OscNode, OscNode.TRIANGLE );
  31889. const oscSawtooth = /*@__PURE__*/ nodeProxy( OscNode, OscNode.SAWTOOTH );
  31890. class SpriteSheetUVNode extends Node {
  31891. static get type() {
  31892. return 'SpriteSheetUVNode';
  31893. }
  31894. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  31895. super( 'vec2' );
  31896. this.countNode = countNode;
  31897. this.uvNode = uvNode;
  31898. this.frameNode = frameNode;
  31899. }
  31900. setup() {
  31901. const { frameNode, uvNode, countNode } = this;
  31902. const { width, height } = countNode;
  31903. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  31904. const column = frameNum.mod( width );
  31905. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  31906. const scale = countNode.reciprocal();
  31907. const uvFrameOffset = vec2( column, row );
  31908. return uvNode.add( uvFrameOffset ).mul( scale );
  31909. }
  31910. }
  31911. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  31912. class StorageArrayElementNode extends ArrayElementNode {
  31913. static get type() {
  31914. return 'StorageArrayElementNode';
  31915. }
  31916. constructor( storageBufferNode, indexNode ) {
  31917. super( storageBufferNode, indexNode );
  31918. this.isStorageArrayElementNode = true;
  31919. }
  31920. set storageBufferNode( value ) {
  31921. this.node = value;
  31922. }
  31923. get storageBufferNode() {
  31924. return this.node;
  31925. }
  31926. setup( builder ) {
  31927. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  31928. if ( this.node.bufferObject === true ) {
  31929. builder.setupPBO( this.node );
  31930. }
  31931. }
  31932. return super.setup( builder );
  31933. }
  31934. generate( builder, output ) {
  31935. let snippet;
  31936. const isAssignContext = builder.context.assign;
  31937. //
  31938. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  31939. if ( this.node.bufferObject === true && isAssignContext !== true ) {
  31940. snippet = builder.generatePBO( this );
  31941. } else {
  31942. snippet = this.node.build( builder );
  31943. }
  31944. } else {
  31945. snippet = super.generate( builder );
  31946. }
  31947. if ( isAssignContext !== true ) {
  31948. const type = this.getNodeType( builder );
  31949. snippet = builder.format( snippet, type, output );
  31950. }
  31951. return snippet;
  31952. }
  31953. }
  31954. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  31955. class TriplanarTexturesNode extends Node {
  31956. static get type() {
  31957. return 'TriplanarTexturesNode';
  31958. }
  31959. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  31960. super( 'vec4' );
  31961. this.textureXNode = textureXNode;
  31962. this.textureYNode = textureYNode;
  31963. this.textureZNode = textureZNode;
  31964. this.scaleNode = scaleNode;
  31965. this.positionNode = positionNode;
  31966. this.normalNode = normalNode;
  31967. }
  31968. setup() {
  31969. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  31970. // Ref: https://github.com/keijiro/StandardTriplanar
  31971. // Blending factor of triplanar mapping
  31972. let bf = normalNode.abs().normalize();
  31973. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  31974. // Triplanar mapping
  31975. const tx = positionNode.yz.mul( scaleNode );
  31976. const ty = positionNode.zx.mul( scaleNode );
  31977. const tz = positionNode.xy.mul( scaleNode );
  31978. // Base color
  31979. const textureX = textureXNode.value;
  31980. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  31981. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  31982. const cx = texture( textureX, tx ).mul( bf.x );
  31983. const cy = texture( textureY, ty ).mul( bf.y );
  31984. const cz = texture( textureZ, tz ).mul( bf.z );
  31985. return add( cx, cy, cz );
  31986. }
  31987. }
  31988. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  31989. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  31990. const _reflectorPlane = new Plane();
  31991. const _normal = new Vector3();
  31992. const _reflectorWorldPosition = new Vector3();
  31993. const _cameraWorldPosition = new Vector3();
  31994. const _rotationMatrix = new Matrix4();
  31995. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  31996. const clipPlane = new Vector4();
  31997. const _view = new Vector3();
  31998. const _target = new Vector3();
  31999. const _q = new Vector4();
  32000. const _size$9 = new Vector2();
  32001. const _defaultRT = new RenderTarget();
  32002. const _defaultUV = screenUV.flipX();
  32003. let _inReflector = false;
  32004. class ReflectorNode extends TextureNode {
  32005. static get type() {
  32006. return 'ReflectorNode';
  32007. }
  32008. constructor( parameters = {} ) {
  32009. super( _defaultRT.texture, _defaultUV );
  32010. const {
  32011. target = new Object3D(),
  32012. resolution = 1,
  32013. generateMipmaps = false,
  32014. bounces = true
  32015. } = parameters;
  32016. //
  32017. this.target = target;
  32018. this.resolution = resolution;
  32019. this.generateMipmaps = generateMipmaps;
  32020. this.bounces = bounces;
  32021. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  32022. this.virtualCameras = new WeakMap();
  32023. this.renderTargets = new WeakMap();
  32024. }
  32025. _updateResolution( renderTarget, renderer ) {
  32026. const resolution = this.resolution;
  32027. renderer.getDrawingBufferSize( _size$9 );
  32028. renderTarget.setSize( Math.round( _size$9.width * resolution ), Math.round( _size$9.height * resolution ) );
  32029. }
  32030. setup( builder ) {
  32031. this._updateResolution( _defaultRT, builder.renderer );
  32032. return super.setup( builder );
  32033. }
  32034. getTextureNode() {
  32035. return this.textureNode;
  32036. }
  32037. getVirtualCamera( camera ) {
  32038. let virtualCamera = this.virtualCameras.get( camera );
  32039. if ( virtualCamera === undefined ) {
  32040. virtualCamera = camera.clone();
  32041. this.virtualCameras.set( camera, virtualCamera );
  32042. }
  32043. return virtualCamera;
  32044. }
  32045. getRenderTarget( camera ) {
  32046. let renderTarget = this.renderTargets.get( camera );
  32047. if ( renderTarget === undefined ) {
  32048. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  32049. if ( this.generateMipmaps === true ) {
  32050. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  32051. renderTarget.texture.generateMipmaps = true;
  32052. }
  32053. this.renderTargets.set( camera, renderTarget );
  32054. }
  32055. return renderTarget;
  32056. }
  32057. updateBefore( frame ) {
  32058. if ( this.bounces === false && _inReflector ) return false;
  32059. _inReflector = true;
  32060. const { scene, camera, renderer, material } = frame;
  32061. const { target } = this;
  32062. const virtualCamera = this.getVirtualCamera( camera );
  32063. const renderTarget = this.getRenderTarget( virtualCamera );
  32064. renderer.getDrawingBufferSize( _size$9 );
  32065. this._updateResolution( renderTarget, renderer );
  32066. //
  32067. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  32068. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  32069. _rotationMatrix.extractRotation( target.matrixWorld );
  32070. _normal.set( 0, 0, 1 );
  32071. _normal.applyMatrix4( _rotationMatrix );
  32072. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  32073. // Avoid rendering when reflector is facing away
  32074. if ( _view.dot( _normal ) > 0 ) return;
  32075. _view.reflect( _normal ).negate();
  32076. _view.add( _reflectorWorldPosition );
  32077. _rotationMatrix.extractRotation( camera.matrixWorld );
  32078. _lookAtPosition.set( 0, 0, - 1 );
  32079. _lookAtPosition.applyMatrix4( _rotationMatrix );
  32080. _lookAtPosition.add( _cameraWorldPosition );
  32081. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  32082. _target.reflect( _normal ).negate();
  32083. _target.add( _reflectorWorldPosition );
  32084. //
  32085. virtualCamera.coordinateSystem = camera.coordinateSystem;
  32086. virtualCamera.position.copy( _view );
  32087. virtualCamera.up.set( 0, 1, 0 );
  32088. virtualCamera.up.applyMatrix4( _rotationMatrix );
  32089. virtualCamera.up.reflect( _normal );
  32090. virtualCamera.lookAt( _target );
  32091. virtualCamera.near = camera.near;
  32092. virtualCamera.far = camera.far;
  32093. virtualCamera.updateMatrixWorld();
  32094. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  32095. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  32096. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  32097. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  32098. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  32099. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  32100. const projectionMatrix = virtualCamera.projectionMatrix;
  32101. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  32102. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  32103. _q.z = - 1.0;
  32104. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  32105. // Calculate the scaled plane vector
  32106. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  32107. const clipBias = 0;
  32108. // Replacing the third row of the projection matrix
  32109. projectionMatrix.elements[ 2 ] = clipPlane.x;
  32110. projectionMatrix.elements[ 6 ] = clipPlane.y;
  32111. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  32112. projectionMatrix.elements[ 14 ] = clipPlane.w;
  32113. //
  32114. this.value = renderTarget.texture;
  32115. material.visible = false;
  32116. const currentRenderTarget = renderer.getRenderTarget();
  32117. const currentMRT = renderer.getMRT();
  32118. renderer.setMRT( null );
  32119. renderer.setRenderTarget( renderTarget );
  32120. renderer.render( scene, virtualCamera );
  32121. renderer.setMRT( currentMRT );
  32122. renderer.setRenderTarget( currentRenderTarget );
  32123. material.visible = true;
  32124. _inReflector = false;
  32125. }
  32126. }
  32127. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  32128. // Helper for passes that need to fill the viewport with a single quad.
  32129. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  32130. // https://github.com/mrdoob/three.js/pull/21358
  32131. class QuadGeometry extends BufferGeometry {
  32132. constructor( flipY = false ) {
  32133. super();
  32134. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  32135. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  32136. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  32137. }
  32138. }
  32139. const _geometry = /*@__PURE__*/ new QuadGeometry();
  32140. class QuadMesh extends Mesh {
  32141. constructor( material = null ) {
  32142. super( _geometry, material );
  32143. this.camera = _camera;
  32144. this.isQuadMesh = true;
  32145. }
  32146. renderAsync( renderer ) {
  32147. return renderer.renderAsync( this, _camera );
  32148. }
  32149. render( renderer ) {
  32150. renderer.render( this, _camera );
  32151. }
  32152. }
  32153. const _size$8 = /*@__PURE__*/ new Vector2();
  32154. class RTTNode extends TextureNode {
  32155. static get type() {
  32156. return 'RTTNode';
  32157. }
  32158. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  32159. const renderTarget = new RenderTarget( width, height, options );
  32160. super( renderTarget.texture, uv() );
  32161. this.node = node;
  32162. this.width = width;
  32163. this.height = height;
  32164. this.renderTarget = renderTarget;
  32165. this.textureNeedsUpdate = true;
  32166. this.autoUpdate = true;
  32167. this.updateMap = new WeakMap();
  32168. this._rttNode = null;
  32169. this._quadMesh = new QuadMesh( new NodeMaterial() );
  32170. this.updateBeforeType = NodeUpdateType.RENDER;
  32171. }
  32172. get autoSize() {
  32173. return this.width === null;
  32174. }
  32175. setup( builder ) {
  32176. this._rttNode = this.node.context( builder.getSharedContext() );
  32177. this._quadMesh.material.name = 'RTT';
  32178. this._quadMesh.material.needsUpdate = true;
  32179. return super.setup( builder );
  32180. }
  32181. setSize( width, height ) {
  32182. this.width = width;
  32183. this.height = height;
  32184. const effectiveWidth = width * this.pixelRatio;
  32185. const effectiveHeight = height * this.pixelRatio;
  32186. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  32187. this.textureNeedsUpdate = true;
  32188. }
  32189. setPixelRatio( pixelRatio ) {
  32190. this.pixelRatio = pixelRatio;
  32191. this.setSize( this.width, this.height );
  32192. }
  32193. updateBefore( { renderer } ) {
  32194. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  32195. this.textureNeedsUpdate = false;
  32196. //
  32197. if ( this.autoSize === true ) {
  32198. this.pixelRatio = renderer.getPixelRatio();
  32199. const size = renderer.getSize( _size$8 );
  32200. this.setSize( size.width, size.height );
  32201. }
  32202. //
  32203. this._quadMesh.material.fragmentNode = this._rttNode;
  32204. //
  32205. const currentRenderTarget = renderer.getRenderTarget();
  32206. renderer.setRenderTarget( this.renderTarget );
  32207. this._quadMesh.render( renderer );
  32208. renderer.setRenderTarget( currentRenderTarget );
  32209. }
  32210. clone() {
  32211. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  32212. newNode.sampler = this.sampler;
  32213. newNode.referenceNode = this;
  32214. return newNode;
  32215. }
  32216. }
  32217. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  32218. const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params );
  32219. class VertexColorNode extends AttributeNode {
  32220. static get type() {
  32221. return 'VertexColorNode';
  32222. }
  32223. constructor( index = 0 ) {
  32224. super( null, 'vec4' );
  32225. this.isVertexColorNode = true;
  32226. this.index = index;
  32227. }
  32228. getAttributeName( /*builder*/ ) {
  32229. const index = this.index;
  32230. return 'color' + ( index > 0 ? index : '' );
  32231. }
  32232. generate( builder ) {
  32233. const attributeName = this.getAttributeName( builder );
  32234. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  32235. let result;
  32236. if ( geometryAttribute === true ) {
  32237. result = super.generate( builder );
  32238. } else {
  32239. // Vertex color fallback should be white
  32240. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  32241. }
  32242. return result;
  32243. }
  32244. serialize( data ) {
  32245. super.serialize( data );
  32246. data.index = this.index;
  32247. }
  32248. deserialize( data ) {
  32249. super.deserialize( data );
  32250. this.index = data.index;
  32251. }
  32252. }
  32253. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  32254. class PointUVNode extends Node {
  32255. static get type() {
  32256. return 'PointUVNode';
  32257. }
  32258. constructor() {
  32259. super( 'vec2' );
  32260. this.isPointUVNode = true;
  32261. }
  32262. generate( /*builder*/ ) {
  32263. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  32264. }
  32265. }
  32266. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  32267. class SceneNode extends Node {
  32268. static get type() {
  32269. return 'SceneNode';
  32270. }
  32271. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  32272. super();
  32273. this.scope = scope;
  32274. this.scene = scene;
  32275. }
  32276. setup( builder ) {
  32277. const scope = this.scope;
  32278. const scene = this.scene !== null ? this.scene : builder.scene;
  32279. let output;
  32280. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  32281. output = reference( 'backgroundBlurriness', 'float', scene );
  32282. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  32283. output = reference( 'backgroundIntensity', 'float', scene );
  32284. } else {
  32285. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  32286. }
  32287. return output;
  32288. }
  32289. }
  32290. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  32291. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  32292. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  32293. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  32294. const GPUPrimitiveTopology = {
  32295. PointList: 'point-list',
  32296. LineList: 'line-list',
  32297. LineStrip: 'line-strip',
  32298. TriangleList: 'triangle-list',
  32299. TriangleStrip: 'triangle-strip',
  32300. };
  32301. const GPUCompareFunction = {
  32302. Never: 'never',
  32303. Less: 'less',
  32304. Equal: 'equal',
  32305. LessEqual: 'less-equal',
  32306. Greater: 'greater',
  32307. NotEqual: 'not-equal',
  32308. GreaterEqual: 'greater-equal',
  32309. Always: 'always'
  32310. };
  32311. const GPUStoreOp = {
  32312. Store: 'store',
  32313. Discard: 'discard'
  32314. };
  32315. const GPULoadOp = {
  32316. Load: 'load',
  32317. Clear: 'clear'
  32318. };
  32319. const GPUFrontFace = {
  32320. CCW: 'ccw',
  32321. CW: 'cw'
  32322. };
  32323. const GPUCullMode = {
  32324. None: 'none',
  32325. Front: 'front',
  32326. Back: 'back'
  32327. };
  32328. const GPUIndexFormat = {
  32329. Uint16: 'uint16',
  32330. Uint32: 'uint32'
  32331. };
  32332. const GPUTextureFormat = {
  32333. // 8-bit formats
  32334. R8Unorm: 'r8unorm',
  32335. R8Snorm: 'r8snorm',
  32336. R8Uint: 'r8uint',
  32337. R8Sint: 'r8sint',
  32338. // 16-bit formats
  32339. R16Uint: 'r16uint',
  32340. R16Sint: 'r16sint',
  32341. R16Float: 'r16float',
  32342. RG8Unorm: 'rg8unorm',
  32343. RG8Snorm: 'rg8snorm',
  32344. RG8Uint: 'rg8uint',
  32345. RG8Sint: 'rg8sint',
  32346. // 32-bit formats
  32347. R32Uint: 'r32uint',
  32348. R32Sint: 'r32sint',
  32349. R32Float: 'r32float',
  32350. RG16Uint: 'rg16uint',
  32351. RG16Sint: 'rg16sint',
  32352. RG16Float: 'rg16float',
  32353. RGBA8Unorm: 'rgba8unorm',
  32354. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  32355. RGBA8Snorm: 'rgba8snorm',
  32356. RGBA8Uint: 'rgba8uint',
  32357. RGBA8Sint: 'rgba8sint',
  32358. BGRA8Unorm: 'bgra8unorm',
  32359. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  32360. // Packed 32-bit formats
  32361. RGB9E5UFloat: 'rgb9e5ufloat',
  32362. RGB10A2Unorm: 'rgb10a2unorm',
  32363. RG11B10uFloat: 'rgb10a2unorm',
  32364. // 64-bit formats
  32365. RG32Uint: 'rg32uint',
  32366. RG32Sint: 'rg32sint',
  32367. RG32Float: 'rg32float',
  32368. RGBA16Uint: 'rgba16uint',
  32369. RGBA16Sint: 'rgba16sint',
  32370. RGBA16Float: 'rgba16float',
  32371. // 128-bit formats
  32372. RGBA32Uint: 'rgba32uint',
  32373. RGBA32Sint: 'rgba32sint',
  32374. RGBA32Float: 'rgba32float',
  32375. // Depth and stencil formats
  32376. Stencil8: 'stencil8',
  32377. Depth16Unorm: 'depth16unorm',
  32378. Depth24Plus: 'depth24plus',
  32379. Depth24PlusStencil8: 'depth24plus-stencil8',
  32380. Depth32Float: 'depth32float',
  32381. // 'depth32float-stencil8' extension
  32382. Depth32FloatStencil8: 'depth32float-stencil8',
  32383. // BC compressed formats usable if 'texture-compression-bc' is both
  32384. // supported by the device/user agent and enabled in requestDevice.
  32385. BC1RGBAUnorm: 'bc1-rgba-unorm',
  32386. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  32387. BC2RGBAUnorm: 'bc2-rgba-unorm',
  32388. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  32389. BC3RGBAUnorm: 'bc3-rgba-unorm',
  32390. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  32391. BC4RUnorm: 'bc4-r-unorm',
  32392. BC4RSnorm: 'bc4-r-snorm',
  32393. BC5RGUnorm: 'bc5-rg-unorm',
  32394. BC5RGSnorm: 'bc5-rg-snorm',
  32395. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  32396. BC6HRGBFloat: 'bc6h-rgb-float',
  32397. BC7RGBAUnorm: 'bc7-rgba-unorm',
  32398. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  32399. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  32400. // supported by the device/user agent and enabled in requestDevice.
  32401. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  32402. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  32403. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  32404. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  32405. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  32406. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  32407. EACR11Unorm: 'eac-r11unorm',
  32408. EACR11Snorm: 'eac-r11snorm',
  32409. EACRG11Unorm: 'eac-rg11unorm',
  32410. EACRG11Snorm: 'eac-rg11snorm',
  32411. // ASTC compressed formats usable if 'texture-compression-astc' is both
  32412. // supported by the device/user agent and enabled in requestDevice.
  32413. ASTC4x4Unorm: 'astc-4x4-unorm',
  32414. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  32415. ASTC5x4Unorm: 'astc-5x4-unorm',
  32416. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  32417. ASTC5x5Unorm: 'astc-5x5-unorm',
  32418. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  32419. ASTC6x5Unorm: 'astc-6x5-unorm',
  32420. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  32421. ASTC6x6Unorm: 'astc-6x6-unorm',
  32422. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  32423. ASTC8x5Unorm: 'astc-8x5-unorm',
  32424. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  32425. ASTC8x6Unorm: 'astc-8x6-unorm',
  32426. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  32427. ASTC8x8Unorm: 'astc-8x8-unorm',
  32428. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  32429. ASTC10x5Unorm: 'astc-10x5-unorm',
  32430. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  32431. ASTC10x6Unorm: 'astc-10x6-unorm',
  32432. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  32433. ASTC10x8Unorm: 'astc-10x8-unorm',
  32434. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  32435. ASTC10x10Unorm: 'astc-10x10-unorm',
  32436. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  32437. ASTC12x10Unorm: 'astc-12x10-unorm',
  32438. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  32439. ASTC12x12Unorm: 'astc-12x12-unorm',
  32440. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  32441. };
  32442. const GPUAddressMode = {
  32443. ClampToEdge: 'clamp-to-edge',
  32444. Repeat: 'repeat',
  32445. MirrorRepeat: 'mirror-repeat'
  32446. };
  32447. const GPUFilterMode = {
  32448. Linear: 'linear',
  32449. Nearest: 'nearest'
  32450. };
  32451. const GPUBlendFactor = {
  32452. Zero: 'zero',
  32453. One: 'one',
  32454. Src: 'src',
  32455. OneMinusSrc: 'one-minus-src',
  32456. SrcAlpha: 'src-alpha',
  32457. OneMinusSrcAlpha: 'one-minus-src-alpha',
  32458. Dst: 'dst',
  32459. OneMinusDstColor: 'one-minus-dst',
  32460. DstAlpha: 'dst-alpha',
  32461. OneMinusDstAlpha: 'one-minus-dst-alpha',
  32462. SrcAlphaSaturated: 'src-alpha-saturated',
  32463. Constant: 'constant',
  32464. OneMinusConstant: 'one-minus-constant'
  32465. };
  32466. const GPUBlendOperation = {
  32467. Add: 'add',
  32468. Subtract: 'subtract',
  32469. ReverseSubtract: 'reverse-subtract',
  32470. Min: 'min',
  32471. Max: 'max'
  32472. };
  32473. const GPUColorWriteFlags = {
  32474. None: 0,
  32475. Red: 0x1,
  32476. Green: 0x2,
  32477. Blue: 0x4,
  32478. Alpha: 0x8,
  32479. All: 0xF
  32480. };
  32481. const GPUStencilOperation = {
  32482. Keep: 'keep',
  32483. Zero: 'zero',
  32484. Replace: 'replace',
  32485. Invert: 'invert',
  32486. IncrementClamp: 'increment-clamp',
  32487. DecrementClamp: 'decrement-clamp',
  32488. IncrementWrap: 'increment-wrap',
  32489. DecrementWrap: 'decrement-wrap'
  32490. };
  32491. const GPUBufferBindingType = {
  32492. Uniform: 'uniform',
  32493. Storage: 'storage',
  32494. ReadOnlyStorage: 'read-only-storage'
  32495. };
  32496. const GPUStorageTextureAccess = {
  32497. WriteOnly: 'write-only',
  32498. ReadOnly: 'read-only',
  32499. ReadWrite: 'read-write',
  32500. };
  32501. const GPUTextureSampleType = {
  32502. Float: 'float',
  32503. UnfilterableFloat: 'unfilterable-float',
  32504. Depth: 'depth',
  32505. SInt: 'sint',
  32506. UInt: 'uint'
  32507. };
  32508. const GPUTextureDimension = {
  32509. OneD: '1d',
  32510. TwoD: '2d',
  32511. ThreeD: '3d'
  32512. };
  32513. const GPUTextureViewDimension = {
  32514. OneD: '1d',
  32515. TwoD: '2d',
  32516. TwoDArray: '2d-array',
  32517. Cube: 'cube',
  32518. CubeArray: 'cube-array',
  32519. ThreeD: '3d'
  32520. };
  32521. const GPUTextureAspect = {
  32522. All: 'all',
  32523. StencilOnly: 'stencil-only',
  32524. DepthOnly: 'depth-only'
  32525. };
  32526. const GPUInputStepMode = {
  32527. Vertex: 'vertex',
  32528. Instance: 'instance'
  32529. };
  32530. const GPUFeatureName = {
  32531. DepthClipControl: 'depth-clip-control',
  32532. Depth32FloatStencil8: 'depth32float-stencil8',
  32533. TextureCompressionBC: 'texture-compression-bc',
  32534. TextureCompressionETC2: 'texture-compression-etc2',
  32535. TextureCompressionASTC: 'texture-compression-astc',
  32536. TimestampQuery: 'timestamp-query',
  32537. IndirectFirstInstance: 'indirect-first-instance',
  32538. ShaderF16: 'shader-f16',
  32539. RG11B10UFloat: 'rg11b10ufloat-renderable',
  32540. BGRA8UNormStorage: 'bgra8unorm-storage',
  32541. Float32Filterable: 'float32-filterable',
  32542. ClipDistances: 'clip-distances',
  32543. DualSourceBlending: 'dual-source-blending',
  32544. Subgroups: 'subgroups'
  32545. };
  32546. class StorageBufferNode extends BufferNode {
  32547. static get type() {
  32548. return 'StorageBufferNode';
  32549. }
  32550. constructor( value, bufferType, bufferCount = 0 ) {
  32551. super( value, bufferType, bufferCount );
  32552. this.isStorageBufferNode = true;
  32553. this.access = GPUBufferBindingType.Storage;
  32554. this.isAtomic = false;
  32555. this.bufferObject = false;
  32556. this.bufferCount = bufferCount;
  32557. this._attribute = null;
  32558. this._varying = null;
  32559. this.global = true;
  32560. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  32561. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  32562. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  32563. else value.isStorageBufferAttribute = true;
  32564. }
  32565. }
  32566. getHash( builder ) {
  32567. if ( this.bufferCount === 0 ) {
  32568. let bufferData = builder.globalCache.getData( this.value );
  32569. if ( bufferData === undefined ) {
  32570. bufferData = {
  32571. node: this
  32572. };
  32573. builder.globalCache.setData( this.value, bufferData );
  32574. }
  32575. return bufferData.node.uuid;
  32576. }
  32577. return this.uuid;
  32578. }
  32579. getInputType( /*builder*/ ) {
  32580. return 'storageBuffer';
  32581. }
  32582. element( indexNode ) {
  32583. return storageElement( this, indexNode );
  32584. }
  32585. setBufferObject( value ) {
  32586. this.bufferObject = value;
  32587. return this;
  32588. }
  32589. setAccess( value ) {
  32590. this.access = value;
  32591. return this;
  32592. }
  32593. toReadOnly() {
  32594. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  32595. }
  32596. setAtomic( value ) {
  32597. this.isAtomic = value;
  32598. return this;
  32599. }
  32600. toAtomic() {
  32601. return this.setAtomic( true );
  32602. }
  32603. generate( builder ) {
  32604. if ( builder.isAvailable( 'storageBuffer' ) ) {
  32605. return super.generate( builder );
  32606. }
  32607. const nodeType = this.getNodeType( builder );
  32608. if ( this._attribute === null ) {
  32609. this._attribute = bufferAttribute( this.value );
  32610. this._varying = varying( this._attribute );
  32611. }
  32612. const output = this._varying.build( builder, nodeType );
  32613. builder.registerTransform( output, this._attribute );
  32614. return output;
  32615. }
  32616. }
  32617. // Read-Write Storage
  32618. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  32619. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  32620. class StorageTextureNode extends TextureNode {
  32621. static get type() {
  32622. return 'StorageTextureNode';
  32623. }
  32624. constructor( value, uvNode, storeNode = null ) {
  32625. super( value, uvNode );
  32626. this.storeNode = storeNode;
  32627. this.isStorageTextureNode = true;
  32628. this.access = GPUStorageTextureAccess.WriteOnly;
  32629. }
  32630. getInputType( /*builder*/ ) {
  32631. return 'storageTexture';
  32632. }
  32633. setup( builder ) {
  32634. super.setup( builder );
  32635. const properties = builder.getNodeProperties( this );
  32636. properties.storeNode = this.storeNode;
  32637. }
  32638. setAccess( value ) {
  32639. this.access = value;
  32640. return this;
  32641. }
  32642. generate( builder, output ) {
  32643. let snippet;
  32644. if ( this.storeNode !== null ) {
  32645. snippet = this.generateStore( builder );
  32646. } else {
  32647. snippet = super.generate( builder, output );
  32648. }
  32649. return snippet;
  32650. }
  32651. toReadOnly() {
  32652. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  32653. }
  32654. toWriteOnly() {
  32655. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  32656. }
  32657. generateStore( builder ) {
  32658. const properties = builder.getNodeProperties( this );
  32659. const { uvNode, storeNode } = properties;
  32660. const textureProperty = super.generate( builder, 'property' );
  32661. const uvSnippet = uvNode.build( builder, 'uvec2' );
  32662. const storeSnippet = storeNode.build( builder, 'vec4' );
  32663. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  32664. builder.addLineFlowCode( snippet );
  32665. }
  32666. }
  32667. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  32668. const textureStore = ( value, uvNode, storeNode ) => {
  32669. const node = storageTexture( value, uvNode, storeNode );
  32670. if ( storeNode !== null ) node.append();
  32671. return node;
  32672. };
  32673. class UserDataNode extends ReferenceNode {
  32674. static get type() {
  32675. return 'UserDataNode';
  32676. }
  32677. constructor( property, inputType, userData = null ) {
  32678. super( property, inputType, userData );
  32679. this.userData = userData;
  32680. }
  32681. updateReference( state ) {
  32682. this.reference = this.userData !== null ? this.userData : state.object.userData;
  32683. return this.reference;
  32684. }
  32685. }
  32686. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  32687. class PosterizeNode extends TempNode {
  32688. static get type() {
  32689. return 'PosterizeNode';
  32690. }
  32691. constructor( sourceNode, stepsNode ) {
  32692. super();
  32693. this.sourceNode = sourceNode;
  32694. this.stepsNode = stepsNode;
  32695. }
  32696. setup() {
  32697. const { sourceNode, stepsNode } = this;
  32698. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  32699. }
  32700. }
  32701. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  32702. let _sharedFramebuffer = null;
  32703. class ViewportSharedTextureNode extends ViewportTextureNode {
  32704. static get type() {
  32705. return 'ViewportSharedTextureNode';
  32706. }
  32707. constructor( uvNode = screenUV, levelNode = null ) {
  32708. if ( _sharedFramebuffer === null ) {
  32709. _sharedFramebuffer = new FramebufferTexture();
  32710. }
  32711. super( uvNode, levelNode, _sharedFramebuffer );
  32712. }
  32713. updateReference() {
  32714. return this;
  32715. }
  32716. }
  32717. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  32718. const _size$7 = /*@__PURE__*/ new Vector2();
  32719. class PassTextureNode extends TextureNode {
  32720. static get type() {
  32721. return 'PassTextureNode';
  32722. }
  32723. constructor( passNode, texture ) {
  32724. super( texture );
  32725. this.passNode = passNode;
  32726. this.setUpdateMatrix( false );
  32727. }
  32728. setup( builder ) {
  32729. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  32730. return super.setup( builder );
  32731. }
  32732. clone() {
  32733. return new this.constructor( this.passNode, this.value );
  32734. }
  32735. }
  32736. class PassMultipleTextureNode extends PassTextureNode {
  32737. static get type() {
  32738. return 'PassMultipleTextureNode';
  32739. }
  32740. constructor( passNode, textureName, previousTexture = false ) {
  32741. super( passNode, null );
  32742. this.textureName = textureName;
  32743. this.previousTexture = previousTexture;
  32744. }
  32745. updateTexture() {
  32746. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  32747. }
  32748. setup( builder ) {
  32749. this.updateTexture();
  32750. return super.setup( builder );
  32751. }
  32752. clone() {
  32753. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  32754. }
  32755. }
  32756. class PassNode extends TempNode {
  32757. static get type() {
  32758. return 'PassNode';
  32759. }
  32760. constructor( scope, scene, camera, options = {} ) {
  32761. super( 'vec4' );
  32762. this.scope = scope;
  32763. this.scene = scene;
  32764. this.camera = camera;
  32765. this.options = options;
  32766. this._pixelRatio = 1;
  32767. this._width = 1;
  32768. this._height = 1;
  32769. const depthTexture = new DepthTexture();
  32770. depthTexture.isRenderTargetTexture = true;
  32771. //depthTexture.type = FloatType;
  32772. depthTexture.name = 'depth';
  32773. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  32774. renderTarget.texture.name = 'output';
  32775. renderTarget.depthTexture = depthTexture;
  32776. this.renderTarget = renderTarget;
  32777. this.updateBeforeType = NodeUpdateType.FRAME;
  32778. this._textures = {
  32779. output: renderTarget.texture,
  32780. depth: depthTexture
  32781. };
  32782. this._textureNodes = {};
  32783. this._linearDepthNodes = {};
  32784. this._viewZNodes = {};
  32785. this._previousTextures = {};
  32786. this._previousTextureNodes = {};
  32787. this._cameraNear = uniform( 0 );
  32788. this._cameraFar = uniform( 0 );
  32789. this._mrt = null;
  32790. this.isPassNode = true;
  32791. }
  32792. setMRT( mrt ) {
  32793. this._mrt = mrt;
  32794. return this;
  32795. }
  32796. getMRT() {
  32797. return this._mrt;
  32798. }
  32799. isGlobal() {
  32800. return true;
  32801. }
  32802. getTexture( name ) {
  32803. let texture = this._textures[ name ];
  32804. if ( texture === undefined ) {
  32805. const refTexture = this.renderTarget.texture;
  32806. texture = refTexture.clone();
  32807. texture.isRenderTargetTexture = true;
  32808. texture.name = name;
  32809. this._textures[ name ] = texture;
  32810. this.renderTarget.textures.push( texture );
  32811. }
  32812. return texture;
  32813. }
  32814. getPreviousTexture( name ) {
  32815. let texture = this._previousTextures[ name ];
  32816. if ( texture === undefined ) {
  32817. texture = this.getTexture( name ).clone();
  32818. texture.isRenderTargetTexture = true;
  32819. this._previousTextures[ name ] = texture;
  32820. }
  32821. return texture;
  32822. }
  32823. toggleTexture( name ) {
  32824. const prevTexture = this._previousTextures[ name ];
  32825. if ( prevTexture !== undefined ) {
  32826. const texture = this._textures[ name ];
  32827. const index = this.renderTarget.textures.indexOf( texture );
  32828. this.renderTarget.textures[ index ] = prevTexture;
  32829. this._textures[ name ] = prevTexture;
  32830. this._previousTextures[ name ] = texture;
  32831. this._textureNodes[ name ].updateTexture();
  32832. this._previousTextureNodes[ name ].updateTexture();
  32833. }
  32834. }
  32835. getTextureNode( name = 'output' ) {
  32836. let textureNode = this._textureNodes[ name ];
  32837. if ( textureNode === undefined ) {
  32838. this._textureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  32839. this._textureNodes[ name ].updateTexture();
  32840. }
  32841. return textureNode;
  32842. }
  32843. getPreviousTextureNode( name = 'output' ) {
  32844. let textureNode = this._previousTextureNodes[ name ];
  32845. if ( textureNode === undefined ) {
  32846. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  32847. this._previousTextureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  32848. this._previousTextureNodes[ name ].updateTexture();
  32849. }
  32850. return textureNode;
  32851. }
  32852. getViewZNode( name = 'depth' ) {
  32853. let viewZNode = this._viewZNodes[ name ];
  32854. if ( viewZNode === undefined ) {
  32855. const cameraNear = this._cameraNear;
  32856. const cameraFar = this._cameraFar;
  32857. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  32858. }
  32859. return viewZNode;
  32860. }
  32861. getLinearDepthNode( name = 'depth' ) {
  32862. let linearDepthNode = this._linearDepthNodes[ name ];
  32863. if ( linearDepthNode === undefined ) {
  32864. const cameraNear = this._cameraNear;
  32865. const cameraFar = this._cameraFar;
  32866. const viewZNode = this.getViewZNode( name );
  32867. // TODO: just if ( builder.camera.isPerspectiveCamera )
  32868. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  32869. }
  32870. return linearDepthNode;
  32871. }
  32872. setup( { renderer } ) {
  32873. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  32874. // Disable MSAA for WebGL backend for now
  32875. if ( renderer.backend.isWebGLBackend === true ) {
  32876. this.renderTarget.samples = 0;
  32877. }
  32878. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  32879. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  32880. }
  32881. updateBefore( frame ) {
  32882. const { renderer } = frame;
  32883. const { scene, camera } = this;
  32884. this._pixelRatio = renderer.getPixelRatio();
  32885. const size = renderer.getSize( _size$7 );
  32886. this.setSize( size.width, size.height );
  32887. const currentRenderTarget = renderer.getRenderTarget();
  32888. const currentMRT = renderer.getMRT();
  32889. this._cameraNear.value = camera.near;
  32890. this._cameraFar.value = camera.far;
  32891. for ( const name in this._previousTextures ) {
  32892. this.toggleTexture( name );
  32893. }
  32894. renderer.setRenderTarget( this.renderTarget );
  32895. renderer.setMRT( this._mrt );
  32896. renderer.render( scene, camera );
  32897. renderer.setRenderTarget( currentRenderTarget );
  32898. renderer.setMRT( currentMRT );
  32899. }
  32900. setSize( width, height ) {
  32901. this._width = width;
  32902. this._height = height;
  32903. const effectiveWidth = this._width * this._pixelRatio;
  32904. const effectiveHeight = this._height * this._pixelRatio;
  32905. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  32906. }
  32907. setPixelRatio( pixelRatio ) {
  32908. this._pixelRatio = pixelRatio;
  32909. this.setSize( this._width, this._height );
  32910. }
  32911. dispose() {
  32912. this.renderTarget.dispose();
  32913. }
  32914. }
  32915. PassNode.COLOR = 'color';
  32916. PassNode.DEPTH = 'depth';
  32917. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  32918. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  32919. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  32920. // WebGPU: The use of a single QuadMesh for both gaussian blur passes results in a single RenderObject with a SampledTexture binding that
  32921. // alternates between source textures and triggers creation of new BindGroups and BindGroupLayouts every frame.
  32922. const _quadMesh1 = /*@__PURE__*/ new QuadMesh();
  32923. const _quadMesh2 = /*@__PURE__*/ new QuadMesh();
  32924. class GaussianBlurNode extends TempNode {
  32925. static get type() {
  32926. return 'GaussianBlurNode';
  32927. }
  32928. constructor( textureNode, directionNode = null, sigma = 2 ) {
  32929. super( 'vec4' );
  32930. this.textureNode = textureNode;
  32931. this.directionNode = directionNode;
  32932. this.sigma = sigma;
  32933. this._invSize = uniform( new Vector2() );
  32934. this._passDirection = uniform( new Vector2() );
  32935. this._horizontalRT = new RenderTarget();
  32936. this._horizontalRT.texture.name = 'GaussianBlurNode.horizontal';
  32937. this._verticalRT = new RenderTarget();
  32938. this._verticalRT.texture.name = 'GaussianBlurNode.vertical';
  32939. this._textureNode = passTexture( this, this._verticalRT.texture );
  32940. this.updateBeforeType = NodeUpdateType.RENDER;
  32941. this.resolution = new Vector2( 1, 1 );
  32942. }
  32943. setSize( width, height ) {
  32944. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  32945. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  32946. this._invSize.value.set( 1 / width, 1 / height );
  32947. this._horizontalRT.setSize( width, height );
  32948. this._verticalRT.setSize( width, height );
  32949. }
  32950. updateBefore( frame ) {
  32951. const { renderer } = frame;
  32952. const textureNode = this.textureNode;
  32953. const map = textureNode.value;
  32954. const currentRenderTarget = renderer.getRenderTarget();
  32955. const currentMRT = renderer.getMRT();
  32956. const currentTexture = textureNode.value;
  32957. _quadMesh1.material = this._material;
  32958. _quadMesh2.material = this._material;
  32959. this.setSize( map.image.width, map.image.height );
  32960. const textureType = map.type;
  32961. this._horizontalRT.texture.type = textureType;
  32962. this._verticalRT.texture.type = textureType;
  32963. // clear
  32964. renderer.setMRT( null );
  32965. // horizontal
  32966. renderer.setRenderTarget( this._horizontalRT );
  32967. this._passDirection.value.set( 1, 0 );
  32968. _quadMesh1.render( renderer );
  32969. // vertical
  32970. textureNode.value = this._horizontalRT.texture;
  32971. renderer.setRenderTarget( this._verticalRT );
  32972. this._passDirection.value.set( 0, 1 );
  32973. _quadMesh2.render( renderer );
  32974. // restore
  32975. renderer.setRenderTarget( currentRenderTarget );
  32976. renderer.setMRT( currentMRT );
  32977. textureNode.value = currentTexture;
  32978. }
  32979. getTextureNode() {
  32980. return this._textureNode;
  32981. }
  32982. setup( builder ) {
  32983. const textureNode = this.textureNode;
  32984. if ( textureNode.isTextureNode !== true ) {
  32985. console.error( 'GaussianBlurNode requires a TextureNode.' );
  32986. return vec4();
  32987. }
  32988. //
  32989. const uvNode = textureNode.uvNode || uv();
  32990. const directionNode = vec2( this.directionNode || 1 );
  32991. const sampleTexture = ( uv ) => textureNode.uv( uv );
  32992. const blur = Fn( () => {
  32993. const kernelSize = 3 + ( 2 * this.sigma );
  32994. const gaussianCoefficients = this._getCoefficients( kernelSize );
  32995. const invSize = this._invSize;
  32996. const direction = directionNode.mul( this._passDirection );
  32997. const weightSum = float( gaussianCoefficients[ 0 ] ).toVar();
  32998. const diffuseSum = vec4( sampleTexture( uvNode ).mul( weightSum ) ).toVar();
  32999. for ( let i = 1; i < kernelSize; i ++ ) {
  33000. const x = float( i );
  33001. const w = float( gaussianCoefficients[ i ] );
  33002. const uvOffset = vec2( direction.mul( invSize.mul( x ) ) ).toVar();
  33003. const sample1 = vec4( sampleTexture( uvNode.add( uvOffset ) ) );
  33004. const sample2 = vec4( sampleTexture( uvNode.sub( uvOffset ) ) );
  33005. diffuseSum.addAssign( sample1.add( sample2 ).mul( w ) );
  33006. weightSum.addAssign( mul( 2.0, w ) );
  33007. }
  33008. return diffuseSum.div( weightSum );
  33009. } );
  33010. //
  33011. const material = this._material || ( this._material = new NodeMaterial() );
  33012. material.fragmentNode = blur().context( builder.getSharedContext() );
  33013. material.name = 'Gaussian_blur';
  33014. material.needsUpdate = true;
  33015. //
  33016. const properties = builder.getNodeProperties( this );
  33017. properties.textureNode = textureNode;
  33018. //
  33019. return this._textureNode;
  33020. }
  33021. dispose() {
  33022. this._horizontalRT.dispose();
  33023. this._verticalRT.dispose();
  33024. }
  33025. _getCoefficients( kernelRadius ) {
  33026. const coefficients = [];
  33027. for ( let i = 0; i < kernelRadius; i ++ ) {
  33028. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  33029. }
  33030. return coefficients;
  33031. }
  33032. }
  33033. const gaussianBlur = ( node, directionNode, sigma ) => nodeObject( new GaussianBlurNode( convertToTexture( node ), directionNode, sigma ) );
  33034. const _size$6 = /*@__PURE__*/ new Vector2();
  33035. const _quadMeshComp = /*@__PURE__*/ new QuadMesh();
  33036. class AfterImageNode extends TempNode {
  33037. static get type() {
  33038. return 'AfterImageNode';
  33039. }
  33040. constructor( textureNode, damp = 0.96 ) {
  33041. super( textureNode );
  33042. this.textureNode = textureNode;
  33043. this.textureNodeOld = texture();
  33044. this.damp = uniform( damp );
  33045. this._compRT = new RenderTarget();
  33046. this._compRT.texture.name = 'AfterImageNode.comp';
  33047. this._oldRT = new RenderTarget();
  33048. this._oldRT.texture.name = 'AfterImageNode.old';
  33049. this._textureNode = passTexture( this, this._compRT.texture );
  33050. this.updateBeforeType = NodeUpdateType.RENDER;
  33051. }
  33052. getTextureNode() {
  33053. return this._textureNode;
  33054. }
  33055. setSize( width, height ) {
  33056. this._compRT.setSize( width, height );
  33057. this._oldRT.setSize( width, height );
  33058. }
  33059. updateBefore( frame ) {
  33060. const { renderer } = frame;
  33061. const textureNode = this.textureNode;
  33062. const map = textureNode.value;
  33063. const textureType = map.type;
  33064. this._compRT.texture.type = textureType;
  33065. this._oldRT.texture.type = textureType;
  33066. renderer.getDrawingBufferSize( _size$6 );
  33067. this.setSize( _size$6.x, _size$6.y );
  33068. const currentRenderTarget = renderer.getRenderTarget();
  33069. const currentTexture = textureNode.value;
  33070. this.textureNodeOld.value = this._oldRT.texture;
  33071. // comp
  33072. renderer.setRenderTarget( this._compRT );
  33073. _quadMeshComp.render( renderer );
  33074. // Swap the textures
  33075. const temp = this._oldRT;
  33076. this._oldRT = this._compRT;
  33077. this._compRT = temp;
  33078. renderer.setRenderTarget( currentRenderTarget );
  33079. textureNode.value = currentTexture;
  33080. }
  33081. setup( builder ) {
  33082. const textureNode = this.textureNode;
  33083. const textureNodeOld = this.textureNodeOld;
  33084. //
  33085. const uvNode = textureNode.uvNode || uv();
  33086. textureNodeOld.uvNode = uvNode;
  33087. const sampleTexture = ( uv ) => textureNode.uv( uv );
  33088. const when_gt = Fn( ( [ x_immutable, y_immutable ] ) => {
  33089. const y = float( y_immutable ).toVar();
  33090. const x = vec4( x_immutable ).toVar();
  33091. return max$1( sign( x.sub( y ) ), 0.0 );
  33092. } );
  33093. const afterImg = Fn( () => {
  33094. const texelOld = vec4( textureNodeOld );
  33095. const texelNew = vec4( sampleTexture( uvNode ) );
  33096. texelOld.mulAssign( this.damp.mul( when_gt( texelOld, 0.1 ) ) );
  33097. return max$1( texelNew, texelOld );
  33098. } );
  33099. //
  33100. const materialComposed = this._materialComposed || ( this._materialComposed = new NodeMaterial() );
  33101. materialComposed.name = 'AfterImage';
  33102. materialComposed.fragmentNode = afterImg();
  33103. _quadMeshComp.material = materialComposed;
  33104. //
  33105. const properties = builder.getNodeProperties( this );
  33106. properties.textureNode = textureNode;
  33107. //
  33108. return this._textureNode;
  33109. }
  33110. dispose() {
  33111. this._compRT.dispose();
  33112. this._oldRT.dispose();
  33113. }
  33114. }
  33115. const afterImage = ( node, damp ) => nodeObject( new AfterImageNode( convertToTexture( node ), damp ) );
  33116. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  33117. return luminance( color.rgb );
  33118. } );
  33119. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  33120. return adjustment.mix( luminance( color.rgb ), color.rgb );
  33121. } );
  33122. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  33123. const average = add( color.r, color.g, color.b ).div( 3.0 );
  33124. const mx = color.r.max( color.g.max( color.b ) );
  33125. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  33126. return mix( color.rgb, mx, amt );
  33127. } );
  33128. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  33129. const k = vec3( 0.57735, 0.57735, 0.57735 );
  33130. const cosAngle = adjustment.cos();
  33131. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  33132. } );
  33133. const _luminanceCoefficients = /*@__PURE__*/ new Vector3();
  33134. const luminance = (
  33135. color,
  33136. luminanceCoefficients = vec3( ... ColorManagement.getLuminanceCoefficients( _luminanceCoefficients ) )
  33137. ) => dot( color, luminanceCoefficients );
  33138. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  33139. const _quadMesh$5 = /*@__PURE__*/ new QuadMesh();
  33140. class AnamorphicNode extends TempNode {
  33141. static get type() {
  33142. return 'AnamorphicNode';
  33143. }
  33144. constructor( textureNode, tresholdNode, scaleNode, samples ) {
  33145. super( 'vec4' );
  33146. this.textureNode = textureNode;
  33147. this.tresholdNode = tresholdNode;
  33148. this.scaleNode = scaleNode;
  33149. this.colorNode = vec3( 0.1, 0.0, 1.0 );
  33150. this.samples = samples;
  33151. this.resolution = new Vector2( 1, 1 );
  33152. this._renderTarget = new RenderTarget();
  33153. this._renderTarget.texture.name = 'anamorphic';
  33154. this._invSize = uniform( new Vector2() );
  33155. this._textureNode = passTexture( this, this._renderTarget.texture );
  33156. this.updateBeforeType = NodeUpdateType.RENDER;
  33157. }
  33158. getTextureNode() {
  33159. return this._textureNode;
  33160. }
  33161. setSize( width, height ) {
  33162. this._invSize.value.set( 1 / width, 1 / height );
  33163. width = Math.max( Math.round( width * this.resolution.x ), 1 );
  33164. height = Math.max( Math.round( height * this.resolution.y ), 1 );
  33165. this._renderTarget.setSize( width, height );
  33166. }
  33167. updateBefore( frame ) {
  33168. const { renderer } = frame;
  33169. const textureNode = this.textureNode;
  33170. const map = textureNode.value;
  33171. this._renderTarget.texture.type = map.type;
  33172. const currentRenderTarget = renderer.getRenderTarget();
  33173. const currentTexture = textureNode.value;
  33174. _quadMesh$5.material = this._material;
  33175. this.setSize( map.image.width, map.image.height );
  33176. // render
  33177. renderer.setRenderTarget( this._renderTarget );
  33178. _quadMesh$5.render( renderer );
  33179. // restore
  33180. renderer.setRenderTarget( currentRenderTarget );
  33181. textureNode.value = currentTexture;
  33182. }
  33183. setup( builder ) {
  33184. const textureNode = this.textureNode;
  33185. const uvNode = textureNode.uvNode || uv();
  33186. const sampleTexture = ( uv ) => textureNode.uv( uv );
  33187. const anamorph = Fn( () => {
  33188. const samples = this.samples;
  33189. const halfSamples = Math.floor( samples / 2 );
  33190. const total = vec3( 0 ).toVar();
  33191. Loop( { start: - halfSamples, end: halfSamples }, ( { i } ) => {
  33192. const softness = float( i ).abs().div( halfSamples ).oneMinus();
  33193. const uv = vec2( uvNode.x.add( this._invSize.x.mul( i ).mul( this.scaleNode ) ), uvNode.y );
  33194. const color = sampleTexture( uv );
  33195. const pass = threshold( color, this.tresholdNode ).mul( softness );
  33196. total.addAssign( pass );
  33197. } );
  33198. return total.mul( this.colorNode );
  33199. } );
  33200. //
  33201. const material = this._material || ( this._material = new NodeMaterial() );
  33202. material.name = 'Anamorphic';
  33203. material.fragmentNode = anamorph();
  33204. //
  33205. const properties = builder.getNodeProperties( this );
  33206. properties.textureNode = textureNode;
  33207. //
  33208. return this._textureNode;
  33209. }
  33210. dispose() {
  33211. this._renderTarget.dispose();
  33212. }
  33213. }
  33214. const anamorphic = ( node, threshold = .9, scale = 3, samples = 32 ) => nodeObject( new AnamorphicNode( convertToTexture( node ), nodeObject( threshold ), nodeObject( scale ), samples ) );
  33215. class SobelOperatorNode extends TempNode {
  33216. static get type() {
  33217. return 'SobelOperatorNode';
  33218. }
  33219. constructor( textureNode ) {
  33220. super();
  33221. this.textureNode = textureNode;
  33222. this.updateBeforeType = NodeUpdateType.RENDER;
  33223. this._invSize = uniform( new Vector2() );
  33224. }
  33225. updateBefore() {
  33226. const map = this.textureNode.value;
  33227. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  33228. }
  33229. setup() {
  33230. const { textureNode } = this;
  33231. const uvNode = textureNode.uvNode || uv();
  33232. const sampleTexture = ( uv ) => textureNode.uv( uv );
  33233. const sobel = Fn( () => {
  33234. // Sobel Edge Detection (see https://youtu.be/uihBwtPIBxM)
  33235. const texel = this._invSize;
  33236. // kernel definition (in glsl matrices are filled in column-major order)
  33237. const Gx = mat3( - 1, - 2, - 1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
  33238. const Gy = mat3( - 1, 0, 1, - 2, 0, 2, - 1, 0, 1 ); // y direction kernel
  33239. // fetch the 3x3 neighbourhood of a fragment
  33240. // first column
  33241. const tx0y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, - 1 ) ) ) ).xyz );
  33242. const tx0y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 0 ) ) ) ).xyz );
  33243. const tx0y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( - 1, 1 ) ) ) ).xyz );
  33244. // second column
  33245. const tx1y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, - 1 ) ) ) ).xyz );
  33246. const tx1y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 0 ) ) ) ).xyz );
  33247. const tx1y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 0, 1 ) ) ) ).xyz );
  33248. // third column
  33249. const tx2y0 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, - 1 ) ) ) ).xyz );
  33250. const tx2y1 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 0 ) ) ) ).xyz );
  33251. const tx2y2 = luminance( sampleTexture( uvNode.add( texel.mul( vec2( 1, 1 ) ) ) ).xyz );
  33252. // gradient value in x direction
  33253. const valueGx = add(
  33254. Gx[ 0 ][ 0 ].mul( tx0y0 ),
  33255. Gx[ 1 ][ 0 ].mul( tx1y0 ),
  33256. Gx[ 2 ][ 0 ].mul( tx2y0 ),
  33257. Gx[ 0 ][ 1 ].mul( tx0y1 ),
  33258. Gx[ 1 ][ 1 ].mul( tx1y1 ),
  33259. Gx[ 2 ][ 1 ].mul( tx2y1 ),
  33260. Gx[ 0 ][ 2 ].mul( tx0y2 ),
  33261. Gx[ 1 ][ 2 ].mul( tx1y2 ),
  33262. Gx[ 2 ][ 2 ].mul( tx2y2 )
  33263. );
  33264. // gradient value in y direction
  33265. const valueGy = add(
  33266. Gy[ 0 ][ 0 ].mul( tx0y0 ),
  33267. Gy[ 1 ][ 0 ].mul( tx1y0 ),
  33268. Gy[ 2 ][ 0 ].mul( tx2y0 ),
  33269. Gy[ 0 ][ 1 ].mul( tx0y1 ),
  33270. Gy[ 1 ][ 1 ].mul( tx1y1 ),
  33271. Gy[ 2 ][ 1 ].mul( tx2y1 ),
  33272. Gy[ 0 ][ 2 ].mul( tx0y2 ),
  33273. Gy[ 1 ][ 2 ].mul( tx1y2 ),
  33274. Gy[ 2 ][ 2 ].mul( tx2y2 )
  33275. );
  33276. // magnitute of the total gradient
  33277. const G = valueGx.mul( valueGx ).add( valueGy.mul( valueGy ) ).sqrt();
  33278. return vec4( vec3( G ), 1 );
  33279. } );
  33280. const outputNode = sobel();
  33281. return outputNode;
  33282. }
  33283. }
  33284. const sobel = ( node ) => nodeObject( new SobelOperatorNode( convertToTexture( node ) ) );
  33285. class DepthOfFieldNode extends TempNode {
  33286. static get type() {
  33287. return 'DepthOfFieldNode';
  33288. }
  33289. constructor( textureNode, viewZNode, focusNode, apertureNode, maxblurNode ) {
  33290. super();
  33291. this.textureNode = textureNode;
  33292. this.viewZNode = viewZNode;
  33293. this.focusNode = focusNode;
  33294. this.apertureNode = apertureNode;
  33295. this.maxblurNode = maxblurNode;
  33296. this._aspect = uniform( 0 );
  33297. this.updateBeforeType = NodeUpdateType.RENDER;
  33298. }
  33299. updateBefore() {
  33300. const map = this.textureNode.value;
  33301. this._aspect.value = map.image.width / map.image.height;
  33302. }
  33303. setup() {
  33304. const textureNode = this.textureNode;
  33305. const uvNode = textureNode.uvNode || uv();
  33306. const sampleTexture = ( uv ) => textureNode.uv( uv );
  33307. const dof = Fn( () => {
  33308. const aspectcorrect = vec2( 1.0, this._aspect );
  33309. const factor = this.focusNode.add( this.viewZNode );
  33310. const dofblur = vec2( clamp( factor.mul( this.apertureNode ), this.maxblurNode.negate(), this.maxblurNode ) );
  33311. const dofblur9 = dofblur.mul( 0.9 );
  33312. const dofblur7 = dofblur.mul( 0.7 );
  33313. const dofblur4 = dofblur.mul( 0.4 );
  33314. let col = vec4( 0.0 );
  33315. col = col.add( sampleTexture( uvNode ) );
  33316. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33317. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33318. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33319. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33320. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33321. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33322. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33323. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33324. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33325. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33326. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33327. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33328. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33329. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33330. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33331. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur ) ) ) );
  33332. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33333. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33334. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33335. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33336. col = col.add( sampleTexture( uvNode.add( vec2( - 0.15, 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33337. col = col.add( sampleTexture( uvNode.add( vec2( 0.37, 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33338. col = col.add( sampleTexture( uvNode.add( vec2( - 0.37, - 0.15 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33339. col = col.add( sampleTexture( uvNode.add( vec2( 0.15, - 0.37 ).mul( aspectcorrect ).mul( dofblur9 ) ) ) );
  33340. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33341. col = col.add( sampleTexture( uvNode.add( vec2( 0.40, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33342. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33343. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33344. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33345. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33346. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33347. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur7 ) ) ) );
  33348. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33349. col = col.add( sampleTexture( uvNode.add( vec2( 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33350. col = col.add( sampleTexture( uvNode.add( vec2( 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33351. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, - 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33352. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33353. col = col.add( sampleTexture( uvNode.add( vec2( - 0.4, 0.0 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33354. col = col.add( sampleTexture( uvNode.add( vec2( - 0.29, - 0.29 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33355. col = col.add( sampleTexture( uvNode.add( vec2( 0.0, 0.4 ).mul( aspectcorrect ).mul( dofblur4 ) ) ) );
  33356. col = col.div( 41 );
  33357. col.a = 1;
  33358. return vec4( col );
  33359. } );
  33360. const outputNode = dof();
  33361. return outputNode;
  33362. }
  33363. }
  33364. const dof = ( node, viewZNode, focus = 1, aperture = 0.025, maxblur = 1 ) => nodeObject( new DepthOfFieldNode( convertToTexture( node ), nodeObject( viewZNode ), nodeObject( focus ), nodeObject( aperture ), nodeObject( maxblur ) ) );
  33365. class DotScreenNode extends TempNode {
  33366. static get type() {
  33367. return 'DotScreenNode';
  33368. }
  33369. constructor( inputNode, center = new Vector2( 0.5, 0.5 ), angle = 1.57, scale = 1 ) {
  33370. super( 'vec4' );
  33371. this.inputNode = inputNode;
  33372. this.center = uniform( center );
  33373. this.angle = uniform( angle );
  33374. this.scale = uniform( scale );
  33375. }
  33376. setup() {
  33377. const inputNode = this.inputNode;
  33378. const pattern = Fn( () => {
  33379. const s = sin( this.angle );
  33380. const c = cos( this.angle );
  33381. const tex = uv().mul( screenSize ).sub( this.center );
  33382. const point = vec2( c.mul( tex.x ).sub( s.mul( tex.y ) ), s.mul( tex.x ).add( c.mul( tex.y ) ) ).mul( this.scale );
  33383. return sin( point.x ).mul( sin( point.y ) ).mul( 4 );
  33384. } );
  33385. const dotScreen = Fn( () => {
  33386. const color = inputNode;
  33387. const average = add( color.r, color.g, color.b ).div( 3 );
  33388. return vec4( vec3( average.mul( 10 ).sub( 5 ).add( pattern() ) ), color.a );
  33389. } );
  33390. const outputNode = dotScreen();
  33391. return outputNode;
  33392. }
  33393. }
  33394. const dotScreen = ( node, center, angle, scale ) => nodeObject( new DotScreenNode( nodeObject( node ), center, angle, scale ) );
  33395. class RGBShiftNode extends TempNode {
  33396. static get type() {
  33397. return 'RGBShiftNode';
  33398. }
  33399. constructor( textureNode, amount = 0.005, angle = 0 ) {
  33400. super( 'vec4' );
  33401. this.textureNode = textureNode;
  33402. this.amount = uniform( amount );
  33403. this.angle = uniform( angle );
  33404. }
  33405. setup() {
  33406. const { textureNode } = this;
  33407. const uvNode = textureNode.uvNode || uv();
  33408. const sampleTexture = ( uv ) => textureNode.uv( uv );
  33409. const rgbShift = Fn( () => {
  33410. const offset = vec2( cos( this.angle ), sin( this.angle ) ).mul( this.amount );
  33411. const cr = sampleTexture( uvNode.add( offset ) );
  33412. const cga = sampleTexture( uvNode );
  33413. const cb = sampleTexture( uvNode.sub( offset ) );
  33414. return vec4( cr.r, cga.g, cb.b, cga.a );
  33415. } );
  33416. return rgbShift();
  33417. }
  33418. }
  33419. const rgbShift = ( node, amount, angle ) => nodeObject( new RGBShiftNode( convertToTexture( node ), amount, angle ) );
  33420. class FilmNode extends TempNode {
  33421. static get type() {
  33422. return 'FilmNode';
  33423. }
  33424. constructor( inputNode, intensityNode = null, uvNode = null ) {
  33425. super();
  33426. this.inputNode = inputNode;
  33427. this.intensityNode = intensityNode;
  33428. this.uvNode = uvNode;
  33429. }
  33430. setup() {
  33431. const uvNode = this.uvNode || uv();
  33432. const film = Fn( () => {
  33433. const base = this.inputNode.rgb;
  33434. const noise = rand( fract( uvNode.add( timerLocal() ) ) );
  33435. let color = base.add( base.mul( clamp( noise.add( 0.1 ), 0, 1 ) ) );
  33436. if ( this.intensityNode !== null ) {
  33437. color = mix( base, color, this.intensityNode );
  33438. }
  33439. return vec4( color, this.inputNode.a );
  33440. } );
  33441. const outputNode = film();
  33442. return outputNode;
  33443. }
  33444. }
  33445. const film = /*@__PURE__*/ nodeProxy( FilmNode );
  33446. class Lut3DNode extends TempNode {
  33447. static get type() {
  33448. return 'Lut3DNode';
  33449. }
  33450. constructor( inputNode, lutNode, size, intensityNode ) {
  33451. super();
  33452. this.inputNode = inputNode;
  33453. this.lutNode = lutNode;
  33454. this.size = uniform( size );
  33455. this.intensityNode = intensityNode;
  33456. }
  33457. setup() {
  33458. const { inputNode, lutNode } = this;
  33459. const sampleLut = ( uv ) => lutNode.uv( uv );
  33460. const lut3D = Fn( () => {
  33461. const base = inputNode;
  33462. // pull the sample in by half a pixel so the sample begins at the center of the edge pixels.
  33463. const pixelWidth = float( 1.0 ).div( this.size );
  33464. const halfPixelWidth = float( 0.5 ).div( this.size );
  33465. const uvw = vec3( halfPixelWidth ).add( base.rgb.mul( float( 1.0 ).sub( pixelWidth ) ) );
  33466. const lutValue = vec4( sampleLut( uvw ).rgb, base.a );
  33467. return vec4( mix( base, lutValue, this.intensityNode ) );
  33468. } );
  33469. const outputNode = lut3D();
  33470. return outputNode;
  33471. }
  33472. }
  33473. const lut3D = ( node, lut, size, intensity ) => nodeObject( new Lut3DNode( nodeObject( node ), nodeObject( lut ), size, nodeObject( intensity ) ) );
  33474. const _quadMesh$4 = /*@__PURE__*/ new QuadMesh();
  33475. const _currentClearColor$1 = /*@__PURE__*/ new Color();
  33476. const _size$5 = /*@__PURE__*/ new Vector2();
  33477. class GTAONode extends TempNode {
  33478. static get type() {
  33479. return 'GTAONode';
  33480. }
  33481. constructor( depthNode, normalNode, camera ) {
  33482. super();
  33483. this.depthNode = depthNode;
  33484. this.normalNode = normalNode;
  33485. this.radius = uniform( 0.25 );
  33486. this.resolution = uniform( new Vector2() );
  33487. this.thickness = uniform( 1 );
  33488. this.distanceExponent = uniform( 1 );
  33489. this.distanceFallOff = uniform( 1 );
  33490. this.scale = uniform( 1 );
  33491. this.noiseNode = texture( generateMagicSquareNoise() );
  33492. this.cameraProjectionMatrix = uniform( camera.projectionMatrix );
  33493. this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  33494. this.SAMPLES = uniform( 16 );
  33495. this._aoRenderTarget = new RenderTarget();
  33496. this._aoRenderTarget.texture.name = 'GTAONode.AO';
  33497. this._material = null;
  33498. this._textureNode = passTexture( this, this._aoRenderTarget.texture );
  33499. this.updateBeforeType = NodeUpdateType.FRAME;
  33500. }
  33501. getTextureNode() {
  33502. return this._textureNode;
  33503. }
  33504. setSize( width, height ) {
  33505. this.resolution.value.set( width, height );
  33506. this._aoRenderTarget.setSize( width, height );
  33507. }
  33508. updateBefore( frame ) {
  33509. const { renderer } = frame;
  33510. const size = renderer.getDrawingBufferSize( _size$5 );
  33511. const currentRenderTarget = renderer.getRenderTarget();
  33512. const currentMRT = renderer.getMRT();
  33513. renderer.getClearColor( _currentClearColor$1 );
  33514. const currentClearAlpha = renderer.getClearAlpha();
  33515. _quadMesh$4.material = this._material;
  33516. this.setSize( size.width, size.height );
  33517. // clear
  33518. renderer.setMRT( null );
  33519. renderer.setClearColor( 0xffffff, 1 );
  33520. // ao
  33521. renderer.setRenderTarget( this._aoRenderTarget );
  33522. _quadMesh$4.render( renderer );
  33523. // restore
  33524. renderer.setRenderTarget( currentRenderTarget );
  33525. renderer.setMRT( currentMRT );
  33526. renderer.setClearColor( _currentClearColor$1, currentClearAlpha );
  33527. }
  33528. setup( builder ) {
  33529. const uvNode = uv();
  33530. const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
  33531. const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
  33532. const getSceneUvAndDepth = Fn( ( [ sampleViewPos ] )=> {
  33533. const sampleClipPos = this.cameraProjectionMatrix.mul( vec4( sampleViewPos, 1.0 ) );
  33534. let sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  33535. sampleUv = vec2( sampleUv.x, sampleUv.y.oneMinus() );
  33536. const sampleSceneDepth = sampleDepth( sampleUv );
  33537. return vec3( sampleUv, sampleSceneDepth );
  33538. } );
  33539. const getViewPosition = Fn( ( [ screenPosition, depth ] ) => {
  33540. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  33541. const clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  33542. const viewSpacePosition = vec4( this.cameraProjectionMatrixInverse.mul( clipSpacePosition ) );
  33543. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  33544. } );
  33545. const ao = Fn( () => {
  33546. const depth = sampleDepth( uvNode );
  33547. depth.greaterThanEqual( 1.0 ).discard();
  33548. const viewPosition = getViewPosition( uvNode, depth );
  33549. const viewNormal = this.normalNode.rgb.normalize();
  33550. const radiusToUse = this.radius;
  33551. const noiseResolution = textureSize( this.noiseNode, 0 );
  33552. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  33553. noiseUv = noiseUv.mul( this.resolution.div( noiseResolution ) );
  33554. const noiseTexel = sampleNoise( noiseUv );
  33555. const randomVec = noiseTexel.xyz.mul( 2.0 ).sub( 1.0 );
  33556. const tangent = vec3( randomVec.xy, 0.0 ).normalize();
  33557. const bitangent = vec3( tangent.y.mul( - 1.0 ), tangent.x, 0.0 );
  33558. const kernelMatrix = mat3( tangent, bitangent, vec3( 0.0, 0.0, 1.0 ) );
  33559. const DIRECTIONS = this.SAMPLES.lessThan( 30 ).select( 3, 5 );
  33560. const STEPS = add( this.SAMPLES, DIRECTIONS.sub( 1 ) ).div( DIRECTIONS );
  33561. const ao = float( 0 ).toVar();
  33562. Loop( { start: int( 0 ), end: DIRECTIONS, type: 'int', condition: '<' }, ( { i } ) => {
  33563. const angle = float( i ).div( float( DIRECTIONS ) ).mul( PI );
  33564. const sampleDir = vec4( cos( angle ), sin( angle ), 0., add( 0.5, mul( 0.5, noiseTexel.w ) ) );
  33565. sampleDir.xyz = normalize( kernelMatrix.mul( sampleDir.xyz ) );
  33566. const viewDir = normalize( viewPosition.xyz.negate() );
  33567. const sliceBitangent = normalize( cross( sampleDir.xyz, viewDir ) );
  33568. const sliceTangent = cross( sliceBitangent, viewDir );
  33569. const normalInSlice = normalize( viewNormal.sub( sliceBitangent.mul( dot( viewNormal, sliceBitangent ) ) ) );
  33570. const tangentToNormalInSlice = cross( normalInSlice, sliceBitangent );
  33571. const cosHorizons = vec2( dot( viewDir, tangentToNormalInSlice ), dot( viewDir, tangentToNormalInSlice.negate() ) ).toVar();
  33572. Loop( { end: STEPS, type: 'int', name: 'j', condition: '<' }, ( { j } ) => {
  33573. const sampleViewOffset = sampleDir.xyz.mul( radiusToUse ).mul( sampleDir.w ).mul( pow( div( float( j ).add( 1.0 ), float( STEPS ) ), this.distanceExponent ) );
  33574. // x
  33575. const sampleSceneUvDepthX = getSceneUvAndDepth( viewPosition.add( sampleViewOffset ) );
  33576. const sampleSceneViewPositionX = getViewPosition( sampleSceneUvDepthX.xy, sampleSceneUvDepthX.z );
  33577. const viewDeltaX = sampleSceneViewPositionX.sub( viewPosition );
  33578. If( abs( viewDeltaX.z ).lessThan( this.thickness ), () => {
  33579. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaX ) );
  33580. cosHorizons.x.addAssign( max$1( 0, mul( sampleCosHorizon.sub( cosHorizons.x ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  33581. } );
  33582. // y
  33583. const sampleSceneUvDepthY = getSceneUvAndDepth( viewPosition.sub( sampleViewOffset ) );
  33584. const sampleSceneViewPositionY = getViewPosition( sampleSceneUvDepthY.xy, sampleSceneUvDepthY.z );
  33585. const viewDeltaY = sampleSceneViewPositionY.sub( viewPosition );
  33586. If( abs( viewDeltaY.z ).lessThan( this.thickness ), () => {
  33587. const sampleCosHorizon = dot( viewDir, normalize( viewDeltaY ) );
  33588. cosHorizons.y.addAssign( max$1( 0, mul( sampleCosHorizon.sub( cosHorizons.y ), mix( 1.0, float( 2.0 ).div( float( j ).add( 2 ) ), this.distanceFallOff ) ) ) );
  33589. } );
  33590. } );
  33591. const sinHorizons = sqrt( sub( 1.0, cosHorizons.mul( cosHorizons ) ) );
  33592. const nx = dot( normalInSlice, sliceTangent );
  33593. const ny = dot( normalInSlice, viewDir );
  33594. const nxb = mul( 0.5, acos( cosHorizons.y ).sub( acos( cosHorizons.x ) ).add( sinHorizons.x.mul( cosHorizons.x ).sub( sinHorizons.y.mul( cosHorizons.y ) ) ) );
  33595. const nyb = mul( 0.5, sub( 2.0, cosHorizons.x.mul( cosHorizons.x ) ).sub( cosHorizons.y.mul( cosHorizons.y ) ) );
  33596. const occlusion = nx.mul( nxb ).add( ny.mul( nyb ) );
  33597. ao.addAssign( occlusion );
  33598. } );
  33599. ao.assign( clamp( ao.div( DIRECTIONS ), 0, 1 ) );
  33600. ao.assign( pow( ao, this.scale ) );
  33601. return vec4( vec3( ao ), 1.0 );
  33602. } );
  33603. const material = this._material || ( this._material = new NodeMaterial() );
  33604. material.fragmentNode = ao().context( builder.getSharedContext() );
  33605. material.name = 'GTAO';
  33606. material.needsUpdate = true;
  33607. //
  33608. return this._textureNode;
  33609. }
  33610. dispose() {
  33611. this._aoRenderTarget.dispose();
  33612. }
  33613. }
  33614. function generateMagicSquareNoise( size = 5 ) {
  33615. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  33616. const magicSquare = generateMagicSquare( noiseSize );
  33617. const noiseSquareSize = magicSquare.length;
  33618. const data = new Uint8Array( noiseSquareSize * 4 );
  33619. for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
  33620. const iAng = magicSquare[ inx ];
  33621. const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
  33622. const randomVec = new Vector3(
  33623. Math.cos( angle ),
  33624. Math.sin( angle ),
  33625. 0
  33626. ).normalize();
  33627. data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
  33628. data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
  33629. data[ inx * 4 + 2 ] = 127;
  33630. data[ inx * 4 + 3 ] = 255;
  33631. }
  33632. const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
  33633. noiseTexture.wrapS = RepeatWrapping;
  33634. noiseTexture.wrapT = RepeatWrapping;
  33635. noiseTexture.needsUpdate = true;
  33636. return noiseTexture;
  33637. }
  33638. function generateMagicSquare( size ) {
  33639. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  33640. const noiseSquareSize = noiseSize * noiseSize;
  33641. const magicSquare = Array( noiseSquareSize ).fill( 0 );
  33642. let i = Math.floor( noiseSize / 2 );
  33643. let j = noiseSize - 1;
  33644. for ( let num = 1; num <= noiseSquareSize; ) {
  33645. if ( i === - 1 && j === noiseSize ) {
  33646. j = noiseSize - 2;
  33647. i = 0;
  33648. } else {
  33649. if ( j === noiseSize ) {
  33650. j = 0;
  33651. }
  33652. if ( i < 0 ) {
  33653. i = noiseSize - 1;
  33654. }
  33655. }
  33656. if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
  33657. j -= 2;
  33658. i ++;
  33659. continue;
  33660. } else {
  33661. magicSquare[ i * noiseSize + j ] = num ++;
  33662. }
  33663. j ++;
  33664. i --;
  33665. }
  33666. return magicSquare;
  33667. }
  33668. const ao = ( depthNode, normalNode, camera ) => nodeObject( new GTAONode( nodeObject( depthNode ), nodeObject( normalNode ), camera ) );
  33669. class DenoiseNode extends TempNode {
  33670. static get type() {
  33671. return 'DenoiseNode';
  33672. }
  33673. constructor( textureNode, depthNode, normalNode, noiseNode, camera ) {
  33674. super();
  33675. this.textureNode = textureNode;
  33676. this.depthNode = depthNode;
  33677. this.normalNode = normalNode;
  33678. this.noiseNode = noiseNode;
  33679. this.cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  33680. this.lumaPhi = uniform( 5 );
  33681. this.depthPhi = uniform( 5 );
  33682. this.normalPhi = uniform( 5 );
  33683. this.radius = uniform( 5 );
  33684. this.index = uniform( 0 );
  33685. this._resolution = uniform( new Vector2() );
  33686. this._sampleVectors = uniformArray( generatePdSamplePointInitializer( 16, 2, 1 ) );
  33687. this.updateBeforeType = NodeUpdateType.RENDER;
  33688. }
  33689. updateBefore() {
  33690. const map = this.textureNode.value;
  33691. this._resolution.value.set( map.image.width, map.image.height );
  33692. }
  33693. setup() {
  33694. const uvNode = uv();
  33695. const sampleTexture = ( uv ) => this.textureNode.uv( uv );
  33696. const sampleDepth = ( uv ) => this.depthNode.uv( uv ).x;
  33697. const sampleNormal = ( uv ) => this.normalNode.uv( uv );
  33698. const sampleNoise = ( uv ) => this.noiseNode.uv( uv );
  33699. const getViewPosition = Fn( ( [ screenPosition, depth ] ) => {
  33700. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  33701. const clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  33702. const viewSpacePosition = vec4( this.cameraProjectionMatrixInverse.mul( clipSpacePosition ) );
  33703. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  33704. } );
  33705. const denoiseSample = Fn( ( [ center, viewNormal, viewPosition, sampleUv ] ) => {
  33706. const texel = sampleTexture( sampleUv );
  33707. const depth = sampleDepth( sampleUv );
  33708. const normal = sampleNormal( sampleUv ).rgb.normalize();
  33709. const neighborColor = texel.rgb;
  33710. const viewPos = getViewPosition( sampleUv, depth );
  33711. const normalDiff = dot( viewNormal, normal ).toVar();
  33712. const normalSimilarity = pow( max$1( normalDiff, 0 ), this.normalPhi ).toVar();
  33713. const lumaDiff = abs( luminance( neighborColor ).sub( luminance( center ) ) ).toVar();
  33714. const lumaSimilarity = max$1( float( 1.0 ).sub( lumaDiff.div( this.lumaPhi ) ), 0 ).toVar();
  33715. const depthDiff = abs( dot( viewPosition.sub( viewPos ), viewNormal ) ).toVar();
  33716. const depthSimilarity = max$1( float( 1.0 ).sub( depthDiff.div( this.depthPhi ) ), 0 );
  33717. const w = lumaSimilarity.mul( depthSimilarity ).mul( normalSimilarity );
  33718. return vec4( neighborColor.mul( w ), w );
  33719. } );
  33720. const denoise = Fn( ( [ uvNode ] ) => {
  33721. const depth = sampleDepth( uvNode );
  33722. const viewNormal = sampleNormal( uvNode ).rgb.normalize();
  33723. const texel = sampleTexture( uvNode );
  33724. If( depth.greaterThanEqual( 1.0 ).or( dot( viewNormal, viewNormal ).equal( 0.0 ) ), () => {
  33725. return texel;
  33726. } );
  33727. const center = vec3( texel.rgb );
  33728. const viewPosition = getViewPosition( uvNode, depth );
  33729. const noiseResolution = textureSize( this.noiseNode, 0 );
  33730. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  33731. noiseUv = noiseUv.mul( this._resolution.div( noiseResolution ) );
  33732. const noiseTexel = sampleNoise( noiseUv );
  33733. const x = sin( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  33734. const y = cos( noiseTexel.element( this.index.mod( 4 ).mul( 2 ).mul( PI ) ) );
  33735. const noiseVec = vec2( x, y );
  33736. const rotationMatrix = mat2( noiseVec.x, noiseVec.y.negate(), noiseVec.x, noiseVec.y );
  33737. const totalWeight = float( 1.0 ).toVar();
  33738. const denoised = vec3( texel.rgb ).toVar();
  33739. Loop( { start: int( 0 ), end: int( 16 ), type: 'int', condition: '<' }, ( { i } ) => {
  33740. const sampleDir = this._sampleVectors.element( i ).toVar();
  33741. const offset = rotationMatrix.mul( sampleDir.xy.mul( float( 1.0 ).add( sampleDir.z.mul( this.radius.sub( 1 ) ) ) ) ).div( this._resolution ).toVar();
  33742. const sampleUv = uvNode.add( offset ).toVar();
  33743. const result = denoiseSample( center, viewNormal, viewPosition, sampleUv );
  33744. denoised.addAssign( result.xyz );
  33745. totalWeight.addAssign( result.w );
  33746. } );
  33747. If( totalWeight.greaterThan( float( 0 ) ), () => {
  33748. denoised.divAssign( totalWeight );
  33749. } );
  33750. return vec4( denoised, texel.a );
  33751. } ).setLayout( {
  33752. name: 'denoise',
  33753. type: 'vec4',
  33754. inputs: [
  33755. { name: 'uv', type: 'vec2' }
  33756. ]
  33757. } );
  33758. const output = Fn( () => {
  33759. return denoise( uvNode );
  33760. } );
  33761. const outputNode = output();
  33762. return outputNode;
  33763. }
  33764. }
  33765. function generatePdSamplePointInitializer( samples, rings, radiusExponent ) {
  33766. const poissonDisk = generateDenoiseSamples( samples, rings, radiusExponent );
  33767. const array = [];
  33768. for ( let i = 0; i < samples; i ++ ) {
  33769. const sample = poissonDisk[ i ];
  33770. array.push( sample );
  33771. }
  33772. return array;
  33773. }
  33774. function generateDenoiseSamples( numSamples, numRings, radiusExponent ) {
  33775. const samples = [];
  33776. for ( let i = 0; i < numSamples; i ++ ) {
  33777. const angle = 2 * Math.PI * numRings * i / numSamples;
  33778. const radius = Math.pow( i / ( numSamples - 1 ), radiusExponent );
  33779. samples.push( new Vector3( Math.cos( angle ), Math.sin( angle ), radius ) );
  33780. }
  33781. return samples;
  33782. }
  33783. const denoise = ( node, depthNode, normalNode, noiseNode, camera ) => nodeObject( new DenoiseNode( convertToTexture( node ), nodeObject( depthNode ), nodeObject( normalNode ), nodeObject( noiseNode ), camera ) );
  33784. class FXAANode extends TempNode {
  33785. static get type() {
  33786. return 'FXAANode';
  33787. }
  33788. constructor( textureNode ) {
  33789. super();
  33790. this.textureNode = textureNode;
  33791. this.updateBeforeType = NodeUpdateType.RENDER;
  33792. this._invSize = uniform( new Vector2() );
  33793. }
  33794. updateBefore() {
  33795. const map = this.textureNode.value;
  33796. this._invSize.value.set( 1 / map.image.width, 1 / map.image.height );
  33797. }
  33798. setup() {
  33799. const textureNode = this.textureNode.bias( - 100 );
  33800. const uvNode = textureNode.uvNode || uv();
  33801. // FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)
  33802. //----------------------------------------------------------------------------------
  33803. // File: es3-kepler\FXAA\assets\shaders/FXAA_DefaultES.frag
  33804. // SDK Version: v3.00
  33805. // Email: gameworks@nvidia.com
  33806. // Site: http://developer.nvidia.com/
  33807. //
  33808. // Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
  33809. //
  33810. // Redistribution and use in source and binary forms, with or without
  33811. // modification, are permitted provided that the following conditions
  33812. // are met:
  33813. // * Redistributions of source code must retain the above copyright
  33814. // notice, this list of conditions and the following disclaimer.
  33815. // * Redistributions in binary form must reproduce the above copyright
  33816. // notice, this list of conditions and the following disclaimer in the
  33817. // documentation and/or other materials provided with the distribution.
  33818. // * Neither the name of NVIDIA CORPORATION nor the names of its
  33819. // contributors may be used to endorse or promote products derived
  33820. // from this software without specific prior written permission.
  33821. //
  33822. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
  33823. // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  33824. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  33825. // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  33826. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  33827. // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  33828. // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  33829. // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  33830. // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  33831. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  33832. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33833. //
  33834. //----------------------------------------------------------------------------------
  33835. const FxaaTexTop = ( p ) => textureNode.uv( p );
  33836. const FxaaTexOff = ( p, o, r ) => textureNode.uv( p.add( o.mul( r ) ) );
  33837. const NUM_SAMPLES = int( 5 );
  33838. const contrast = Fn( ( [ a_immutable, b_immutable ] ) => {
  33839. // assumes colors have premultipliedAlpha, so that the calculated color contrast is scaled by alpha
  33840. const b = vec4( b_immutable ).toVar();
  33841. const a = vec4( a_immutable ).toVar();
  33842. const diff = vec4( abs( a.sub( b ) ) ).toVar();
  33843. return max$1( max$1( max$1( diff.r, diff.g ), diff.b ), diff.a );
  33844. } );
  33845. // FXAA3 QUALITY - PC
  33846. const FxaaPixelShader = Fn( ( [ uv, fxaaQualityRcpFrame, fxaaQualityEdgeThreshold, fxaaQualityinvEdgeThreshold ] ) => {
  33847. const rgbaM = FxaaTexTop( uv ).toVar();
  33848. const rgbaS = FxaaTexOff( uv, vec2( 0.0, - 1.0 ), fxaaQualityRcpFrame.xy ).toVar();
  33849. const rgbaE = FxaaTexOff( uv, vec2( 1.0, 0.0 ), fxaaQualityRcpFrame.xy ).toVar();
  33850. const rgbaN = FxaaTexOff( uv, vec2( 0.0, 1.0 ), fxaaQualityRcpFrame.xy ).toVar();
  33851. const rgbaW = FxaaTexOff( uv, vec2( - 1.0, 0.0 ), fxaaQualityRcpFrame.xy ).toVar();
  33852. // . S .
  33853. // W M E
  33854. // . N .
  33855. const contrastN = contrast( rgbaM, rgbaN ).toVar();
  33856. const contrastS = contrast( rgbaM, rgbaS ).toVar();
  33857. const contrastE = contrast( rgbaM, rgbaE ).toVar();
  33858. const contrastW = contrast( rgbaM, rgbaW ).toVar();
  33859. const maxValue = max$1( contrastN, max$1( contrastS, max$1( contrastE, contrastW ) ) ).toVar();
  33860. // . 0 .
  33861. // 0 0 0
  33862. // . 0 .
  33863. If( maxValue.lessThan( fxaaQualityEdgeThreshold ), () => {
  33864. return rgbaM; // assuming define FXAA_DISCARD is always 0
  33865. } );
  33866. //
  33867. const relativeVContrast = sub( contrastN.add( contrastS ), ( contrastE.add( contrastW ) ) ).toVar();
  33868. relativeVContrast.mulAssign( fxaaQualityinvEdgeThreshold );
  33869. // 45 deg edge detection and corners of objects, aka V/H contrast is too similar
  33870. If( abs( relativeVContrast ).lessThan( 0.3 ), () => {
  33871. // locate the edge
  33872. const x = contrastE.greaterThan( contrastW ).select( 1, - 1 ).toVar();
  33873. const y = contrastS.greaterThan( contrastN ).select( 1, - 1 ).toVar();
  33874. const dirToEdge = vec2( x, y ).toVar();
  33875. // . 2 . . 1 .
  33876. // 1 0 2 ~= 0 0 1
  33877. // . 1 . . 0 .
  33878. // tap 2 pixels and see which ones are "outside" the edge, to
  33879. // determine if the edge is vertical or horizontal
  33880. const rgbaAlongH = FxaaTexOff( uv, vec2( dirToEdge.x, dirToEdge.y ), fxaaQualityRcpFrame.xy );
  33881. const matchAlongH = contrast( rgbaM, rgbaAlongH ).toVar();
  33882. // . 1 .
  33883. // 0 0 1
  33884. // . 0 H
  33885. const rgbaAlongV = FxaaTexOff( uv, vec2( dirToEdge.x.negate(), dirToEdge.y.negate() ), fxaaQualityRcpFrame.xy );
  33886. const matchAlongV = contrast( rgbaM, rgbaAlongV ).toVar();
  33887. // V 1 .
  33888. // 0 0 1
  33889. // . 0 .
  33890. relativeVContrast.assign( matchAlongV.sub( matchAlongH ) );
  33891. relativeVContrast.mulAssign( fxaaQualityinvEdgeThreshold );
  33892. If( abs( relativeVContrast ).lessThan( 0.3 ), () => { // 45 deg edge
  33893. // 1 1 .
  33894. // 0 0 1
  33895. // . 0 1
  33896. // do a simple blur
  33897. const sum = rgbaN.add( rgbaS ).add( rgbaE ).add( rgbaW );
  33898. return mix( rgbaM, sum.mul( 0.25 ), 0.4 );
  33899. } );
  33900. } );
  33901. const offNP = vec2().toVar();
  33902. If( relativeVContrast.lessThanEqual( 0 ), () => {
  33903. rgbaN.assign( rgbaW );
  33904. rgbaS.assign( rgbaE );
  33905. // . 0 . 1
  33906. // 1 0 1 -> 0
  33907. // . 0 . 1
  33908. offNP.x.assign( 0 );
  33909. offNP.y.assign( fxaaQualityRcpFrame.y );
  33910. } ).Else( () => {
  33911. offNP.x.assign( fxaaQualityRcpFrame.x );
  33912. offNP.y.assign( 0 );
  33913. } );
  33914. const mn = contrast( rgbaM, rgbaN ).toVar();
  33915. const ms = contrast( rgbaM, rgbaS ).toVar();
  33916. If( mn.lessThanEqual( ms ), () => {
  33917. rgbaN.assign( rgbaS );
  33918. } );
  33919. const doneN = int( 0 ).toVar();
  33920. const doneP = int( 0 ).toVar();
  33921. const nDist = float( 0 ).toVar();
  33922. const pDist = float( 0 ).toVar();
  33923. const posN = vec2( uv ).toVar();
  33924. const posP = vec2( uv ).toVar();
  33925. const iterationsUsedN = int( 0 ).toVar();
  33926. const iterationsUsedP = int( 0 ).toVar();
  33927. Loop( NUM_SAMPLES, ( { i } ) => {
  33928. const increment = i.add( 1 ).toVar();
  33929. If( doneN.equal( 0 ), () => {
  33930. nDist.addAssign( increment );
  33931. posN.assign( uv.add( offNP.mul( nDist ) ) );
  33932. const rgbaEndN = FxaaTexTop( posN.xy );
  33933. const nm = contrast( rgbaEndN, rgbaM ).toVar();
  33934. const nn = contrast( rgbaEndN, rgbaN ).toVar();
  33935. If( nm.greaterThan( nn ), () => {
  33936. doneN.assign( 1 );
  33937. } );
  33938. iterationsUsedN.assign( i );
  33939. } );
  33940. If( doneP.equal( 0 ), () => {
  33941. pDist.addAssign( increment );
  33942. posP.assign( uv.sub( offNP.mul( pDist ) ) );
  33943. const rgbaEndP = FxaaTexTop( posP.xy );
  33944. const pm = contrast( rgbaEndP, rgbaM ).toVar();
  33945. const pn = contrast( rgbaEndP, rgbaN ).toVar();
  33946. If( pm.greaterThan( pn ), () => {
  33947. doneP.assign( 1 );
  33948. } );
  33949. iterationsUsedP.assign( i );
  33950. } );
  33951. If( doneN.equal( 1 ).or( doneP.equal( 1 ) ), () => {
  33952. Break();
  33953. } );
  33954. } );
  33955. If( doneN.equal( 0 ).and( doneP.equal( 0 ) ), () => {
  33956. return rgbaM; // failed to find end of edge
  33957. } );
  33958. const distN = float( 1 ).toVar();
  33959. const distP = float( 1 ).toVar();
  33960. If( doneN.equal( 1 ), () => {
  33961. distN.assign( float( iterationsUsedN ).div( float( NUM_SAMPLES.sub( 1 ) ) ) );
  33962. } );
  33963. If( doneP.equal( 1 ), () => {
  33964. distP.assign( float( iterationsUsedP ).div( float( NUM_SAMPLES.sub( 1 ) ) ) );
  33965. } );
  33966. const dist = min$1( distN, distP );
  33967. // hacky way of reduces blurriness of mostly diagonal edges
  33968. // but reduces AA quality
  33969. dist.assign( pow( dist, 0.5 ) );
  33970. dist.assign( float( 1 ).sub( dist ) );
  33971. return mix( rgbaM, rgbaN, dist.mul( 0.5 ) );
  33972. } ).setLayout( {
  33973. name: 'FxaaPixelShader',
  33974. type: 'vec4',
  33975. inputs: [
  33976. { name: 'uv', type: 'vec2' },
  33977. { name: 'fxaaQualityRcpFrame', type: 'vec2' },
  33978. { name: 'fxaaQualityEdgeThreshold', type: 'float' },
  33979. { name: 'fxaaQualityinvEdgeThreshold', type: 'float' },
  33980. ]
  33981. } );
  33982. const fxaa = Fn( () => {
  33983. const edgeDetectionQuality = float( 0.2 );
  33984. const invEdgeDetectionQuality = float( 1 ).div( edgeDetectionQuality );
  33985. return FxaaPixelShader( uvNode, this._invSize, edgeDetectionQuality, invEdgeDetectionQuality );
  33986. } );
  33987. const outputNode = fxaa();
  33988. return outputNode;
  33989. }
  33990. }
  33991. const fxaa = ( node ) => nodeObject( new FXAANode( convertToTexture( node ) ) );
  33992. const _quadMesh$3 = /*@__PURE__*/ new QuadMesh();
  33993. const _clearColor$1 = /*@__PURE__*/ new Color( 0, 0, 0 );
  33994. const _currentClearColor = /*@__PURE__*/ new Color();
  33995. const _size$4 = /*@__PURE__*/ new Vector2();
  33996. const _BlurDirectionX = /*@__PURE__*/ new Vector2( 1.0, 0.0 );
  33997. const _BlurDirectionY = /*@__PURE__*/ new Vector2( 0.0, 1.0 );
  33998. class BloomNode extends TempNode {
  33999. static get type() {
  34000. return 'BloomNode';
  34001. }
  34002. constructor( inputNode, strength = 1, radius = 0, threshold = 0 ) {
  34003. super();
  34004. this.inputNode = inputNode;
  34005. this.strength = uniform( strength );
  34006. this.radius = uniform( radius );
  34007. this.threshold = uniform( threshold );
  34008. this.smoothWidth = uniform( 0.01 );
  34009. //
  34010. this._renderTargetsHorizontal = [];
  34011. this._renderTargetsVertical = [];
  34012. this._nMips = 5;
  34013. // render targets
  34014. this._renderTargetBright = new RenderTarget( 1, 1, { type: HalfFloatType } );
  34015. this._renderTargetBright.texture.name = 'UnrealBloomPass.bright';
  34016. this._renderTargetBright.texture.generateMipmaps = false;
  34017. for ( let i = 0; i < this._nMips; i ++ ) {
  34018. const renderTargetHorizontal = new RenderTarget( 1, 1, { type: HalfFloatType } );
  34019. renderTargetHorizontal.texture.name = 'UnrealBloomPass.h' + i;
  34020. renderTargetHorizontal.texture.generateMipmaps = false;
  34021. this._renderTargetsHorizontal.push( renderTargetHorizontal );
  34022. const renderTargetVertical = new RenderTarget( 1, 1, { type: HalfFloatType } );
  34023. renderTargetVertical.texture.name = 'UnrealBloomPass.v' + i;
  34024. renderTargetVertical.texture.generateMipmaps = false;
  34025. this._renderTargetsVertical.push( renderTargetVertical );
  34026. }
  34027. // materials
  34028. this._compositeMaterial = null;
  34029. this._highPassFilterMaterial = null;
  34030. this._separableBlurMaterials = [];
  34031. // pass and texture nodes
  34032. this._textureNodeBright = texture( this._renderTargetBright.texture );
  34033. this._textureNodeBlur0 = texture( this._renderTargetsVertical[ 0 ].texture );
  34034. this._textureNodeBlur1 = texture( this._renderTargetsVertical[ 1 ].texture );
  34035. this._textureNodeBlur2 = texture( this._renderTargetsVertical[ 2 ].texture );
  34036. this._textureNodeBlur3 = texture( this._renderTargetsVertical[ 3 ].texture );
  34037. this._textureNodeBlur4 = texture( this._renderTargetsVertical[ 4 ].texture );
  34038. this._textureOutput = passTexture( this, this._renderTargetsHorizontal[ 0 ].texture );
  34039. this.updateBeforeType = NodeUpdateType.FRAME;
  34040. }
  34041. getTextureNode() {
  34042. return this._textureOutput;
  34043. }
  34044. setSize( width, height ) {
  34045. let resx = Math.round( width / 2 );
  34046. let resy = Math.round( height / 2 );
  34047. this._renderTargetBright.setSize( resx, resy );
  34048. for ( let i = 0; i < this._nMips; i ++ ) {
  34049. this._renderTargetsHorizontal[ i ].setSize( resx, resy );
  34050. this._renderTargetsVertical[ i ].setSize( resx, resy );
  34051. this._separableBlurMaterials[ i ].invSize.value.set( 1 / resx, 1 / resy );
  34052. resx = Math.round( resx / 2 );
  34053. resy = Math.round( resy / 2 );
  34054. }
  34055. }
  34056. updateBefore( frame ) {
  34057. const { renderer } = frame;
  34058. const size = renderer.getDrawingBufferSize( _size$4 );
  34059. this.setSize( size.width, size.height );
  34060. const currentRenderTarget = renderer.getRenderTarget();
  34061. const currentMRT = renderer.getMRT();
  34062. renderer.getClearColor( _currentClearColor );
  34063. const currentClearAlpha = renderer.getClearAlpha();
  34064. this.setSize( size.width, size.height );
  34065. renderer.setMRT( null );
  34066. renderer.setClearColor( _clearColor$1, 0 );
  34067. // 1. Extract Bright Areas
  34068. renderer.setRenderTarget( this._renderTargetBright );
  34069. _quadMesh$3.material = this._highPassFilterMaterial;
  34070. _quadMesh$3.render( renderer );
  34071. // 2. Blur All the mips progressively
  34072. let inputRenderTarget = this._renderTargetBright;
  34073. for ( let i = 0; i < this._nMips; i ++ ) {
  34074. _quadMesh$3.material = this._separableBlurMaterials[ i ];
  34075. this._separableBlurMaterials[ i ].colorTexture.value = inputRenderTarget.texture;
  34076. this._separableBlurMaterials[ i ].direction.value = _BlurDirectionX;
  34077. renderer.setRenderTarget( this._renderTargetsHorizontal[ i ] );
  34078. renderer.clear();
  34079. _quadMesh$3.render( renderer );
  34080. this._separableBlurMaterials[ i ].colorTexture.value = this._renderTargetsHorizontal[ i ].texture;
  34081. this._separableBlurMaterials[ i ].direction.value = _BlurDirectionY;
  34082. renderer.setRenderTarget( this._renderTargetsVertical[ i ] );
  34083. renderer.clear();
  34084. _quadMesh$3.render( renderer );
  34085. inputRenderTarget = this._renderTargetsVertical[ i ];
  34086. }
  34087. // 3. Composite All the mips
  34088. renderer.setRenderTarget( this._renderTargetsHorizontal[ 0 ] );
  34089. renderer.clear();
  34090. _quadMesh$3.material = this._compositeMaterial;
  34091. _quadMesh$3.render( renderer );
  34092. // restore
  34093. renderer.setRenderTarget( currentRenderTarget );
  34094. renderer.setMRT( currentMRT );
  34095. renderer.setClearColor( _currentClearColor, currentClearAlpha );
  34096. }
  34097. setup( builder ) {
  34098. // luminosity high pass material
  34099. const luminosityHighPass = Fn( () => {
  34100. const texel = this.inputNode;
  34101. const v = luminance( texel.rgb );
  34102. const alpha = smoothstep( this.threshold, this.threshold.add( this.smoothWidth ), v );
  34103. return mix( vec4( 0 ), texel, alpha );
  34104. } );
  34105. this._highPassFilterMaterial = this._highPassFilterMaterial || new NodeMaterial();
  34106. this._highPassFilterMaterial.fragmentNode = luminosityHighPass().context( builder.getSharedContext() );
  34107. this._highPassFilterMaterial.name = 'Bloom_highPass';
  34108. this._highPassFilterMaterial.needsUpdate = true;
  34109. // gaussian blur materials
  34110. const kernelSizeArray = [ 3, 5, 7, 9, 11 ];
  34111. for ( let i = 0; i < this._nMips; i ++ ) {
  34112. this._separableBlurMaterials.push( this._getSeperableBlurMaterial( builder, kernelSizeArray[ i ] ) );
  34113. }
  34114. // composite material
  34115. const bloomFactors = uniformArray( [ 1.0, 0.8, 0.6, 0.4, 0.2 ] );
  34116. const bloomTintColors = uniformArray( [ new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ), new Vector3( 1, 1, 1 ) ] );
  34117. const lerpBloomFactor = Fn( ( [ factor, radius ] ) => {
  34118. const mirrorFactor = float( 1.2 ).sub( factor );
  34119. return mix( factor, mirrorFactor, radius );
  34120. } ).setLayout( {
  34121. name: 'lerpBloomFactor',
  34122. type: 'float',
  34123. inputs: [
  34124. { name: 'factor', type: 'float' },
  34125. { name: 'radius', type: 'float' },
  34126. ]
  34127. } );
  34128. const compositePass = Fn( () => {
  34129. const color0 = lerpBloomFactor( bloomFactors.element( 0 ), this.radius ).mul( vec4( bloomTintColors.element( 0 ), 1.0 ) ).mul( this._textureNodeBlur0 );
  34130. const color1 = lerpBloomFactor( bloomFactors.element( 1 ), this.radius ).mul( vec4( bloomTintColors.element( 1 ), 1.0 ) ).mul( this._textureNodeBlur1 );
  34131. const color2 = lerpBloomFactor( bloomFactors.element( 2 ), this.radius ).mul( vec4( bloomTintColors.element( 2 ), 1.0 ) ).mul( this._textureNodeBlur2 );
  34132. const color3 = lerpBloomFactor( bloomFactors.element( 3 ), this.radius ).mul( vec4( bloomTintColors.element( 3 ), 1.0 ) ).mul( this._textureNodeBlur3 );
  34133. const color4 = lerpBloomFactor( bloomFactors.element( 4 ), this.radius ).mul( vec4( bloomTintColors.element( 4 ), 1.0 ) ).mul( this._textureNodeBlur4 );
  34134. const sum = color0.add( color1 ).add( color2 ).add( color3 ).add( color4 );
  34135. return sum.mul( this.strength );
  34136. } );
  34137. this._compositeMaterial = this._compositeMaterial || new NodeMaterial();
  34138. this._compositeMaterial.fragmentNode = compositePass().context( builder.getSharedContext() );
  34139. this._compositeMaterial.name = 'Bloom_comp';
  34140. this._compositeMaterial.needsUpdate = true;
  34141. //
  34142. return this._textureOutput;
  34143. }
  34144. dispose() {
  34145. for ( let i = 0; i < this._renderTargetsHorizontal.length; i ++ ) {
  34146. this._renderTargetsHorizontal[ i ].dispose();
  34147. }
  34148. for ( let i = 0; i < this._renderTargetsVertical.length; i ++ ) {
  34149. this._renderTargetsVertical[ i ].dispose();
  34150. }
  34151. this._renderTargetBright.dispose();
  34152. }
  34153. _getSeperableBlurMaterial( builder, kernelRadius ) {
  34154. const coefficients = [];
  34155. for ( let i = 0; i < kernelRadius; i ++ ) {
  34156. coefficients.push( 0.39894 * Math.exp( - 0.5 * i * i / ( kernelRadius * kernelRadius ) ) / kernelRadius );
  34157. }
  34158. //
  34159. const colorTexture = texture();
  34160. const gaussianCoefficients = uniformArray( coefficients );
  34161. const invSize = uniform( new Vector2() );
  34162. const direction = uniform( new Vector2( 0.5, 0.5 ) );
  34163. const uvNode = uv();
  34164. const sampleTexel = ( uv ) => colorTexture.uv( uv );
  34165. const seperableBlurPass = Fn( () => {
  34166. const weightSum = gaussianCoefficients.element( 0 ).toVar();
  34167. const diffuseSum = sampleTexel( uvNode ).rgb.mul( weightSum ).toVar();
  34168. Loop( { start: int( 1 ), end: int( kernelRadius ), type: 'int', condition: '<' }, ( { i } ) => {
  34169. const x = float( i );
  34170. const w = gaussianCoefficients.element( i );
  34171. const uvOffset = direction.mul( invSize ).mul( x );
  34172. const sample1 = sampleTexel( uvNode.add( uvOffset ) ).rgb;
  34173. const sample2 = sampleTexel( uvNode.sub( uvOffset ) ).rgb;
  34174. diffuseSum.addAssign( add( sample1, sample2 ).mul( w ) );
  34175. weightSum.addAssign( float( 2.0 ).mul( w ) );
  34176. } );
  34177. return vec4( diffuseSum.div( weightSum ), 1.0 );
  34178. } );
  34179. const seperableBlurMaterial = new NodeMaterial();
  34180. seperableBlurMaterial.fragmentNode = seperableBlurPass().context( builder.getSharedContext() );
  34181. seperableBlurMaterial.name = 'Bloom_seperable';
  34182. seperableBlurMaterial.needsUpdate = true;
  34183. // uniforms
  34184. seperableBlurMaterial.colorTexture = colorTexture;
  34185. seperableBlurMaterial.direction = direction;
  34186. seperableBlurMaterial.invSize = invSize;
  34187. return seperableBlurMaterial;
  34188. }
  34189. }
  34190. const bloom = ( node, strength, radius, threshold ) => nodeObject( new BloomNode( nodeObject( node ), strength, radius, threshold ) );
  34191. class TransitionNode extends TempNode {
  34192. static get type() {
  34193. return 'TransitionNode';
  34194. }
  34195. constructor( textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode ) {
  34196. super();
  34197. // Input textures
  34198. this.textureNodeA = textureNodeA;
  34199. this.textureNodeB = textureNodeB;
  34200. this.mixTextureNode = mixTextureNode;
  34201. // Uniforms
  34202. this.mixRatioNode = mixRatioNode;
  34203. this.thresholdNode = thresholdNode;
  34204. this.useTextureNode = useTextureNode;
  34205. }
  34206. setup() {
  34207. const { textureNodeA, textureNodeB, mixTextureNode, mixRatioNode, thresholdNode, useTextureNode } = this;
  34208. const sampleTexture = ( textureNode ) => {
  34209. const uvNodeTexture = textureNode.uvNode || uv();
  34210. return textureNode.uv( uvNodeTexture );
  34211. };
  34212. const transition = Fn( () => {
  34213. const texelOne = sampleTexture( textureNodeA );
  34214. const texelTwo = sampleTexture( textureNodeB );
  34215. const color = vec4().toVar();
  34216. If( useTextureNode.equal( int( 1 ) ), () => {
  34217. const transitionTexel = sampleTexture( mixTextureNode );
  34218. const r = mixRatioNode.mul( thresholdNode.mul( 2.0 ).add( 1.0 ) ).sub( thresholdNode );
  34219. const mixf = clamp( sub( transitionTexel.r, r ).mul( float( 1.0 ).div( thresholdNode ) ), 0.0, 1.0 );
  34220. color.assign( mix( texelOne, texelTwo, mixf ) );
  34221. } ).Else( () => {
  34222. color.assign( mix( texelTwo, texelOne, mixRatioNode ) );
  34223. } );
  34224. return color;
  34225. } );
  34226. const outputNode = transition();
  34227. return outputNode;
  34228. }
  34229. }
  34230. const transition = ( nodeA, nodeB, mixTexture, mixRatio = 0.0, threshold = 0.1, useTexture = 0 ) => nodeObject( new TransitionNode( convertToTexture( nodeA ), convertToTexture( nodeB ), convertToTexture( mixTexture ), nodeObject( mixRatio ), nodeObject( threshold ), nodeObject( useTexture ) ) );
  34231. class PixelationNode extends TempNode {
  34232. static get type() {
  34233. return 'PixelationNode';
  34234. }
  34235. constructor( textureNode, depthNode, normalNode, pixelSize, normalEdgeStrength, depthEdgeStrength ) {
  34236. super();
  34237. // Input textures
  34238. this.textureNode = textureNode;
  34239. this.depthNode = depthNode;
  34240. this.normalNode = normalNode;
  34241. // Input uniforms
  34242. this.pixelSize = pixelSize;
  34243. this.normalEdgeStrength = normalEdgeStrength;
  34244. this.depthEdgeStrength = depthEdgeStrength;
  34245. // Private uniforms
  34246. this._resolution = uniform( new Vector4() );
  34247. this.updateBeforeType = NodeUpdateType.RENDER;
  34248. }
  34249. updateBefore() {
  34250. const map = this.textureNode.value;
  34251. const width = map.image.width;
  34252. const height = map.image.height;
  34253. this._resolution.value.set( width, height, 1 / width, 1 / height );
  34254. }
  34255. setup() {
  34256. const { textureNode, depthNode, normalNode } = this;
  34257. const uvNodeTexture = textureNode.uvNode || uv();
  34258. const uvNodeDepth = depthNode.uvNode || uv();
  34259. const uvNodeNormal = normalNode.uvNode || uv();
  34260. const sampleTexture = () => textureNode.uv( uvNodeTexture );
  34261. const sampleDepth = ( x, y ) => depthNode.uv( uvNodeDepth.add( vec2( x, y ).mul( this._resolution.zw ) ) ).r;
  34262. const sampleNormal = ( x, y ) => normalNode.uv( uvNodeNormal.add( vec2( x, y ).mul( this._resolution.zw ) ) ).rgb.normalize();
  34263. const depthEdgeIndicator = ( depth ) => {
  34264. const diff = property( 'float', 'diff' );
  34265. diff.addAssign( clamp( sampleDepth( 1, 0 ).sub( depth ) ) );
  34266. diff.addAssign( clamp( sampleDepth( - 1, 0 ).sub( depth ) ) );
  34267. diff.addAssign( clamp( sampleDepth( 0, 1 ).sub( depth ) ) );
  34268. diff.addAssign( clamp( sampleDepth( 0, - 1 ).sub( depth ) ) );
  34269. return floor( smoothstep( 0.01, 0.02, diff ).mul( 2 ) ).div( 2 );
  34270. };
  34271. const neighborNormalEdgeIndicator = ( x, y, depth, normal ) => {
  34272. const depthDiff = sampleDepth( x, y ).sub( depth );
  34273. const neighborNormal = sampleNormal( x, y );
  34274. // Edge pixels should yield to faces who's normals are closer to the bias normal.
  34275. const normalEdgeBias = vec3( 1, 1, 1 ); // This should probably be a parameter.
  34276. const normalDiff = dot( normal.sub( neighborNormal ), normalEdgeBias );
  34277. const normalIndicator = clamp( smoothstep( - 0.01, 0.01, normalDiff ), 0.0, 1.0 );
  34278. // Only the shallower pixel should detect the normal edge.
  34279. const depthIndicator = clamp( sign( depthDiff.mul( .25 ).add( .0025 ) ), 0.0, 1.0 );
  34280. return float( 1.0 ).sub( dot( normal, neighborNormal ) ).mul( depthIndicator ).mul( normalIndicator );
  34281. };
  34282. const normalEdgeIndicator = ( depth, normal ) => {
  34283. const indicator = property( 'float', 'indicator' );
  34284. indicator.addAssign( neighborNormalEdgeIndicator( 0, - 1, depth, normal ) );
  34285. indicator.addAssign( neighborNormalEdgeIndicator( 0, 1, depth, normal ) );
  34286. indicator.addAssign( neighborNormalEdgeIndicator( - 1, 0, depth, normal ) );
  34287. indicator.addAssign( neighborNormalEdgeIndicator( 1, 0, depth, normal ) );
  34288. return step( 0.1, indicator );
  34289. };
  34290. const pixelation = Fn( () => {
  34291. const texel = sampleTexture();
  34292. const depth = property( 'float', 'depth' );
  34293. const normal = property( 'vec3', 'normal' );
  34294. If( this.depthEdgeStrength.greaterThan( 0.0 ).or( this.normalEdgeStrength.greaterThan( 0.0 ) ), () => {
  34295. depth.assign( sampleDepth( 0, 0 ) );
  34296. normal.assign( sampleNormal( 0, 0 ) );
  34297. } );
  34298. const dei = property( 'float', 'dei' );
  34299. If( this.depthEdgeStrength.greaterThan( 0.0 ), () => {
  34300. dei.assign( depthEdgeIndicator( depth ) );
  34301. } );
  34302. const nei = property( 'float', 'nei' );
  34303. If( this.normalEdgeStrength.greaterThan( 0.0 ), () => {
  34304. nei.assign( normalEdgeIndicator( depth, normal ) );
  34305. } );
  34306. const strength = dei.greaterThan( 0 ).select( float( 1.0 ).sub( dei.mul( this.depthEdgeStrength ) ), nei.mul( this.normalEdgeStrength ).add( 1 ) );
  34307. return texel.mul( strength );
  34308. } );
  34309. const outputNode = pixelation();
  34310. return outputNode;
  34311. }
  34312. }
  34313. const pixelation = ( node, depthNode, normalNode, pixelSize = 6, normalEdgeStrength = 0.3, depthEdgeStrength = 0.4 ) => nodeObject( new PixelationNode( convertToTexture( node ), convertToTexture( depthNode ), convertToTexture( normalNode ), nodeObject( pixelSize ), nodeObject( normalEdgeStrength ), nodeObject( depthEdgeStrength ) ) );
  34314. class PixelationPassNode extends PassNode {
  34315. static get type() {
  34316. return 'PixelationPassNode';
  34317. }
  34318. constructor( scene, camera, pixelSize = 6, normalEdgeStrength = 0.3, depthEdgeStrength = 0.4 ) {
  34319. super( 'color', scene, camera, { minFilter: NearestFilter, magFilter: NearestFilter } );
  34320. this.pixelSize = pixelSize;
  34321. this.normalEdgeStrength = normalEdgeStrength;
  34322. this.depthEdgeStrength = depthEdgeStrength;
  34323. this.isPixelationPassNode = true;
  34324. this._mrt = mrt( {
  34325. output: output,
  34326. normal: normalView
  34327. } );
  34328. }
  34329. setSize( width, height ) {
  34330. const pixelSize = this.pixelSize.value ? this.pixelSize.value : this.pixelSize;
  34331. const adjustedWidth = Math.floor( width / pixelSize );
  34332. const adjustedHeight = Math.floor( height / pixelSize );
  34333. super.setSize( adjustedWidth, adjustedHeight );
  34334. }
  34335. setup() {
  34336. const color = super.getTextureNode( 'output' );
  34337. const depth = super.getTextureNode( 'depth' );
  34338. const normal = super.getTextureNode( 'normal' );
  34339. return pixelation( color, depth, normal, this.pixelSize, this.normalEdgeStrength, this.depthEdgeStrength );
  34340. }
  34341. }
  34342. const pixelationPass = ( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) => nodeObject( new PixelationPassNode( scene, camera, pixelSize, normalEdgeStrength, depthEdgeStrength ) );
  34343. const _size$3 = /*@__PURE__*/ new Vector2();
  34344. /**
  34345. *
  34346. * Supersample Anti-Aliasing Render Pass
  34347. *
  34348. * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
  34349. *
  34350. * References: https://en.wikipedia.org/wiki/Supersampling
  34351. *
  34352. */
  34353. class SSAAPassNode extends PassNode {
  34354. static get type() {
  34355. return 'SSAAPassNode';
  34356. }
  34357. constructor( scene, camera ) {
  34358. super( PassNode.COLOR, scene, camera );
  34359. this.isSSAAPassNode = true;
  34360. this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
  34361. this.unbiased = true;
  34362. this.clearColor = new Color( 0x000000 );
  34363. this.clearAlpha = 0;
  34364. this._currentClearColor = new Color();
  34365. this.sampleWeight = uniform( 1 );
  34366. this.sampleRenderTarget = null;
  34367. this._quadMesh = new QuadMesh();
  34368. }
  34369. updateBefore( frame ) {
  34370. const { renderer } = frame;
  34371. const { scene, camera } = this;
  34372. this._pixelRatio = renderer.getPixelRatio();
  34373. const size = renderer.getSize( _size$3 );
  34374. this.setSize( size.width, size.height );
  34375. this.sampleRenderTarget.setSize( this.renderTarget.width, this.renderTarget.height );
  34376. // save current renderer settings
  34377. renderer.getClearColor( this._currentClearColor );
  34378. const currentClearAlpha = renderer.getClearAlpha();
  34379. const currentRenderTarget = renderer.getRenderTarget();
  34380. const currentMRT = renderer.getMRT();
  34381. const currentAutoClear = renderer.autoClear;
  34382. //
  34383. this._cameraNear.value = camera.near;
  34384. this._cameraFar.value = camera.far;
  34385. renderer.setMRT( this.getMRT() );
  34386. renderer.autoClear = false;
  34387. const jitterOffsets = _JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];
  34388. const baseSampleWeight = 1.0 / jitterOffsets.length;
  34389. const roundingRange = 1 / 32;
  34390. const viewOffset = {
  34391. fullWidth: this.renderTarget.width,
  34392. fullHeight: this.renderTarget.height,
  34393. offsetX: 0,
  34394. offsetY: 0,
  34395. width: this.renderTarget.width,
  34396. height: this.renderTarget.height
  34397. };
  34398. const originalViewOffset = Object.assign( {}, camera.view );
  34399. if ( originalViewOffset.enabled ) Object.assign( viewOffset, originalViewOffset );
  34400. // render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
  34401. for ( let i = 0; i < jitterOffsets.length; i ++ ) {
  34402. const jitterOffset = jitterOffsets[ i ];
  34403. if ( camera.setViewOffset ) {
  34404. camera.setViewOffset(
  34405. viewOffset.fullWidth, viewOffset.fullHeight,
  34406. viewOffset.offsetX + jitterOffset[ 0 ] * 0.0625, viewOffset.offsetY + jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16
  34407. viewOffset.width, viewOffset.height
  34408. );
  34409. }
  34410. this.sampleWeight.value = baseSampleWeight;
  34411. if ( this.unbiased ) {
  34412. // the theory is that equal weights for each sample lead to an accumulation of rounding errors.
  34413. // The following equation varies the sampleWeight per sample so that it is uniformly distributed
  34414. // across a range of values whose rounding errors cancel each other out.
  34415. const uniformCenteredDistribution = ( - 0.5 + ( i + 0.5 ) / jitterOffsets.length );
  34416. this.sampleWeight.value += roundingRange * uniformCenteredDistribution;
  34417. }
  34418. renderer.setClearColor( this.clearColor, this.clearAlpha );
  34419. renderer.setRenderTarget( this.sampleRenderTarget );
  34420. renderer.clear();
  34421. renderer.render( scene, camera );
  34422. // accumulation
  34423. renderer.setRenderTarget( this.renderTarget );
  34424. if ( i === 0 ) {
  34425. renderer.setClearColor( 0x000000, 0.0 );
  34426. renderer.clear();
  34427. }
  34428. this._quadMesh.render( renderer );
  34429. }
  34430. renderer.copyTextureToTexture( this.sampleRenderTarget.depthTexture, this.renderTarget.depthTexture );
  34431. // restore
  34432. if ( camera.setViewOffset && originalViewOffset.enabled ) {
  34433. camera.setViewOffset(
  34434. originalViewOffset.fullWidth, originalViewOffset.fullHeight,
  34435. originalViewOffset.offsetX, originalViewOffset.offsetY,
  34436. originalViewOffset.width, originalViewOffset.height
  34437. );
  34438. } else if ( camera.clearViewOffset ) {
  34439. camera.clearViewOffset();
  34440. }
  34441. renderer.setRenderTarget( currentRenderTarget );
  34442. renderer.setMRT( currentMRT );
  34443. renderer.autoClear = currentAutoClear;
  34444. renderer.setClearColor( this._currentClearColor, currentClearAlpha );
  34445. }
  34446. setup( builder ) {
  34447. if ( this.sampleRenderTarget === null ) {
  34448. this.sampleRenderTarget = this.renderTarget.clone();
  34449. }
  34450. let sampleTexture;
  34451. const passMRT = this.getMRT();
  34452. if ( passMRT !== null ) {
  34453. const outputs = {};
  34454. for ( const name in passMRT.outputNodes ) {
  34455. const index = getTextureIndex( this.sampleRenderTarget.textures, name );
  34456. if ( index >= 0 ) {
  34457. outputs[ name ] = texture( this.sampleRenderTarget.textures[ index ] ).mul( this.sampleWeight );
  34458. }
  34459. }
  34460. sampleTexture = mrt( outputs );
  34461. } else {
  34462. sampleTexture = texture( this.sampleRenderTarget.texture ).mul( this.sampleWeight );
  34463. }
  34464. this._quadMesh.material = new NodeMaterial();
  34465. this._quadMesh.material.fragmentNode = sampleTexture;
  34466. this._quadMesh.material.transparent = true;
  34467. this._quadMesh.material.depthTest = false;
  34468. this._quadMesh.material.depthWrite = false;
  34469. this._quadMesh.material.premultipliedAlpha = true;
  34470. this._quadMesh.material.blending = AdditiveBlending;
  34471. this._quadMesh.material.normals = false;
  34472. this._quadMesh.material.name = 'SSAA';
  34473. return super.setup( builder );
  34474. }
  34475. dispose() {
  34476. super.dispose();
  34477. if ( this.sampleRenderTarget !== null ) {
  34478. this.sampleRenderTarget.dispose();
  34479. }
  34480. }
  34481. }
  34482. // These jitter vectors are specified in integers because it is easier.
  34483. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
  34484. // before being used, thus these integers need to be scaled by 1/16.
  34485. //
  34486. // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
  34487. const _JitterVectors = [
  34488. [
  34489. [ 0, 0 ]
  34490. ],
  34491. [
  34492. [ 4, 4 ], [ - 4, - 4 ]
  34493. ],
  34494. [
  34495. [ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
  34496. ],
  34497. [
  34498. [ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
  34499. [ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
  34500. ],
  34501. [
  34502. [ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
  34503. [ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
  34504. [ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
  34505. [ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
  34506. ],
  34507. [
  34508. [ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
  34509. [ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
  34510. [ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
  34511. [ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
  34512. [ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
  34513. [ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
  34514. [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
  34515. [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
  34516. ]
  34517. ];
  34518. const ssaaPass = ( scene, camera ) => nodeObject( new SSAAPassNode( scene, camera ) );
  34519. const _size$2 = /*@__PURE__*/ new Vector2();
  34520. class StereoPassNode extends PassNode {
  34521. static get type() {
  34522. return 'StereoPassNode';
  34523. }
  34524. constructor( scene, camera ) {
  34525. super( PassNode.COLOR, scene, camera );
  34526. this.isStereoPassNode = true;
  34527. this.stereo = new StereoCamera();
  34528. this.stereo.aspect = 0.5;
  34529. }
  34530. updateBefore( frame ) {
  34531. const { renderer } = frame;
  34532. const { scene, camera, stereo, renderTarget } = this;
  34533. this._pixelRatio = renderer.getPixelRatio();
  34534. stereo.cameraL.coordinateSystem = renderer.coordinateSystem;
  34535. stereo.cameraR.coordinateSystem = renderer.coordinateSystem;
  34536. stereo.update( camera );
  34537. const size = renderer.getSize( _size$2 );
  34538. this.setSize( size.width, size.height );
  34539. const currentAutoClear = renderer.autoClear;
  34540. renderer.autoClear = false;
  34541. const currentRenderTarget = renderer.getRenderTarget();
  34542. const currentMRT = renderer.getMRT();
  34543. this._cameraNear.value = camera.near;
  34544. this._cameraFar.value = camera.far;
  34545. for ( const name in this._previousTextures ) {
  34546. this.toggleTexture( name );
  34547. }
  34548. renderer.setRenderTarget( renderTarget );
  34549. renderer.setMRT( this._mrt );
  34550. renderer.clear();
  34551. renderTarget.scissorTest = true;
  34552. renderTarget.scissor.set( 0, 0, renderTarget.width / 2, renderTarget.height );
  34553. renderTarget.viewport.set( 0, 0, renderTarget.width / 2, renderTarget.height );
  34554. renderer.render( scene, stereo.cameraL );
  34555. renderTarget.scissor.set( renderTarget.width / 2, 0, renderTarget.width / 2, renderTarget.height );
  34556. renderTarget.viewport.set( renderTarget.width / 2, 0, renderTarget.width / 2, renderTarget.height );
  34557. renderer.render( scene, stereo.cameraR );
  34558. renderTarget.scissorTest = false;
  34559. renderer.setRenderTarget( currentRenderTarget );
  34560. renderer.setMRT( currentMRT );
  34561. renderer.autoClear = currentAutoClear;
  34562. }
  34563. }
  34564. const stereoPass = ( scene, camera ) => nodeObject( new StereoPassNode( scene, camera ) );
  34565. const _size$1 = /*@__PURE__*/ new Vector2();
  34566. const _quadMesh$2 = /*@__PURE__*/ new QuadMesh();
  34567. class StereoCompositePassNode extends PassNode {
  34568. static get type() {
  34569. return 'StereoCompositePassNode';
  34570. }
  34571. constructor( scene, camera ) {
  34572. super( PassNode.COLOR, scene, camera );
  34573. this.isStereoCompositePassNode = true;
  34574. this.stereo = new StereoCamera();
  34575. const _params = { minFilter: LinearFilter, magFilter: NearestFilter, type: HalfFloatType };
  34576. this._renderTargetL = new RenderTarget( 1, 1, _params );
  34577. this._renderTargetR = new RenderTarget( 1, 1, _params );
  34578. this._mapLeft = texture( this._renderTargetL.texture );
  34579. this._mapRight = texture( this._renderTargetR.texture );
  34580. this._material = null;
  34581. }
  34582. updateStereoCamera( coordinateSystem ) {
  34583. this.stereo.cameraL.coordinateSystem = coordinateSystem;
  34584. this.stereo.cameraR.coordinateSystem = coordinateSystem;
  34585. this.stereo.update( this.camera );
  34586. }
  34587. setSize( width, height ) {
  34588. super.setSize( width, height );
  34589. this._renderTargetL.setSize( this.renderTarget.width, this.renderTarget.height );
  34590. this._renderTargetR.setSize( this.renderTarget.width, this.renderTarget.height );
  34591. }
  34592. updateBefore( frame ) {
  34593. const { renderer } = frame;
  34594. const { scene, stereo, renderTarget } = this;
  34595. this._pixelRatio = renderer.getPixelRatio();
  34596. this.updateStereoCamera( renderer.coordinateSystem );
  34597. const size = renderer.getSize( _size$1 );
  34598. this.setSize( size.width, size.height );
  34599. const currentRenderTarget = renderer.getRenderTarget();
  34600. // left
  34601. renderer.setRenderTarget( this._renderTargetL );
  34602. renderer.render( scene, stereo.cameraL );
  34603. // right
  34604. renderer.setRenderTarget( this._renderTargetR );
  34605. renderer.render( scene, stereo.cameraR );
  34606. // composite
  34607. renderer.setRenderTarget( renderTarget );
  34608. _quadMesh$2.material = this._material;
  34609. _quadMesh$2.render( renderer );
  34610. // restore
  34611. renderer.setRenderTarget( currentRenderTarget );
  34612. }
  34613. dispose() {
  34614. super.dispose();
  34615. this._renderTargetL.dispose();
  34616. this._renderTargetR.dispose();
  34617. if ( this._material !== null ) {
  34618. this._material.dispose();
  34619. }
  34620. }
  34621. }
  34622. class AnaglyphPassNode extends StereoCompositePassNode {
  34623. static get type() {
  34624. return 'AnaglyphPassNode';
  34625. }
  34626. constructor( scene, camera ) {
  34627. super( scene, camera );
  34628. this.isAnaglyphPassNode = true;
  34629. // Dubois matrices from https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.7.6968&rep=rep1&type=pdf#page=4
  34630. this._colorMatrixLeft = uniform( new Matrix3().fromArray( [
  34631. 0.456100, - 0.0400822, - 0.0152161,
  34632. 0.500484, - 0.0378246, - 0.0205971,
  34633. 0.176381, - 0.0157589, - 0.00546856
  34634. ] ) );
  34635. this._colorMatrixRight = uniform( new Matrix3().fromArray( [
  34636. - 0.0434706, 0.378476, - 0.0721527,
  34637. - 0.0879388, 0.73364, - 0.112961,
  34638. - 0.00155529, - 0.0184503, 1.2264
  34639. ] ) );
  34640. }
  34641. setup( builder ) {
  34642. const uvNode = uv();
  34643. const anaglyph = Fn( () => {
  34644. const colorL = this._mapLeft.uv( uvNode );
  34645. const colorR = this._mapRight.uv( uvNode );
  34646. const color = clamp( this._colorMatrixLeft.mul( colorL.rgb ).add( this._colorMatrixRight.mul( colorR.rgb ) ) );
  34647. return vec4( color.rgb, max$1( colorL.a, colorR.a ) );
  34648. } );
  34649. const material = this._material || ( this._material = new NodeMaterial() );
  34650. material.fragmentNode = anaglyph().context( builder.getSharedContext() );
  34651. material.name = 'Anaglyph';
  34652. material.needsUpdate = true;
  34653. return super.setup( builder );
  34654. }
  34655. }
  34656. const anaglyphPass = ( scene, camera ) => nodeObject( new AnaglyphPassNode( scene, camera ) );
  34657. class ParallaxBarrierPassNode extends StereoCompositePassNode {
  34658. static get type() {
  34659. return 'ParallaxBarrierPassNode';
  34660. }
  34661. constructor( scene, camera ) {
  34662. super( scene, camera );
  34663. this.isParallaxBarrierPassNode = true;
  34664. }
  34665. setup( builder ) {
  34666. const uvNode = uv();
  34667. const parallaxBarrier = Fn( () => {
  34668. const color = vec4().toVar();
  34669. If( mod( screenCoordinate.y, 2 ).greaterThan( 1 ), () => {
  34670. color.assign( this._mapLeft.uv( uvNode ) );
  34671. } ).Else( () => {
  34672. color.assign( this._mapRight.uv( uvNode ) );
  34673. } );
  34674. return color;
  34675. } );
  34676. const material = this._material || ( this._material = new NodeMaterial() );
  34677. material.fragmentNode = parallaxBarrier().context( builder.getSharedContext() );
  34678. material.needsUpdate = true;
  34679. return super.setup( builder );
  34680. }
  34681. }
  34682. const parallaxBarrierPass = ( scene, camera ) => nodeObject( new ParallaxBarrierPassNode( scene, camera ) );
  34683. class ScriptableValueNode extends Node {
  34684. static get type() {
  34685. return 'ScriptableValueNode';
  34686. }
  34687. constructor( value = null ) {
  34688. super();
  34689. this._value = value;
  34690. this._cache = null;
  34691. this.inputType = null;
  34692. this.outpuType = null;
  34693. this.events = new EventDispatcher();
  34694. this.isScriptableValueNode = true;
  34695. }
  34696. get isScriptableOutputNode() {
  34697. return this.outputType !== null;
  34698. }
  34699. set value( val ) {
  34700. if ( this._value === val ) return;
  34701. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  34702. URL.revokeObjectURL( this._cache );
  34703. this._cache = null;
  34704. }
  34705. this._value = val;
  34706. this.events.dispatchEvent( { type: 'change' } );
  34707. this.refresh();
  34708. }
  34709. get value() {
  34710. return this._value;
  34711. }
  34712. refresh() {
  34713. this.events.dispatchEvent( { type: 'refresh' } );
  34714. }
  34715. getValue() {
  34716. const value = this.value;
  34717. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  34718. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  34719. } else if ( value && value.value !== null && value.value !== undefined && (
  34720. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  34721. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  34722. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  34723. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  34724. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  34725. ( this.inputType === 'Color' && value.value.isColor ) ||
  34726. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  34727. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  34728. ) ) {
  34729. return value.value;
  34730. }
  34731. return this._cache || value;
  34732. }
  34733. getNodeType( builder ) {
  34734. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  34735. }
  34736. setup() {
  34737. return this.value && this.value.isNode ? this.value : float();
  34738. }
  34739. serialize( data ) {
  34740. super.serialize( data );
  34741. if ( this.value !== null ) {
  34742. if ( this.inputType === 'ArrayBuffer' ) {
  34743. data.value = arrayBufferToBase64( this.value );
  34744. } else {
  34745. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  34746. }
  34747. } else {
  34748. data.value = null;
  34749. }
  34750. data.inputType = this.inputType;
  34751. data.outputType = this.outputType;
  34752. }
  34753. deserialize( data ) {
  34754. super.deserialize( data );
  34755. let value = null;
  34756. if ( data.value !== null ) {
  34757. if ( data.inputType === 'ArrayBuffer' ) {
  34758. value = base64ToArrayBuffer( data.value );
  34759. } else if ( data.inputType === 'Texture' ) {
  34760. value = data.meta.textures[ data.value ];
  34761. } else {
  34762. value = data.meta.nodes[ data.value ] || null;
  34763. }
  34764. }
  34765. this.value = value;
  34766. this.inputType = data.inputType;
  34767. this.outputType = data.outputType;
  34768. }
  34769. }
  34770. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  34771. class Resources extends Map {
  34772. get( key, callback = null, ...params ) {
  34773. if ( this.has( key ) ) return super.get( key );
  34774. if ( callback !== null ) {
  34775. const value = callback( ...params );
  34776. this.set( key, value );
  34777. return value;
  34778. }
  34779. }
  34780. }
  34781. class Parameters {
  34782. constructor( scriptableNode ) {
  34783. this.scriptableNode = scriptableNode;
  34784. }
  34785. get parameters() {
  34786. return this.scriptableNode.parameters;
  34787. }
  34788. get layout() {
  34789. return this.scriptableNode.getLayout();
  34790. }
  34791. getInputLayout( id ) {
  34792. return this.scriptableNode.getInputLayout( id );
  34793. }
  34794. get( name ) {
  34795. const param = this.parameters[ name ];
  34796. const value = param ? param.getValue() : null;
  34797. return value;
  34798. }
  34799. }
  34800. const global = new Resources();
  34801. class ScriptableNode extends Node {
  34802. static get type() {
  34803. return 'ScriptableNode';
  34804. }
  34805. constructor( codeNode = null, parameters = {} ) {
  34806. super();
  34807. this.codeNode = codeNode;
  34808. this.parameters = parameters;
  34809. this._local = new Resources();
  34810. this._output = scriptableValue();
  34811. this._outputs = {};
  34812. this._source = this.source;
  34813. this._method = null;
  34814. this._object = null;
  34815. this._value = null;
  34816. this._needsOutputUpdate = true;
  34817. this.onRefresh = this.onRefresh.bind( this );
  34818. this.isScriptableNode = true;
  34819. }
  34820. get source() {
  34821. return this.codeNode ? this.codeNode.code : '';
  34822. }
  34823. setLocal( name, value ) {
  34824. return this._local.set( name, value );
  34825. }
  34826. getLocal( name ) {
  34827. return this._local.get( name );
  34828. }
  34829. onRefresh() {
  34830. this._refresh();
  34831. }
  34832. getInputLayout( id ) {
  34833. for ( const element of this.getLayout() ) {
  34834. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  34835. return element;
  34836. }
  34837. }
  34838. }
  34839. getOutputLayout( id ) {
  34840. for ( const element of this.getLayout() ) {
  34841. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  34842. return element;
  34843. }
  34844. }
  34845. }
  34846. setOutput( name, value ) {
  34847. const outputs = this._outputs;
  34848. if ( outputs[ name ] === undefined ) {
  34849. outputs[ name ] = scriptableValue( value );
  34850. } else {
  34851. outputs[ name ].value = value;
  34852. }
  34853. return this;
  34854. }
  34855. getOutput( name ) {
  34856. return this._outputs[ name ];
  34857. }
  34858. getParameter( name ) {
  34859. return this.parameters[ name ];
  34860. }
  34861. setParameter( name, value ) {
  34862. const parameters = this.parameters;
  34863. if ( value && value.isScriptableNode ) {
  34864. this.deleteParameter( name );
  34865. parameters[ name ] = value;
  34866. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  34867. } else if ( value && value.isScriptableValueNode ) {
  34868. this.deleteParameter( name );
  34869. parameters[ name ] = value;
  34870. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  34871. } else if ( parameters[ name ] === undefined ) {
  34872. parameters[ name ] = scriptableValue( value );
  34873. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  34874. } else {
  34875. parameters[ name ].value = value;
  34876. }
  34877. return this;
  34878. }
  34879. getValue() {
  34880. return this.getDefaultOutput().getValue();
  34881. }
  34882. deleteParameter( name ) {
  34883. let valueNode = this.parameters[ name ];
  34884. if ( valueNode ) {
  34885. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  34886. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  34887. }
  34888. return this;
  34889. }
  34890. clearParameters() {
  34891. for ( const name of Object.keys( this.parameters ) ) {
  34892. this.deleteParameter( name );
  34893. }
  34894. this.needsUpdate = true;
  34895. return this;
  34896. }
  34897. call( name, ...params ) {
  34898. const object = this.getObject();
  34899. const method = object[ name ];
  34900. if ( typeof method === 'function' ) {
  34901. return method( ...params );
  34902. }
  34903. }
  34904. async callAsync( name, ...params ) {
  34905. const object = this.getObject();
  34906. const method = object[ name ];
  34907. if ( typeof method === 'function' ) {
  34908. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  34909. }
  34910. }
  34911. getNodeType( builder ) {
  34912. return this.getDefaultOutputNode().getNodeType( builder );
  34913. }
  34914. refresh( output = null ) {
  34915. if ( output !== null ) {
  34916. this.getOutput( output ).refresh();
  34917. } else {
  34918. this._refresh();
  34919. }
  34920. }
  34921. getObject() {
  34922. if ( this.needsUpdate ) this.dispose();
  34923. if ( this._object !== null ) return this._object;
  34924. //
  34925. const refresh = () => this.refresh();
  34926. const setOutput = ( id, value ) => this.setOutput( id, value );
  34927. const parameters = new Parameters( this );
  34928. const THREE = global.get( 'THREE' );
  34929. const TSL = global.get( 'TSL' );
  34930. const method = this.getMethod( this.codeNode );
  34931. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  34932. this._object = method( ...params );
  34933. const layout = this._object.layout;
  34934. if ( layout ) {
  34935. if ( layout.cache === false ) {
  34936. this._local.clear();
  34937. }
  34938. // default output
  34939. this._output.outputType = layout.outputType || null;
  34940. if ( Array.isArray( layout.elements ) ) {
  34941. for ( const element of layout.elements ) {
  34942. const id = element.id || element.name;
  34943. if ( element.inputType ) {
  34944. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  34945. this.getParameter( id ).inputType = element.inputType;
  34946. }
  34947. if ( element.outputType ) {
  34948. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  34949. this.getOutput( id ).outputType = element.outputType;
  34950. }
  34951. }
  34952. }
  34953. }
  34954. return this._object;
  34955. }
  34956. deserialize( data ) {
  34957. super.deserialize( data );
  34958. for ( const name in this.parameters ) {
  34959. let valueNode = this.parameters[ name ];
  34960. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  34961. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  34962. }
  34963. }
  34964. getLayout() {
  34965. return this.getObject().layout;
  34966. }
  34967. getDefaultOutputNode() {
  34968. const output = this.getDefaultOutput().value;
  34969. if ( output && output.isNode ) {
  34970. return output;
  34971. }
  34972. return float();
  34973. }
  34974. getDefaultOutput() {
  34975. return this._exec()._output;
  34976. }
  34977. getMethod() {
  34978. if ( this.needsUpdate ) this.dispose();
  34979. if ( this._method !== null ) return this._method;
  34980. //
  34981. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  34982. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  34983. const properties = interfaceProps.join( ', ' );
  34984. const declarations = 'var ' + properties + '; var output = {};\n';
  34985. const returns = '\nreturn { ...output, ' + properties + ' };';
  34986. const code = declarations + this.codeNode.code + returns;
  34987. //
  34988. this._method = new Function( ...parametersProps, code );
  34989. return this._method;
  34990. }
  34991. dispose() {
  34992. if ( this._method === null ) return;
  34993. if ( this._object && typeof this._object.dispose === 'function' ) {
  34994. this._object.dispose();
  34995. }
  34996. this._method = null;
  34997. this._object = null;
  34998. this._source = null;
  34999. this._value = null;
  35000. this._needsOutputUpdate = true;
  35001. this._output.value = null;
  35002. this._outputs = {};
  35003. }
  35004. setup() {
  35005. return this.getDefaultOutputNode();
  35006. }
  35007. getCacheKey( force ) {
  35008. const cacheKey = [ this.source, this.getDefaultOutputNode().getCacheKey( force ) ];
  35009. for ( const param in this.parameters ) {
  35010. cacheKey.push( this.parameters[ param ].getCacheKey( force ) );
  35011. }
  35012. return cacheKey.join( ',' );
  35013. }
  35014. set needsUpdate( value ) {
  35015. if ( value === true ) this.dispose();
  35016. }
  35017. get needsUpdate() {
  35018. return this.source !== this._source;
  35019. }
  35020. _exec() {
  35021. if ( this.codeNode === null ) return this;
  35022. if ( this._needsOutputUpdate === true ) {
  35023. this._value = this.call( 'main' );
  35024. this._needsOutputUpdate = false;
  35025. }
  35026. this._output.value = this._value;
  35027. return this;
  35028. }
  35029. _refresh() {
  35030. this.needsUpdate = true;
  35031. this._exec();
  35032. this._output.refresh();
  35033. }
  35034. }
  35035. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  35036. class FogNode extends Node {
  35037. static get type() {
  35038. return 'FogNode';
  35039. }
  35040. constructor( colorNode, factorNode ) {
  35041. super( 'float' );
  35042. this.isFogNode = true;
  35043. this.colorNode = colorNode;
  35044. this.factorNode = factorNode;
  35045. }
  35046. getViewZNode( builder ) {
  35047. let viewZ;
  35048. const getViewZ = builder.context.getViewZ;
  35049. if ( getViewZ !== undefined ) {
  35050. viewZ = getViewZ( this );
  35051. }
  35052. return ( viewZ || positionView.z ).negate();
  35053. }
  35054. setup() {
  35055. return this.factorNode;
  35056. }
  35057. }
  35058. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  35059. class FogRangeNode extends FogNode {
  35060. static get type() {
  35061. return 'FogRangeNode';
  35062. }
  35063. constructor( colorNode, nearNode, farNode ) {
  35064. super( colorNode );
  35065. this.isFogRangeNode = true;
  35066. this.nearNode = nearNode;
  35067. this.farNode = farNode;
  35068. }
  35069. setup( builder ) {
  35070. const viewZ = this.getViewZNode( builder );
  35071. return smoothstep( this.nearNode, this.farNode, viewZ );
  35072. }
  35073. }
  35074. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  35075. class FogExp2Node extends FogNode {
  35076. static get type() {
  35077. return 'FogExp2Node';
  35078. }
  35079. constructor( colorNode, densityNode ) {
  35080. super( colorNode );
  35081. this.isFogExp2Node = true;
  35082. this.densityNode = densityNode;
  35083. }
  35084. setup( builder ) {
  35085. const viewZ = this.getViewZNode( builder );
  35086. const density = this.densityNode;
  35087. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  35088. }
  35089. }
  35090. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  35091. let min = null;
  35092. let max = null;
  35093. class RangeNode extends Node {
  35094. static get type() {
  35095. return 'RangeNode';
  35096. }
  35097. constructor( minNode = float(), maxNode = float() ) {
  35098. super();
  35099. this.minNode = minNode;
  35100. this.maxNode = maxNode;
  35101. }
  35102. getVectorLength( builder ) {
  35103. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  35104. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  35105. return minLength > maxLength ? minLength : maxLength;
  35106. }
  35107. getNodeType( builder ) {
  35108. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  35109. }
  35110. setup( builder ) {
  35111. const object = builder.object;
  35112. let output = null;
  35113. if ( object.count > 1 ) {
  35114. const minValue = this.minNode.value;
  35115. const maxValue = this.maxNode.value;
  35116. const minLength = builder.getTypeLength( getValueType( minValue ) );
  35117. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  35118. min = min || new Vector4();
  35119. max = max || new Vector4();
  35120. min.setScalar( 0 );
  35121. max.setScalar( 0 );
  35122. if ( minLength === 1 ) min.setScalar( minValue );
  35123. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  35124. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  35125. if ( maxLength === 1 ) max.setScalar( maxValue );
  35126. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  35127. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  35128. const stride = 4;
  35129. const length = stride * object.count;
  35130. const array = new Float32Array( length );
  35131. for ( let i = 0; i < length; i ++ ) {
  35132. const index = i % stride;
  35133. const minElementValue = min.getComponent( index );
  35134. const maxElementValue = max.getComponent( index );
  35135. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  35136. }
  35137. const nodeType = this.getNodeType( builder );
  35138. if ( object.count <= 4096 ) {
  35139. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  35140. } else {
  35141. // TODO: Improve anonymous buffer attribute creation removing this part
  35142. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  35143. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  35144. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  35145. }
  35146. } else {
  35147. output = float( 0 );
  35148. }
  35149. return output;
  35150. }
  35151. }
  35152. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  35153. const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => {
  35154. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  35155. } );
  35156. const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  35157. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  35158. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  35159. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  35160. const texelSize = vec2( 1 ).div( mapSize );
  35161. const dx0 = texelSize.x.negate().mul( radius );
  35162. const dy0 = texelSize.y.negate().mul( radius );
  35163. const dx1 = texelSize.x.mul( radius );
  35164. const dy1 = texelSize.y.mul( radius );
  35165. const dx2 = dx0.div( 2 );
  35166. const dy2 = dy0.div( 2 );
  35167. const dx3 = dx1.div( 2 );
  35168. const dy3 = dy1.div( 2 );
  35169. return add(
  35170. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  35171. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  35172. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  35173. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  35174. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  35175. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  35176. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  35177. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  35178. depthCompare( shadowCoord.xy, shadowCoord.z ),
  35179. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  35180. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  35181. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  35182. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  35183. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  35184. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  35185. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  35186. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  35187. ).mul( 1 / 17 );
  35188. } );
  35189. const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  35190. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  35191. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  35192. const texelSize = vec2( 1 ).div( mapSize );
  35193. const dx = texelSize.x;
  35194. const dy = texelSize.y;
  35195. const uv = shadowCoord.xy;
  35196. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  35197. uv.subAssign( f.mul( texelSize ) );
  35198. return add(
  35199. depthCompare( uv, shadowCoord.z ),
  35200. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  35201. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  35202. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  35203. mix(
  35204. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  35205. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  35206. f.x
  35207. ),
  35208. mix(
  35209. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  35210. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  35211. f.x
  35212. ),
  35213. mix(
  35214. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  35215. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  35216. f.y
  35217. ),
  35218. mix(
  35219. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  35220. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  35221. f.y
  35222. ),
  35223. mix(
  35224. mix(
  35225. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  35226. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  35227. f.x
  35228. ),
  35229. mix(
  35230. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  35231. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  35232. f.x
  35233. ),
  35234. f.y
  35235. )
  35236. ).mul( 1 / 9 );
  35237. } );
  35238. // VSM
  35239. const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => {
  35240. const occlusion = float( 1 ).toVar();
  35241. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  35242. const hardShadow = step( shadowCoord.z, distribution.x );
  35243. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  35244. const distance = shadowCoord.z.sub( distribution.x );
  35245. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  35246. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  35247. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  35248. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  35249. } );
  35250. return occlusion;
  35251. } );
  35252. const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => {
  35253. const mean = float( 0 ).toVar();
  35254. const squaredMean = float( 0 ).toVar();
  35255. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  35256. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  35257. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  35258. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  35259. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  35260. mean.addAssign( depth );
  35261. squaredMean.addAssign( depth.mul( depth ) );
  35262. } );
  35263. mean.divAssign( samples );
  35264. squaredMean.divAssign( samples );
  35265. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  35266. return vec2( mean, std_dev );
  35267. } );
  35268. const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => {
  35269. const mean = float( 0 ).toVar();
  35270. const squaredMean = float( 0 ).toVar();
  35271. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  35272. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  35273. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  35274. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  35275. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  35276. mean.addAssign( distribution.x );
  35277. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  35278. } );
  35279. mean.divAssign( samples );
  35280. squaredMean.divAssign( samples );
  35281. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  35282. return vec2( mean, std_dev );
  35283. } );
  35284. const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ];
  35285. //
  35286. let _overrideMaterial = null;
  35287. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  35288. class AnalyticLightNode extends LightingNode {
  35289. static get type() {
  35290. return 'AnalyticLightNode';
  35291. }
  35292. constructor( light = null ) {
  35293. super();
  35294. this.updateType = NodeUpdateType.FRAME;
  35295. this.light = light;
  35296. this.color = new Color();
  35297. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  35298. this.baseColorNode = null;
  35299. this.shadowMap = null;
  35300. this.shadowNode = null;
  35301. this.shadowColorNode = null;
  35302. this.vsmShadowMapVertical = null;
  35303. this.vsmShadowMapHorizontal = null;
  35304. this.vsmMaterialVertical = null;
  35305. this.vsmMaterialHorizontal = null;
  35306. this.isAnalyticLightNode = true;
  35307. }
  35308. getCacheKey() {
  35309. return super.getCacheKey() + '-' + ( this.light.id + '-' + ( this.light.castShadow ? '1' : '0' ) );
  35310. }
  35311. getHash() {
  35312. return this.light.uuid;
  35313. }
  35314. setupShadow( builder ) {
  35315. const { object, renderer } = builder;
  35316. let shadowColorNode = this.shadowColorNode;
  35317. if ( shadowColorNode === null ) {
  35318. if ( _overrideMaterial === null ) {
  35319. _overrideMaterial = new NodeMaterial();
  35320. _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  35321. _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  35322. _overrideMaterial.name = 'ShadowMaterial';
  35323. }
  35324. const shadowMapType = renderer.shadowMap.type;
  35325. const shadow = this.light.shadow;
  35326. const depthTexture = new DepthTexture();
  35327. depthTexture.compareFunction = LessCompare;
  35328. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  35329. shadowMap.depthTexture = depthTexture;
  35330. shadow.camera.updateProjectionMatrix();
  35331. // VSM
  35332. if ( shadowMapType === VSMShadowMap ) {
  35333. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  35334. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  35335. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  35336. const shadowPassVertical = texture( depthTexture );
  35337. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  35338. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  35339. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  35340. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  35341. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  35342. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  35343. material.name = 'VSMVertical';
  35344. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  35345. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  35346. material.name = 'VSMHorizontal';
  35347. }
  35348. //
  35349. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  35350. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  35351. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  35352. const position = object.material.shadowPositionNode || positionWorld;
  35353. let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( normalWorld.mul( normalBias ) ) );
  35354. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  35355. let coordZ = shadowCoord.z.add( bias );
  35356. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  35357. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Convertion [ 0, 1 ] to [ - 1, 1 ]
  35358. }
  35359. shadowCoord = vec3(
  35360. shadowCoord.x,
  35361. shadowCoord.y.oneMinus(), // follow webgpu standards
  35362. coordZ
  35363. );
  35364. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  35365. .and( shadowCoord.x.lessThanEqual( 1 ) )
  35366. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  35367. .and( shadowCoord.y.lessThanEqual( 1 ) )
  35368. .and( shadowCoord.z.lessThanEqual( 1 ) );
  35369. //
  35370. const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null;
  35371. if ( filterFn === null ) {
  35372. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  35373. }
  35374. const shadowColor = texture( shadowMap.texture, shadowCoord );
  35375. const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) );
  35376. this.shadowMap = shadowMap;
  35377. this.light.shadow.map = shadowMap;
  35378. this.shadowNode = shadowNode;
  35379. this.shadowColorNode = shadowColorNode = this.colorNode.mul( mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ) );
  35380. this.baseColorNode = this.colorNode;
  35381. }
  35382. //
  35383. this.colorNode = shadowColorNode;
  35384. this.updateBeforeType = NodeUpdateType.RENDER;
  35385. }
  35386. setup( builder ) {
  35387. this.colorNode = this.baseColorNode || this.colorNode;
  35388. if ( this.light.castShadow ) {
  35389. if ( builder.object.receiveShadow ) {
  35390. this.setupShadow( builder );
  35391. }
  35392. } else if ( this.shadowNode !== null ) {
  35393. this.disposeShadow();
  35394. }
  35395. }
  35396. updateShadow( frame ) {
  35397. const { shadowMap, light } = this;
  35398. const { renderer, scene, camera } = frame;
  35399. const shadowType = renderer.shadowMap.type;
  35400. const depthVersion = shadowMap.depthTexture.version;
  35401. this._depthVersionCached = depthVersion;
  35402. const currentOverrideMaterial = scene.overrideMaterial;
  35403. scene.overrideMaterial = _overrideMaterial;
  35404. shadowMap.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  35405. light.shadow.updateMatrices( light );
  35406. light.shadow.camera.layers.mask = camera.layers.mask;
  35407. const currentRenderTarget = renderer.getRenderTarget();
  35408. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  35409. renderer.setRenderObjectFunction( ( object, ...params ) => {
  35410. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  35411. renderer.renderObject( object, ...params );
  35412. }
  35413. } );
  35414. renderer.setRenderTarget( shadowMap );
  35415. renderer.render( scene, light.shadow.camera );
  35416. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  35417. // vsm blur pass
  35418. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  35419. this.vsmPass( frame, light );
  35420. }
  35421. renderer.setRenderTarget( currentRenderTarget );
  35422. scene.overrideMaterial = currentOverrideMaterial;
  35423. }
  35424. vsmPass( frame, light ) {
  35425. const { renderer } = frame;
  35426. this.vsmShadowMapVertical.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  35427. this.vsmShadowMapHorizontal.setSize( light.shadow.mapSize.width, light.shadow.mapSize.height );
  35428. renderer.setRenderTarget( this.vsmShadowMapVertical );
  35429. _quadMesh$1.material = this.vsmMaterialVertical;
  35430. _quadMesh$1.render( renderer );
  35431. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  35432. _quadMesh$1.material = this.vsmMaterialHorizontal;
  35433. _quadMesh$1.render( renderer );
  35434. }
  35435. disposeShadow() {
  35436. this.shadowMap.dispose();
  35437. this.shadowMap = null;
  35438. if ( this.vsmShadowMapVertical !== null ) {
  35439. this.vsmShadowMapVertical.dispose();
  35440. this.vsmShadowMapVertical = null;
  35441. this.vsmMaterialVertical.dispose();
  35442. this.vsmMaterialVertical = null;
  35443. }
  35444. if ( this.vsmShadowMapHorizontal !== null ) {
  35445. this.vsmShadowMapHorizontal.dispose();
  35446. this.vsmShadowMapHorizontal = null;
  35447. this.vsmMaterialHorizontal.dispose();
  35448. this.vsmMaterialHorizontal = null;
  35449. }
  35450. this.shadowNode = null;
  35451. this.shadowColorNode = null;
  35452. this.baseColorNode = null;
  35453. this.updateBeforeType = NodeUpdateType.NONE;
  35454. }
  35455. updateBefore( frame ) {
  35456. const shadow = this.light.shadow;
  35457. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  35458. if ( needsUpdate ) {
  35459. this.updateShadow( frame );
  35460. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  35461. shadow.needsUpdate = false;
  35462. }
  35463. }
  35464. }
  35465. update( /*frame*/ ) {
  35466. const { light } = this;
  35467. this.color.copy( light.color ).multiplyScalar( light.intensity );
  35468. }
  35469. }
  35470. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  35471. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  35472. // based upon Frostbite 3 Moving to Physically-based Rendering
  35473. // page 32, equation 26: E[window1]
  35474. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  35475. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  35476. return cutoffDistance.greaterThan( 0 ).select(
  35477. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  35478. distanceFalloff
  35479. );
  35480. } ); // validated
  35481. let uniformsLib;
  35482. function getLightData( light ) {
  35483. uniformsLib = uniformsLib || new WeakMap();
  35484. let uniforms = uniformsLib.get( light );
  35485. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  35486. return uniforms;
  35487. }
  35488. function lightPosition( light ) {
  35489. const data = getLightData( light );
  35490. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  35491. }
  35492. function lightTargetPosition( light ) {
  35493. const data = getLightData( light );
  35494. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  35495. }
  35496. function lightViewPosition( light ) {
  35497. const data = getLightData( light );
  35498. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  35499. self.value = self.value || new Vector3();
  35500. self.value.setFromMatrixPosition( light.matrixWorld );
  35501. self.value.applyMatrix4( camera.matrixWorldInverse );
  35502. } ) );
  35503. }
  35504. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  35505. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  35506. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  35507. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  35508. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  35509. const result = word.shiftRight( 22 ).bitXor( word );
  35510. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  35511. } );
  35512. // remapping functions https://iquilezles.org/articles/functions/
  35513. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  35514. 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 ) );
  35515. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  35516. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  35517. // https://github.com/cabbibo/glsl-tri-noise-3d
  35518. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  35519. return x.fract().sub( .5 ).abs();
  35520. } ).setLayout( {
  35521. name: 'tri',
  35522. type: 'float',
  35523. inputs: [
  35524. { name: 'x', type: 'float' }
  35525. ]
  35526. } );
  35527. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  35528. 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. ) ) ) ) );
  35529. } ).setLayout( {
  35530. name: 'tri3',
  35531. type: 'vec3',
  35532. inputs: [
  35533. { name: 'p', type: 'vec3' }
  35534. ]
  35535. } );
  35536. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  35537. const p = vec3( p_immutable ).toVar();
  35538. const z = float( 1.4 ).toVar();
  35539. const rz = float( 0.0 ).toVar();
  35540. const bp = vec3( p ).toVar();
  35541. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  35542. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  35543. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  35544. bp.mulAssign( 1.8 );
  35545. z.mulAssign( 1.5 );
  35546. p.mulAssign( 1.2 );
  35547. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  35548. rz.addAssign( t.div( z ) );
  35549. bp.addAssign( 0.14 );
  35550. } );
  35551. return rz;
  35552. } ).setLayout( {
  35553. name: 'triNoise3D',
  35554. type: 'float',
  35555. inputs: [
  35556. { name: 'p', type: 'vec3' },
  35557. { name: 'spd', type: 'float' },
  35558. { name: 'time', type: 'float' }
  35559. ]
  35560. } );
  35561. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  35562. return rotate( uv.sub( center ), rotation ).add( center );
  35563. } );
  35564. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  35565. const delta = uv.sub( center );
  35566. const delta2 = delta.dot( delta );
  35567. const delta4 = delta2.mul( delta2 );
  35568. const deltaOffset = delta4.mul( strength );
  35569. return uv.add( delta.mul( deltaOffset ) );
  35570. } );
  35571. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  35572. let worldMatrix;
  35573. if ( position !== null ) {
  35574. worldMatrix = modelWorldMatrix.toVar();
  35575. worldMatrix[ 3 ][ 0 ] = position.x;
  35576. worldMatrix[ 3 ][ 1 ] = position.y;
  35577. worldMatrix[ 3 ][ 2 ] = position.z;
  35578. } else {
  35579. worldMatrix = modelWorldMatrix;
  35580. }
  35581. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  35582. if ( defined( horizontal ) ) {
  35583. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  35584. modelViewMatrix[ 0 ][ 1 ] = 0;
  35585. modelViewMatrix[ 0 ][ 2 ] = 0;
  35586. }
  35587. if ( defined( vertical ) ) {
  35588. modelViewMatrix[ 1 ][ 0 ] = 0;
  35589. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  35590. modelViewMatrix[ 1 ][ 2 ] = 0;
  35591. }
  35592. modelViewMatrix[ 2 ][ 0 ] = 0;
  35593. modelViewMatrix[ 2 ][ 1 ] = 0;
  35594. modelViewMatrix[ 2 ][ 2 ] = 1;
  35595. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  35596. } );
  35597. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  35598. const depth = linearDepth();
  35599. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  35600. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  35601. return finalUV;
  35602. } );
  35603. const _objectData = new WeakMap();
  35604. class VelocityNode extends TempNode {
  35605. static get type() {
  35606. return 'VelocityNode';
  35607. }
  35608. constructor() {
  35609. super( 'vec2' );
  35610. this.updateType = NodeUpdateType.OBJECT;
  35611. this.updateAfterType = NodeUpdateType.OBJECT;
  35612. this.previousModelWorldMatrix = uniform( new Matrix4() );
  35613. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  35614. this.previousCameraViewMatrix = uniform( new Matrix4() );
  35615. }
  35616. update( { frameId, camera, object } ) {
  35617. const previousModelMatrix = getPreviousMatrix( object );
  35618. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  35619. //
  35620. const cameraData = getData( camera );
  35621. if ( cameraData.frameId !== frameId ) {
  35622. cameraData.frameId = frameId;
  35623. if ( cameraData.previousProjectionMatrix === undefined ) {
  35624. cameraData.previousProjectionMatrix = new Matrix4();
  35625. cameraData.previousCameraViewMatrix = new Matrix4();
  35626. cameraData.currentProjectionMatrix = new Matrix4();
  35627. cameraData.currentCameraViewMatrix = new Matrix4();
  35628. cameraData.previousProjectionMatrix.copy( camera.projectionMatrix );
  35629. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  35630. } else {
  35631. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  35632. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  35633. }
  35634. cameraData.currentProjectionMatrix.copy( camera.projectionMatrix );
  35635. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  35636. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  35637. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  35638. }
  35639. }
  35640. updateAfter( { object } ) {
  35641. getPreviousMatrix( object ).copy( object.matrixWorld );
  35642. }
  35643. setup( /*builder*/ ) {
  35644. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  35645. const clipPositionCurrent = cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  35646. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  35647. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  35648. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  35649. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  35650. return velocity;
  35651. }
  35652. }
  35653. function getData( object ) {
  35654. let objectData = _objectData.get( object );
  35655. if ( objectData === undefined ) {
  35656. objectData = {};
  35657. _objectData.set( object, objectData );
  35658. }
  35659. return objectData;
  35660. }
  35661. function getPreviousMatrix( object, index = 0 ) {
  35662. const objectData = getData( object );
  35663. let matrix = objectData[ index ];
  35664. if ( matrix === undefined ) {
  35665. objectData[ index ] = matrix = new Matrix4();
  35666. }
  35667. return matrix;
  35668. }
  35669. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  35670. const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  35671. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  35672. } ).setLayout( {
  35673. name: 'burnBlend',
  35674. type: 'vec3',
  35675. inputs: [
  35676. { name: 'base', type: 'vec3' },
  35677. { name: 'blend', type: 'vec3' }
  35678. ]
  35679. } );
  35680. const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  35681. return min$1( base.div( blend.oneMinus() ), 1.0 );
  35682. } ).setLayout( {
  35683. name: 'dodgeBlend',
  35684. type: 'vec3',
  35685. inputs: [
  35686. { name: 'base', type: 'vec3' },
  35687. { name: 'blend', type: 'vec3' }
  35688. ]
  35689. } );
  35690. const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  35691. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  35692. } ).setLayout( {
  35693. name: 'screenBlend',
  35694. type: 'vec3',
  35695. inputs: [
  35696. { name: 'base', type: 'vec3' },
  35697. { name: 'blend', type: 'vec3' }
  35698. ]
  35699. } );
  35700. const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  35701. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  35702. } ).setLayout( {
  35703. name: 'overlayBlend',
  35704. type: 'vec3',
  35705. inputs: [
  35706. { name: 'base', type: 'vec3' },
  35707. { name: 'blend', type: 'vec3' }
  35708. ]
  35709. } );
  35710. const motionBlur = /*@__PURE__*/ Fn( ( [ inputNode, velocity, numSamples = int( 16 ) ] ) => {
  35711. const sampleColor = ( uv ) => inputNode.uv( uv );
  35712. const uvs = uv();
  35713. const colorResult = sampleColor( uvs ).toVar();
  35714. const fSamples = float( numSamples );
  35715. Loop( { start: int( 1 ), end: numSamples, type: 'int', condition: '<=' }, ( { i } ) => {
  35716. const offset = velocity.mul( float( i ).div( fSamples.sub( 1 ) ).sub( 0.5 ) );
  35717. colorResult.addAssign( sampleColor( uvs.add( offset ) ) );
  35718. } );
  35719. colorResult.divAssign( fSamples );
  35720. return colorResult;
  35721. } );
  35722. const bleach = /*@__PURE__*/ Fn( ( [ color, opacity = 1 ] ) => {
  35723. const base = color;
  35724. const lum = luminance( base.rgb );
  35725. const blend = vec3( lum );
  35726. const L = min$1( 1.0, max$1( 0.0, float( 10.0 ).mul( lum.sub( 0.45 ) ) ) );
  35727. const result1 = blend.mul( base.rgb ).mul( 2.0 );
  35728. const result2 = float( 2.0 ).mul( blend.oneMinus() ).mul( base.rgb.oneMinus() ).oneMinus();
  35729. const newColor = mix( result1, result2, L );
  35730. const A2 = base.a.mul( opacity );
  35731. const mixRGB = A2.mul( newColor.rgb );
  35732. mixRGB.addAssign( base.rgb.mul( A2.oneMinus() ) );
  35733. return vec4( mixRGB, base.a );
  35734. } );
  35735. const sepia = /*@__PURE__*/ Fn( ( [ color ] ) => {
  35736. const c = vec3( color );
  35737. // https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/sepia.js
  35738. return vec4(
  35739. dot( c, vec3( 0.393, 0.769, 0.189 ) ),
  35740. dot( c, vec3( 0.349, 0.686, 0.168 ) ),
  35741. dot( c, vec3( 0.272, 0.534, 0.131 ) ),
  35742. color.a
  35743. );
  35744. } );
  35745. const sRGBToLinearSRGB = /*@__PURE__*/ Fn( ( [ color ] ) => {
  35746. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  35747. const b = color.mul( 0.0773993808 );
  35748. const factor = color.lessThanEqual( 0.04045 );
  35749. const rgbResult = mix( a, b, factor );
  35750. return rgbResult;
  35751. } ).setLayout( {
  35752. name: 'sRGBToLinearSRGB',
  35753. type: 'vec3',
  35754. inputs: [
  35755. { name: 'color', type: 'vec3' }
  35756. ]
  35757. } );
  35758. const linearSRGBTosRGB = /*@__PURE__*/ Fn( ( [ color ] ) => {
  35759. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  35760. const b = color.mul( 12.92 );
  35761. const factor = color.lessThanEqual( 0.0031308 );
  35762. const rgbResult = mix( a, b, factor );
  35763. return rgbResult;
  35764. } ).setLayout( {
  35765. name: 'linearSRGBTosRGB',
  35766. type: 'vec3',
  35767. inputs: [
  35768. { name: 'color', type: 'vec3' }
  35769. ]
  35770. } );
  35771. // exposure only
  35772. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  35773. return color.mul( exposure ).clamp();
  35774. } ).setLayout( {
  35775. name: 'linearToneMapping',
  35776. type: 'vec3',
  35777. inputs: [
  35778. { name: 'color', type: 'vec3' },
  35779. { name: 'exposure', type: 'float' }
  35780. ]
  35781. } );
  35782. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  35783. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  35784. color = color.mul( exposure );
  35785. return color.div( color.add( 1.0 ) ).clamp();
  35786. } ).setLayout( {
  35787. name: 'reinhardToneMapping',
  35788. type: 'vec3',
  35789. inputs: [
  35790. { name: 'color', type: 'vec3' },
  35791. { name: 'exposure', type: 'float' }
  35792. ]
  35793. } );
  35794. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  35795. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  35796. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  35797. color = color.mul( exposure );
  35798. color = color.sub( 0.004 ).max( 0.0 );
  35799. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  35800. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  35801. return a.div( b ).pow( 2.2 );
  35802. } ).setLayout( {
  35803. name: 'cineonToneMapping',
  35804. type: 'vec3',
  35805. inputs: [
  35806. { name: 'color', type: 'vec3' },
  35807. { name: 'exposure', type: 'float' }
  35808. ]
  35809. } );
  35810. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  35811. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  35812. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  35813. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  35814. return a.div( b );
  35815. } );
  35816. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  35817. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  35818. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  35819. const ACESInputMat = mat3(
  35820. 0.59719, 0.35458, 0.04823,
  35821. 0.07600, 0.90834, 0.01566,
  35822. 0.02840, 0.13383, 0.83777
  35823. );
  35824. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  35825. const ACESOutputMat = mat3(
  35826. 1.60475, - 0.53108, - 0.07367,
  35827. - 0.10208, 1.10813, - 0.00605,
  35828. - 0.00327, - 0.07276, 1.07602
  35829. );
  35830. color = color.mul( exposure ).div( 0.6 );
  35831. color = ACESInputMat.mul( color );
  35832. // Apply RRT and ODT
  35833. color = RRTAndODTFit( color );
  35834. color = ACESOutputMat.mul( color );
  35835. // Clamp to [0, 1]
  35836. return color.clamp();
  35837. } ).setLayout( {
  35838. name: 'acesFilmicToneMapping',
  35839. type: 'vec3',
  35840. inputs: [
  35841. { name: 'color', type: 'vec3' },
  35842. { name: 'exposure', type: 'float' }
  35843. ]
  35844. } );
  35845. 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 ) );
  35846. 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 ) );
  35847. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  35848. const x = vec3( x_immutable ).toVar();
  35849. const x2 = vec3( x.mul( x ) ).toVar();
  35850. const x4 = vec3( x2.mul( x2 ) ).toVar();
  35851. 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 ) ) ) );
  35852. } );
  35853. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  35854. const colortone = vec3( color ).toVar();
  35855. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  35856. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  35857. const AgxMinEv = float( - 12.47393 );
  35858. const AgxMaxEv = float( 4.026069 );
  35859. colortone.mulAssign( exposure );
  35860. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  35861. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  35862. colortone.assign( max$1( colortone, 1e-10 ) );
  35863. colortone.assign( log2( colortone ) );
  35864. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  35865. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  35866. colortone.assign( agxDefaultContrastApprox( colortone ) );
  35867. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  35868. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  35869. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  35870. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  35871. return colortone;
  35872. } ).setLayout( {
  35873. name: 'agxToneMapping',
  35874. type: 'vec3',
  35875. inputs: [
  35876. { name: 'color', type: 'vec3' },
  35877. { name: 'exposure', type: 'float' }
  35878. ]
  35879. } );
  35880. // https://modelviewer.dev/examples/tone-mapping
  35881. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  35882. const StartCompression = float( 0.8 - 0.04 );
  35883. const Desaturation = float( 0.15 );
  35884. color = color.mul( exposure );
  35885. const x = min$1( color.r, min$1( color.g, color.b ) );
  35886. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  35887. color.subAssign( offset );
  35888. const peak = max$1( color.r, max$1( color.g, color.b ) );
  35889. If( peak.lessThan( StartCompression ), () => {
  35890. return color;
  35891. } );
  35892. const d = sub( 1, StartCompression );
  35893. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  35894. color.mulAssign( newPeak.div( peak ) );
  35895. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  35896. return mix( color, vec3( newPeak ), g );
  35897. } ).setLayout( {
  35898. name: 'neutralToneMapping',
  35899. type: 'vec3',
  35900. inputs: [
  35901. { name: 'color', type: 'vec3' },
  35902. { name: 'exposure', type: 'float' }
  35903. ]
  35904. } );
  35905. class BarrierNode extends Node {
  35906. constructor( scope ) {
  35907. super();
  35908. this.scope = scope;
  35909. }
  35910. generate( builder ) {
  35911. const { scope } = this;
  35912. const { renderer } = builder;
  35913. if ( renderer.backend.isWebGLBackend === true ) {
  35914. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  35915. } else {
  35916. builder.addLineFlowCode( `${scope}Barrier()` );
  35917. }
  35918. }
  35919. }
  35920. const barrier = nodeProxy( BarrierNode );
  35921. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  35922. const storageBarrier = () => barrier( 'storage' ).append();
  35923. const textureBarrier = () => barrier( 'texture' ).append();
  35924. class WorkgroupInfoElementNode extends ArrayElementNode {
  35925. constructor( workgroupInfoNode, indexNode ) {
  35926. super( workgroupInfoNode, indexNode );
  35927. this.isWorkgroupInfoElementNode = true;
  35928. }
  35929. generate( builder, output ) {
  35930. let snippet;
  35931. const isAssignContext = builder.context.assign;
  35932. snippet = super.generate( builder );
  35933. if ( isAssignContext !== true ) {
  35934. const type = this.getNodeType( builder );
  35935. snippet = builder.format( snippet, type, output );
  35936. }
  35937. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  35938. return snippet;
  35939. }
  35940. }
  35941. class WorkgroupInfoNode extends Node {
  35942. constructor( scope, bufferType, bufferCount = 0 ) {
  35943. super( bufferType );
  35944. this.bufferType = bufferType;
  35945. this.bufferCount = bufferCount;
  35946. this.isWorkgroupInfoNode = true;
  35947. this.scope = scope;
  35948. }
  35949. label( name ) {
  35950. this.name = name;
  35951. return this;
  35952. }
  35953. getHash() {
  35954. return this.uuid;
  35955. }
  35956. setScope( scope ) {
  35957. this.scope = scope;
  35958. return this;
  35959. }
  35960. getInputType( /*builder*/ ) {
  35961. return `${this.scope}Array`;
  35962. }
  35963. element( indexNode ) {
  35964. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  35965. }
  35966. generate( builder ) {
  35967. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  35968. }
  35969. }
  35970. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  35971. class AtomicFunctionNode extends TempNode {
  35972. static get type() {
  35973. return 'AtomicFunctionNode';
  35974. }
  35975. constructor( method, pointerNode, valueNode, storeNode = null ) {
  35976. super( 'uint' );
  35977. this.method = method;
  35978. this.pointerNode = pointerNode;
  35979. this.valueNode = valueNode;
  35980. this.storeNode = storeNode;
  35981. }
  35982. getInputType( builder ) {
  35983. return this.pointerNode.getNodeType( builder );
  35984. }
  35985. getNodeType( builder ) {
  35986. return this.getInputType( builder );
  35987. }
  35988. generate( builder ) {
  35989. const method = this.method;
  35990. const type = this.getNodeType( builder );
  35991. const inputType = this.getInputType( builder );
  35992. const a = this.pointerNode;
  35993. const b = this.valueNode;
  35994. const params = [];
  35995. params.push( `&${ a.build( builder, inputType ) }` );
  35996. params.push( b.build( builder, inputType ) );
  35997. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  35998. if ( this.storeNode !== null ) {
  35999. const varSnippet = this.storeNode.build( builder, inputType );
  36000. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}` );
  36001. } else {
  36002. builder.addLineFlowCode( methodSnippet );
  36003. }
  36004. }
  36005. }
  36006. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  36007. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  36008. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  36009. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  36010. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  36011. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  36012. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  36013. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  36014. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  36015. const atomicNode = nodeProxy( AtomicFunctionNode );
  36016. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  36017. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  36018. node.append();
  36019. return node;
  36020. };
  36021. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  36022. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  36023. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  36024. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  36025. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  36026. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  36027. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  36028. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  36029. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  36030. const uv = coord.mul( 2.0 );
  36031. const cx = uv.x.floor();
  36032. const cy = uv.y.floor();
  36033. const result = cx.add( cy ).mod( 2.0 );
  36034. return result.sign();
  36035. } );
  36036. // Three.js Transpiler
  36037. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  36038. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  36039. const f = float( f_immutable ).toVar();
  36040. const t = float( t_immutable ).toVar();
  36041. const b = bool( b_immutable ).toVar();
  36042. return select( b, t, f );
  36043. } ).setLayout( {
  36044. name: 'mx_select',
  36045. type: 'float',
  36046. inputs: [
  36047. { name: 'b', type: 'bool' },
  36048. { name: 't', type: 'float' },
  36049. { name: 'f', type: 'float' }
  36050. ]
  36051. } );
  36052. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  36053. const b = bool( b_immutable ).toVar();
  36054. const val = float( val_immutable ).toVar();
  36055. return select( b, val.negate(), val );
  36056. } ).setLayout( {
  36057. name: 'mx_negate_if',
  36058. type: 'float',
  36059. inputs: [
  36060. { name: 'val', type: 'float' },
  36061. { name: 'b', type: 'bool' }
  36062. ]
  36063. } );
  36064. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  36065. const x = float( x_immutable ).toVar();
  36066. return int( floor( x ) );
  36067. } ).setLayout( {
  36068. name: 'mx_floor',
  36069. type: 'int',
  36070. inputs: [
  36071. { name: 'x', type: 'float' }
  36072. ]
  36073. } );
  36074. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  36075. const x = float( x_immutable ).toVar();
  36076. i.assign( mx_floor( x ) );
  36077. return x.sub( float( i ) );
  36078. } );
  36079. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  36080. const t = float( t_immutable ).toVar();
  36081. const s = float( s_immutable ).toVar();
  36082. const v3 = float( v3_immutable ).toVar();
  36083. const v2 = float( v2_immutable ).toVar();
  36084. const v1 = float( v1_immutable ).toVar();
  36085. const v0 = float( v0_immutable ).toVar();
  36086. const s1 = float( sub( 1.0, s ) ).toVar();
  36087. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  36088. } ).setLayout( {
  36089. name: 'mx_bilerp_0',
  36090. type: 'float',
  36091. inputs: [
  36092. { name: 'v0', type: 'float' },
  36093. { name: 'v1', type: 'float' },
  36094. { name: 'v2', type: 'float' },
  36095. { name: 'v3', type: 'float' },
  36096. { name: 's', type: 'float' },
  36097. { name: 't', type: 'float' }
  36098. ]
  36099. } );
  36100. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  36101. const t = float( t_immutable ).toVar();
  36102. const s = float( s_immutable ).toVar();
  36103. const v3 = vec3( v3_immutable ).toVar();
  36104. const v2 = vec3( v2_immutable ).toVar();
  36105. const v1 = vec3( v1_immutable ).toVar();
  36106. const v0 = vec3( v0_immutable ).toVar();
  36107. const s1 = float( sub( 1.0, s ) ).toVar();
  36108. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  36109. } ).setLayout( {
  36110. name: 'mx_bilerp_1',
  36111. type: 'vec3',
  36112. inputs: [
  36113. { name: 'v0', type: 'vec3' },
  36114. { name: 'v1', type: 'vec3' },
  36115. { name: 'v2', type: 'vec3' },
  36116. { name: 'v3', type: 'vec3' },
  36117. { name: 's', type: 'float' },
  36118. { name: 't', type: 'float' }
  36119. ]
  36120. } );
  36121. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  36122. 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 ] ) => {
  36123. const r = float( r_immutable ).toVar();
  36124. const t = float( t_immutable ).toVar();
  36125. const s = float( s_immutable ).toVar();
  36126. const v7 = float( v7_immutable ).toVar();
  36127. const v6 = float( v6_immutable ).toVar();
  36128. const v5 = float( v5_immutable ).toVar();
  36129. const v4 = float( v4_immutable ).toVar();
  36130. const v3 = float( v3_immutable ).toVar();
  36131. const v2 = float( v2_immutable ).toVar();
  36132. const v1 = float( v1_immutable ).toVar();
  36133. const v0 = float( v0_immutable ).toVar();
  36134. const s1 = float( sub( 1.0, s ) ).toVar();
  36135. const t1 = float( sub( 1.0, t ) ).toVar();
  36136. const r1 = float( sub( 1.0, r ) ).toVar();
  36137. 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 ) ) ) ) ) );
  36138. } ).setLayout( {
  36139. name: 'mx_trilerp_0',
  36140. type: 'float',
  36141. inputs: [
  36142. { name: 'v0', type: 'float' },
  36143. { name: 'v1', type: 'float' },
  36144. { name: 'v2', type: 'float' },
  36145. { name: 'v3', type: 'float' },
  36146. { name: 'v4', type: 'float' },
  36147. { name: 'v5', type: 'float' },
  36148. { name: 'v6', type: 'float' },
  36149. { name: 'v7', type: 'float' },
  36150. { name: 's', type: 'float' },
  36151. { name: 't', type: 'float' },
  36152. { name: 'r', type: 'float' }
  36153. ]
  36154. } );
  36155. 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 ] ) => {
  36156. const r = float( r_immutable ).toVar();
  36157. const t = float( t_immutable ).toVar();
  36158. const s = float( s_immutable ).toVar();
  36159. const v7 = vec3( v7_immutable ).toVar();
  36160. const v6 = vec3( v6_immutable ).toVar();
  36161. const v5 = vec3( v5_immutable ).toVar();
  36162. const v4 = vec3( v4_immutable ).toVar();
  36163. const v3 = vec3( v3_immutable ).toVar();
  36164. const v2 = vec3( v2_immutable ).toVar();
  36165. const v1 = vec3( v1_immutable ).toVar();
  36166. const v0 = vec3( v0_immutable ).toVar();
  36167. const s1 = float( sub( 1.0, s ) ).toVar();
  36168. const t1 = float( sub( 1.0, t ) ).toVar();
  36169. const r1 = float( sub( 1.0, r ) ).toVar();
  36170. 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 ) ) ) ) ) );
  36171. } ).setLayout( {
  36172. name: 'mx_trilerp_1',
  36173. type: 'vec3',
  36174. inputs: [
  36175. { name: 'v0', type: 'vec3' },
  36176. { name: 'v1', type: 'vec3' },
  36177. { name: 'v2', type: 'vec3' },
  36178. { name: 'v3', type: 'vec3' },
  36179. { name: 'v4', type: 'vec3' },
  36180. { name: 'v5', type: 'vec3' },
  36181. { name: 'v6', type: 'vec3' },
  36182. { name: 'v7', type: 'vec3' },
  36183. { name: 's', type: 'float' },
  36184. { name: 't', type: 'float' },
  36185. { name: 'r', type: 'float' }
  36186. ]
  36187. } );
  36188. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  36189. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  36190. const y = float( y_immutable ).toVar();
  36191. const x = float( x_immutable ).toVar();
  36192. const hash = uint( hash_immutable ).toVar();
  36193. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  36194. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  36195. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  36196. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  36197. } ).setLayout( {
  36198. name: 'mx_gradient_float_0',
  36199. type: 'float',
  36200. inputs: [
  36201. { name: 'hash', type: 'uint' },
  36202. { name: 'x', type: 'float' },
  36203. { name: 'y', type: 'float' }
  36204. ]
  36205. } );
  36206. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  36207. const z = float( z_immutable ).toVar();
  36208. const y = float( y_immutable ).toVar();
  36209. const x = float( x_immutable ).toVar();
  36210. const hash = uint( hash_immutable ).toVar();
  36211. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  36212. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  36213. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  36214. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  36215. } ).setLayout( {
  36216. name: 'mx_gradient_float_1',
  36217. type: 'float',
  36218. inputs: [
  36219. { name: 'hash', type: 'uint' },
  36220. { name: 'x', type: 'float' },
  36221. { name: 'y', type: 'float' },
  36222. { name: 'z', type: 'float' }
  36223. ]
  36224. } );
  36225. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  36226. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  36227. const y = float( y_immutable ).toVar();
  36228. const x = float( x_immutable ).toVar();
  36229. const hash = uvec3( hash_immutable ).toVar();
  36230. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  36231. } ).setLayout( {
  36232. name: 'mx_gradient_vec3_0',
  36233. type: 'vec3',
  36234. inputs: [
  36235. { name: 'hash', type: 'uvec3' },
  36236. { name: 'x', type: 'float' },
  36237. { name: 'y', type: 'float' }
  36238. ]
  36239. } );
  36240. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  36241. const z = float( z_immutable ).toVar();
  36242. const y = float( y_immutable ).toVar();
  36243. const x = float( x_immutable ).toVar();
  36244. const hash = uvec3( hash_immutable ).toVar();
  36245. 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 ) );
  36246. } ).setLayout( {
  36247. name: 'mx_gradient_vec3_1',
  36248. type: 'vec3',
  36249. inputs: [
  36250. { name: 'hash', type: 'uvec3' },
  36251. { name: 'x', type: 'float' },
  36252. { name: 'y', type: 'float' },
  36253. { name: 'z', type: 'float' }
  36254. ]
  36255. } );
  36256. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  36257. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  36258. const v = float( v_immutable ).toVar();
  36259. return mul( 0.6616, v );
  36260. } ).setLayout( {
  36261. name: 'mx_gradient_scale2d_0',
  36262. type: 'float',
  36263. inputs: [
  36264. { name: 'v', type: 'float' }
  36265. ]
  36266. } );
  36267. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  36268. const v = float( v_immutable ).toVar();
  36269. return mul( 0.9820, v );
  36270. } ).setLayout( {
  36271. name: 'mx_gradient_scale3d_0',
  36272. type: 'float',
  36273. inputs: [
  36274. { name: 'v', type: 'float' }
  36275. ]
  36276. } );
  36277. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  36278. const v = vec3( v_immutable ).toVar();
  36279. return mul( 0.6616, v );
  36280. } ).setLayout( {
  36281. name: 'mx_gradient_scale2d_1',
  36282. type: 'vec3',
  36283. inputs: [
  36284. { name: 'v', type: 'vec3' }
  36285. ]
  36286. } );
  36287. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  36288. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  36289. const v = vec3( v_immutable ).toVar();
  36290. return mul( 0.9820, v );
  36291. } ).setLayout( {
  36292. name: 'mx_gradient_scale3d_1',
  36293. type: 'vec3',
  36294. inputs: [
  36295. { name: 'v', type: 'vec3' }
  36296. ]
  36297. } );
  36298. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  36299. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  36300. const k = int( k_immutable ).toVar();
  36301. const x = uint( x_immutable ).toVar();
  36302. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  36303. } ).setLayout( {
  36304. name: 'mx_rotl32',
  36305. type: 'uint',
  36306. inputs: [
  36307. { name: 'x', type: 'uint' },
  36308. { name: 'k', type: 'int' }
  36309. ]
  36310. } );
  36311. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  36312. a.subAssign( c );
  36313. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  36314. c.addAssign( b );
  36315. b.subAssign( a );
  36316. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  36317. a.addAssign( c );
  36318. c.subAssign( b );
  36319. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  36320. b.addAssign( a );
  36321. a.subAssign( c );
  36322. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  36323. c.addAssign( b );
  36324. b.subAssign( a );
  36325. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  36326. a.addAssign( c );
  36327. c.subAssign( b );
  36328. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  36329. b.addAssign( a );
  36330. } );
  36331. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  36332. const c = uint( c_immutable ).toVar();
  36333. const b = uint( b_immutable ).toVar();
  36334. const a = uint( a_immutable ).toVar();
  36335. c.bitXorAssign( b );
  36336. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  36337. a.bitXorAssign( c );
  36338. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  36339. b.bitXorAssign( a );
  36340. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  36341. c.bitXorAssign( b );
  36342. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  36343. a.bitXorAssign( c );
  36344. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  36345. b.bitXorAssign( a );
  36346. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  36347. c.bitXorAssign( b );
  36348. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  36349. return c;
  36350. } ).setLayout( {
  36351. name: 'mx_bjfinal',
  36352. type: 'uint',
  36353. inputs: [
  36354. { name: 'a', type: 'uint' },
  36355. { name: 'b', type: 'uint' },
  36356. { name: 'c', type: 'uint' }
  36357. ]
  36358. } );
  36359. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  36360. const bits = uint( bits_immutable ).toVar();
  36361. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  36362. } ).setLayout( {
  36363. name: 'mx_bits_to_01',
  36364. type: 'float',
  36365. inputs: [
  36366. { name: 'bits', type: 'uint' }
  36367. ]
  36368. } );
  36369. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  36370. const t = float( t_immutable ).toVar();
  36371. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  36372. } ).setLayout( {
  36373. name: 'mx_fade',
  36374. type: 'float',
  36375. inputs: [
  36376. { name: 't', type: 'float' }
  36377. ]
  36378. } );
  36379. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  36380. const x = int( x_immutable ).toVar();
  36381. const len = uint( uint( 1 ) ).toVar();
  36382. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  36383. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  36384. } ).setLayout( {
  36385. name: 'mx_hash_int_0',
  36386. type: 'uint',
  36387. inputs: [
  36388. { name: 'x', type: 'int' }
  36389. ]
  36390. } );
  36391. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  36392. const y = int( y_immutable ).toVar();
  36393. const x = int( x_immutable ).toVar();
  36394. const len = uint( uint( 2 ) ).toVar();
  36395. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  36396. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  36397. a.addAssign( uint( x ) );
  36398. b.addAssign( uint( y ) );
  36399. return mx_bjfinal( a, b, c );
  36400. } ).setLayout( {
  36401. name: 'mx_hash_int_1',
  36402. type: 'uint',
  36403. inputs: [
  36404. { name: 'x', type: 'int' },
  36405. { name: 'y', type: 'int' }
  36406. ]
  36407. } );
  36408. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  36409. const z = int( z_immutable ).toVar();
  36410. const y = int( y_immutable ).toVar();
  36411. const x = int( x_immutable ).toVar();
  36412. const len = uint( uint( 3 ) ).toVar();
  36413. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  36414. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  36415. a.addAssign( uint( x ) );
  36416. b.addAssign( uint( y ) );
  36417. c.addAssign( uint( z ) );
  36418. return mx_bjfinal( a, b, c );
  36419. } ).setLayout( {
  36420. name: 'mx_hash_int_2',
  36421. type: 'uint',
  36422. inputs: [
  36423. { name: 'x', type: 'int' },
  36424. { name: 'y', type: 'int' },
  36425. { name: 'z', type: 'int' }
  36426. ]
  36427. } );
  36428. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  36429. const xx = int( xx_immutable ).toVar();
  36430. const z = int( z_immutable ).toVar();
  36431. const y = int( y_immutable ).toVar();
  36432. const x = int( x_immutable ).toVar();
  36433. const len = uint( uint( 4 ) ).toVar();
  36434. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  36435. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  36436. a.addAssign( uint( x ) );
  36437. b.addAssign( uint( y ) );
  36438. c.addAssign( uint( z ) );
  36439. mx_bjmix( a, b, c );
  36440. a.addAssign( uint( xx ) );
  36441. return mx_bjfinal( a, b, c );
  36442. } ).setLayout( {
  36443. name: 'mx_hash_int_3',
  36444. type: 'uint',
  36445. inputs: [
  36446. { name: 'x', type: 'int' },
  36447. { name: 'y', type: 'int' },
  36448. { name: 'z', type: 'int' },
  36449. { name: 'xx', type: 'int' }
  36450. ]
  36451. } );
  36452. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  36453. const yy = int( yy_immutable ).toVar();
  36454. const xx = int( xx_immutable ).toVar();
  36455. const z = int( z_immutable ).toVar();
  36456. const y = int( y_immutable ).toVar();
  36457. const x = int( x_immutable ).toVar();
  36458. const len = uint( uint( 5 ) ).toVar();
  36459. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  36460. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  36461. a.addAssign( uint( x ) );
  36462. b.addAssign( uint( y ) );
  36463. c.addAssign( uint( z ) );
  36464. mx_bjmix( a, b, c );
  36465. a.addAssign( uint( xx ) );
  36466. b.addAssign( uint( yy ) );
  36467. return mx_bjfinal( a, b, c );
  36468. } ).setLayout( {
  36469. name: 'mx_hash_int_4',
  36470. type: 'uint',
  36471. inputs: [
  36472. { name: 'x', type: 'int' },
  36473. { name: 'y', type: 'int' },
  36474. { name: 'z', type: 'int' },
  36475. { name: 'xx', type: 'int' },
  36476. { name: 'yy', type: 'int' }
  36477. ]
  36478. } );
  36479. 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 ] );
  36480. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  36481. const y = int( y_immutable ).toVar();
  36482. const x = int( x_immutable ).toVar();
  36483. const h = uint( mx_hash_int( x, y ) ).toVar();
  36484. const result = uvec3().toVar();
  36485. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  36486. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  36487. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  36488. return result;
  36489. } ).setLayout( {
  36490. name: 'mx_hash_vec3_0',
  36491. type: 'uvec3',
  36492. inputs: [
  36493. { name: 'x', type: 'int' },
  36494. { name: 'y', type: 'int' }
  36495. ]
  36496. } );
  36497. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  36498. const z = int( z_immutable ).toVar();
  36499. const y = int( y_immutable ).toVar();
  36500. const x = int( x_immutable ).toVar();
  36501. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  36502. const result = uvec3().toVar();
  36503. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  36504. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  36505. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  36506. return result;
  36507. } ).setLayout( {
  36508. name: 'mx_hash_vec3_1',
  36509. type: 'uvec3',
  36510. inputs: [
  36511. { name: 'x', type: 'int' },
  36512. { name: 'y', type: 'int' },
  36513. { name: 'z', type: 'int' }
  36514. ]
  36515. } );
  36516. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  36517. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36518. const p = vec2( p_immutable ).toVar();
  36519. const X = int().toVar(), Y = int().toVar();
  36520. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  36521. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  36522. const u = float( mx_fade( fx ) ).toVar();
  36523. const v = float( mx_fade( fy ) ).toVar();
  36524. 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();
  36525. return mx_gradient_scale2d( result );
  36526. } ).setLayout( {
  36527. name: 'mx_perlin_noise_float_0',
  36528. type: 'float',
  36529. inputs: [
  36530. { name: 'p', type: 'vec2' }
  36531. ]
  36532. } );
  36533. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36534. const p = vec3( p_immutable ).toVar();
  36535. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  36536. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  36537. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  36538. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  36539. const u = float( mx_fade( fx ) ).toVar();
  36540. const v = float( mx_fade( fy ) ).toVar();
  36541. const w = float( mx_fade( fz ) ).toVar();
  36542. 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();
  36543. return mx_gradient_scale3d( result );
  36544. } ).setLayout( {
  36545. name: 'mx_perlin_noise_float_1',
  36546. type: 'float',
  36547. inputs: [
  36548. { name: 'p', type: 'vec3' }
  36549. ]
  36550. } );
  36551. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  36552. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36553. const p = vec2( p_immutable ).toVar();
  36554. const X = int().toVar(), Y = int().toVar();
  36555. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  36556. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  36557. const u = float( mx_fade( fx ) ).toVar();
  36558. const v = float( mx_fade( fy ) ).toVar();
  36559. 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();
  36560. return mx_gradient_scale2d( result );
  36561. } ).setLayout( {
  36562. name: 'mx_perlin_noise_vec3_0',
  36563. type: 'vec3',
  36564. inputs: [
  36565. { name: 'p', type: 'vec2' }
  36566. ]
  36567. } );
  36568. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36569. const p = vec3( p_immutable ).toVar();
  36570. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  36571. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  36572. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  36573. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  36574. const u = float( mx_fade( fx ) ).toVar();
  36575. const v = float( mx_fade( fy ) ).toVar();
  36576. const w = float( mx_fade( fz ) ).toVar();
  36577. 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();
  36578. return mx_gradient_scale3d( result );
  36579. } ).setLayout( {
  36580. name: 'mx_perlin_noise_vec3_1',
  36581. type: 'vec3',
  36582. inputs: [
  36583. { name: 'p', type: 'vec3' }
  36584. ]
  36585. } );
  36586. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  36587. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36588. const p = float( p_immutable ).toVar();
  36589. const ix = int( mx_floor( p ) ).toVar();
  36590. return mx_bits_to_01( mx_hash_int( ix ) );
  36591. } ).setLayout( {
  36592. name: 'mx_cell_noise_float_0',
  36593. type: 'float',
  36594. inputs: [
  36595. { name: 'p', type: 'float' }
  36596. ]
  36597. } );
  36598. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36599. const p = vec2( p_immutable ).toVar();
  36600. const ix = int( mx_floor( p.x ) ).toVar();
  36601. const iy = int( mx_floor( p.y ) ).toVar();
  36602. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  36603. } ).setLayout( {
  36604. name: 'mx_cell_noise_float_1',
  36605. type: 'float',
  36606. inputs: [
  36607. { name: 'p', type: 'vec2' }
  36608. ]
  36609. } );
  36610. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36611. const p = vec3( p_immutable ).toVar();
  36612. const ix = int( mx_floor( p.x ) ).toVar();
  36613. const iy = int( mx_floor( p.y ) ).toVar();
  36614. const iz = int( mx_floor( p.z ) ).toVar();
  36615. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  36616. } ).setLayout( {
  36617. name: 'mx_cell_noise_float_2',
  36618. type: 'float',
  36619. inputs: [
  36620. { name: 'p', type: 'vec3' }
  36621. ]
  36622. } );
  36623. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36624. const p = vec4( p_immutable ).toVar();
  36625. const ix = int( mx_floor( p.x ) ).toVar();
  36626. const iy = int( mx_floor( p.y ) ).toVar();
  36627. const iz = int( mx_floor( p.z ) ).toVar();
  36628. const iw = int( mx_floor( p.w ) ).toVar();
  36629. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  36630. } ).setLayout( {
  36631. name: 'mx_cell_noise_float_3',
  36632. type: 'float',
  36633. inputs: [
  36634. { name: 'p', type: 'vec4' }
  36635. ]
  36636. } );
  36637. 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 ] );
  36638. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36639. const p = float( p_immutable ).toVar();
  36640. const ix = int( mx_floor( p ) ).toVar();
  36641. 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 ) ) ) );
  36642. } ).setLayout( {
  36643. name: 'mx_cell_noise_vec3_0',
  36644. type: 'vec3',
  36645. inputs: [
  36646. { name: 'p', type: 'float' }
  36647. ]
  36648. } );
  36649. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36650. const p = vec2( p_immutable ).toVar();
  36651. const ix = int( mx_floor( p.x ) ).toVar();
  36652. const iy = int( mx_floor( p.y ) ).toVar();
  36653. 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 ) ) ) );
  36654. } ).setLayout( {
  36655. name: 'mx_cell_noise_vec3_1',
  36656. type: 'vec3',
  36657. inputs: [
  36658. { name: 'p', type: 'vec2' }
  36659. ]
  36660. } );
  36661. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36662. const p = vec3( p_immutable ).toVar();
  36663. const ix = int( mx_floor( p.x ) ).toVar();
  36664. const iy = int( mx_floor( p.y ) ).toVar();
  36665. const iz = int( mx_floor( p.z ) ).toVar();
  36666. 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 ) ) ) );
  36667. } ).setLayout( {
  36668. name: 'mx_cell_noise_vec3_2',
  36669. type: 'vec3',
  36670. inputs: [
  36671. { name: 'p', type: 'vec3' }
  36672. ]
  36673. } );
  36674. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  36675. const p = vec4( p_immutable ).toVar();
  36676. const ix = int( mx_floor( p.x ) ).toVar();
  36677. const iy = int( mx_floor( p.y ) ).toVar();
  36678. const iz = int( mx_floor( p.z ) ).toVar();
  36679. const iw = int( mx_floor( p.w ) ).toVar();
  36680. 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 ) ) ) );
  36681. } ).setLayout( {
  36682. name: 'mx_cell_noise_vec3_3',
  36683. type: 'vec3',
  36684. inputs: [
  36685. { name: 'p', type: 'vec4' }
  36686. ]
  36687. } );
  36688. 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 ] );
  36689. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  36690. const diminish = float( diminish_immutable ).toVar();
  36691. const lacunarity = float( lacunarity_immutable ).toVar();
  36692. const octaves = int( octaves_immutable ).toVar();
  36693. const p = vec3( p_immutable ).toVar();
  36694. const result = float( 0.0 ).toVar();
  36695. const amplitude = float( 1.0 ).toVar();
  36696. Loop( octaves, () => {
  36697. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  36698. amplitude.mulAssign( diminish );
  36699. p.mulAssign( lacunarity );
  36700. } );
  36701. return result;
  36702. } ).setLayout( {
  36703. name: 'mx_fractal_noise_float',
  36704. type: 'float',
  36705. inputs: [
  36706. { name: 'p', type: 'vec3' },
  36707. { name: 'octaves', type: 'int' },
  36708. { name: 'lacunarity', type: 'float' },
  36709. { name: 'diminish', type: 'float' }
  36710. ]
  36711. } );
  36712. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  36713. const diminish = float( diminish_immutable ).toVar();
  36714. const lacunarity = float( lacunarity_immutable ).toVar();
  36715. const octaves = int( octaves_immutable ).toVar();
  36716. const p = vec3( p_immutable ).toVar();
  36717. const result = vec3( 0.0 ).toVar();
  36718. const amplitude = float( 1.0 ).toVar();
  36719. Loop( octaves, () => {
  36720. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  36721. amplitude.mulAssign( diminish );
  36722. p.mulAssign( lacunarity );
  36723. } );
  36724. return result;
  36725. } ).setLayout( {
  36726. name: 'mx_fractal_noise_vec3',
  36727. type: 'vec3',
  36728. inputs: [
  36729. { name: 'p', type: 'vec3' },
  36730. { name: 'octaves', type: 'int' },
  36731. { name: 'lacunarity', type: 'float' },
  36732. { name: 'diminish', type: 'float' }
  36733. ]
  36734. } );
  36735. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  36736. const diminish = float( diminish_immutable ).toVar();
  36737. const lacunarity = float( lacunarity_immutable ).toVar();
  36738. const octaves = int( octaves_immutable ).toVar();
  36739. const p = vec3( p_immutable ).toVar();
  36740. 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 ) );
  36741. } ).setLayout( {
  36742. name: 'mx_fractal_noise_vec2',
  36743. type: 'vec2',
  36744. inputs: [
  36745. { name: 'p', type: 'vec3' },
  36746. { name: 'octaves', type: 'int' },
  36747. { name: 'lacunarity', type: 'float' },
  36748. { name: 'diminish', type: 'float' }
  36749. ]
  36750. } );
  36751. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  36752. const diminish = float( diminish_immutable ).toVar();
  36753. const lacunarity = float( lacunarity_immutable ).toVar();
  36754. const octaves = int( octaves_immutable ).toVar();
  36755. const p = vec3( p_immutable ).toVar();
  36756. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  36757. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  36758. return vec4( c, f );
  36759. } ).setLayout( {
  36760. name: 'mx_fractal_noise_vec4',
  36761. type: 'vec4',
  36762. inputs: [
  36763. { name: 'p', type: 'vec3' },
  36764. { name: 'octaves', type: 'int' },
  36765. { name: 'lacunarity', type: 'float' },
  36766. { name: 'diminish', type: 'float' }
  36767. ]
  36768. } );
  36769. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  36770. const metric = int( metric_immutable ).toVar();
  36771. const jitter = float( jitter_immutable ).toVar();
  36772. const yoff = int( yoff_immutable ).toVar();
  36773. const xoff = int( xoff_immutable ).toVar();
  36774. const y = int( y_immutable ).toVar();
  36775. const x = int( x_immutable ).toVar();
  36776. const p = vec2( p_immutable ).toVar();
  36777. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  36778. const off = vec2( tmp.x, tmp.y ).toVar();
  36779. off.subAssign( 0.5 );
  36780. off.mulAssign( jitter );
  36781. off.addAssign( 0.5 );
  36782. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  36783. const diff = vec2( cellpos.sub( p ) ).toVar();
  36784. If( metric.equal( int( 2 ) ), () => {
  36785. return abs( diff.x ).add( abs( diff.y ) );
  36786. } );
  36787. If( metric.equal( int( 3 ) ), () => {
  36788. return max$1( abs( diff.x ), abs( diff.y ) );
  36789. } );
  36790. return dot( diff, diff );
  36791. } ).setLayout( {
  36792. name: 'mx_worley_distance_0',
  36793. type: 'float',
  36794. inputs: [
  36795. { name: 'p', type: 'vec2' },
  36796. { name: 'x', type: 'int' },
  36797. { name: 'y', type: 'int' },
  36798. { name: 'xoff', type: 'int' },
  36799. { name: 'yoff', type: 'int' },
  36800. { name: 'jitter', type: 'float' },
  36801. { name: 'metric', type: 'int' }
  36802. ]
  36803. } );
  36804. 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 ] ) => {
  36805. const metric = int( metric_immutable ).toVar();
  36806. const jitter = float( jitter_immutable ).toVar();
  36807. const zoff = int( zoff_immutable ).toVar();
  36808. const yoff = int( yoff_immutable ).toVar();
  36809. const xoff = int( xoff_immutable ).toVar();
  36810. const z = int( z_immutable ).toVar();
  36811. const y = int( y_immutable ).toVar();
  36812. const x = int( x_immutable ).toVar();
  36813. const p = vec3( p_immutable ).toVar();
  36814. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  36815. off.subAssign( 0.5 );
  36816. off.mulAssign( jitter );
  36817. off.addAssign( 0.5 );
  36818. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  36819. const diff = vec3( cellpos.sub( p ) ).toVar();
  36820. If( metric.equal( int( 2 ) ), () => {
  36821. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  36822. } );
  36823. If( metric.equal( int( 3 ) ), () => {
  36824. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  36825. } );
  36826. return dot( diff, diff );
  36827. } ).setLayout( {
  36828. name: 'mx_worley_distance_1',
  36829. type: 'float',
  36830. inputs: [
  36831. { name: 'p', type: 'vec3' },
  36832. { name: 'x', type: 'int' },
  36833. { name: 'y', type: 'int' },
  36834. { name: 'z', type: 'int' },
  36835. { name: 'xoff', type: 'int' },
  36836. { name: 'yoff', type: 'int' },
  36837. { name: 'zoff', type: 'int' },
  36838. { name: 'jitter', type: 'float' },
  36839. { name: 'metric', type: 'int' }
  36840. ]
  36841. } );
  36842. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  36843. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  36844. const metric = int( metric_immutable ).toVar();
  36845. const jitter = float( jitter_immutable ).toVar();
  36846. const p = vec2( p_immutable ).toVar();
  36847. const X = int().toVar(), Y = int().toVar();
  36848. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  36849. const sqdist = float( 1e6 ).toVar();
  36850. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  36851. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  36852. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  36853. sqdist.assign( min$1( sqdist, dist ) );
  36854. } );
  36855. } );
  36856. If( metric.equal( int( 0 ) ), () => {
  36857. sqdist.assign( sqrt( sqdist ) );
  36858. } );
  36859. return sqdist;
  36860. } ).setLayout( {
  36861. name: 'mx_worley_noise_float_0',
  36862. type: 'float',
  36863. inputs: [
  36864. { name: 'p', type: 'vec2' },
  36865. { name: 'jitter', type: 'float' },
  36866. { name: 'metric', type: 'int' }
  36867. ]
  36868. } );
  36869. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  36870. const metric = int( metric_immutable ).toVar();
  36871. const jitter = float( jitter_immutable ).toVar();
  36872. const p = vec2( p_immutable ).toVar();
  36873. const X = int().toVar(), Y = int().toVar();
  36874. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  36875. const sqdist = vec2( 1e6, 1e6 ).toVar();
  36876. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  36877. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  36878. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  36879. If( dist.lessThan( sqdist.x ), () => {
  36880. sqdist.y.assign( sqdist.x );
  36881. sqdist.x.assign( dist );
  36882. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  36883. sqdist.y.assign( dist );
  36884. } );
  36885. } );
  36886. } );
  36887. If( metric.equal( int( 0 ) ), () => {
  36888. sqdist.assign( sqrt( sqdist ) );
  36889. } );
  36890. return sqdist;
  36891. } ).setLayout( {
  36892. name: 'mx_worley_noise_vec2_0',
  36893. type: 'vec2',
  36894. inputs: [
  36895. { name: 'p', type: 'vec2' },
  36896. { name: 'jitter', type: 'float' },
  36897. { name: 'metric', type: 'int' }
  36898. ]
  36899. } );
  36900. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  36901. const metric = int( metric_immutable ).toVar();
  36902. const jitter = float( jitter_immutable ).toVar();
  36903. const p = vec2( p_immutable ).toVar();
  36904. const X = int().toVar(), Y = int().toVar();
  36905. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  36906. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  36907. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  36908. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  36909. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  36910. If( dist.lessThan( sqdist.x ), () => {
  36911. sqdist.z.assign( sqdist.y );
  36912. sqdist.y.assign( sqdist.x );
  36913. sqdist.x.assign( dist );
  36914. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  36915. sqdist.z.assign( sqdist.y );
  36916. sqdist.y.assign( dist );
  36917. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  36918. sqdist.z.assign( dist );
  36919. } );
  36920. } );
  36921. } );
  36922. If( metric.equal( int( 0 ) ), () => {
  36923. sqdist.assign( sqrt( sqdist ) );
  36924. } );
  36925. return sqdist;
  36926. } ).setLayout( {
  36927. name: 'mx_worley_noise_vec3_0',
  36928. type: 'vec3',
  36929. inputs: [
  36930. { name: 'p', type: 'vec2' },
  36931. { name: 'jitter', type: 'float' },
  36932. { name: 'metric', type: 'int' }
  36933. ]
  36934. } );
  36935. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  36936. const metric = int( metric_immutable ).toVar();
  36937. const jitter = float( jitter_immutable ).toVar();
  36938. const p = vec3( p_immutable ).toVar();
  36939. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  36940. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  36941. const sqdist = float( 1e6 ).toVar();
  36942. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  36943. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  36944. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  36945. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  36946. sqdist.assign( min$1( sqdist, dist ) );
  36947. } );
  36948. } );
  36949. } );
  36950. If( metric.equal( int( 0 ) ), () => {
  36951. sqdist.assign( sqrt( sqdist ) );
  36952. } );
  36953. return sqdist;
  36954. } ).setLayout( {
  36955. name: 'mx_worley_noise_float_1',
  36956. type: 'float',
  36957. inputs: [
  36958. { name: 'p', type: 'vec3' },
  36959. { name: 'jitter', type: 'float' },
  36960. { name: 'metric', type: 'int' }
  36961. ]
  36962. } );
  36963. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  36964. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  36965. const metric = int( metric_immutable ).toVar();
  36966. const jitter = float( jitter_immutable ).toVar();
  36967. const p = vec3( p_immutable ).toVar();
  36968. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  36969. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  36970. const sqdist = vec2( 1e6, 1e6 ).toVar();
  36971. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  36972. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  36973. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  36974. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  36975. If( dist.lessThan( sqdist.x ), () => {
  36976. sqdist.y.assign( sqdist.x );
  36977. sqdist.x.assign( dist );
  36978. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  36979. sqdist.y.assign( dist );
  36980. } );
  36981. } );
  36982. } );
  36983. } );
  36984. If( metric.equal( int( 0 ) ), () => {
  36985. sqdist.assign( sqrt( sqdist ) );
  36986. } );
  36987. return sqdist;
  36988. } ).setLayout( {
  36989. name: 'mx_worley_noise_vec2_1',
  36990. type: 'vec2',
  36991. inputs: [
  36992. { name: 'p', type: 'vec3' },
  36993. { name: 'jitter', type: 'float' },
  36994. { name: 'metric', type: 'int' }
  36995. ]
  36996. } );
  36997. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  36998. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  36999. const metric = int( metric_immutable ).toVar();
  37000. const jitter = float( jitter_immutable ).toVar();
  37001. const p = vec3( p_immutable ).toVar();
  37002. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  37003. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  37004. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  37005. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  37006. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  37007. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  37008. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  37009. If( dist.lessThan( sqdist.x ), () => {
  37010. sqdist.z.assign( sqdist.y );
  37011. sqdist.y.assign( sqdist.x );
  37012. sqdist.x.assign( dist );
  37013. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  37014. sqdist.z.assign( sqdist.y );
  37015. sqdist.y.assign( dist );
  37016. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  37017. sqdist.z.assign( dist );
  37018. } );
  37019. } );
  37020. } );
  37021. } );
  37022. If( metric.equal( int( 0 ) ), () => {
  37023. sqdist.assign( sqrt( sqdist ) );
  37024. } );
  37025. return sqdist;
  37026. } ).setLayout( {
  37027. name: 'mx_worley_noise_vec3_1',
  37028. type: 'vec3',
  37029. inputs: [
  37030. { name: 'p', type: 'vec3' },
  37031. { name: 'jitter', type: 'float' },
  37032. { name: 'metric', type: 'int' }
  37033. ]
  37034. } );
  37035. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  37036. // Three.js Transpiler
  37037. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  37038. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  37039. const s = hsv.y;
  37040. const v = hsv.z;
  37041. const result = vec3().toVar();
  37042. If( s.lessThan( 0.0001 ), () => {
  37043. result.assign( vec3( v, v, v ) );
  37044. } ).Else( () => {
  37045. let h = hsv.x;
  37046. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  37047. const hi = int( trunc( h ) );
  37048. const f = h.sub( float( hi ) );
  37049. const p = v.mul( s.oneMinus() );
  37050. const q = v.mul( s.mul( f ).oneMinus() );
  37051. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  37052. If( hi.equal( int( 0 ) ), () => {
  37053. result.assign( vec3( v, t, p ) );
  37054. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  37055. result.assign( vec3( q, v, p ) );
  37056. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  37057. result.assign( vec3( p, v, t ) );
  37058. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  37059. result.assign( vec3( p, q, v ) );
  37060. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  37061. result.assign( vec3( t, p, v ) );
  37062. } ).Else( () => {
  37063. result.assign( vec3( v, p, q ) );
  37064. } );
  37065. } );
  37066. return result;
  37067. } ).setLayout( {
  37068. name: 'mx_hsvtorgb',
  37069. type: 'vec3',
  37070. inputs: [
  37071. { name: 'hsv', type: 'vec3' }
  37072. ]
  37073. } );
  37074. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  37075. const c = vec3( c_immutable ).toVar();
  37076. const r = float( c.x ).toVar();
  37077. const g = float( c.y ).toVar();
  37078. const b = float( c.z ).toVar();
  37079. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  37080. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  37081. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  37082. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  37083. v.assign( maxcomp );
  37084. If( maxcomp.greaterThan( 0.0 ), () => {
  37085. s.assign( delta.div( maxcomp ) );
  37086. } ).Else( () => {
  37087. s.assign( 0.0 );
  37088. } );
  37089. If( s.lessThanEqual( 0.0 ), () => {
  37090. h.assign( 0.0 );
  37091. } ).Else( () => {
  37092. If( r.greaterThanEqual( maxcomp ), () => {
  37093. h.assign( g.sub( b ).div( delta ) );
  37094. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  37095. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  37096. } ).Else( () => {
  37097. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  37098. } );
  37099. h.mulAssign( 1.0 / 6.0 );
  37100. If( h.lessThan( 0.0 ), () => {
  37101. h.addAssign( 1.0 );
  37102. } );
  37103. } );
  37104. return vec3( h, s, v );
  37105. } ).setLayout( {
  37106. name: 'mx_rgbtohsv',
  37107. type: 'vec3',
  37108. inputs: [
  37109. { name: 'c', type: 'vec3' }
  37110. ]
  37111. } );
  37112. // Three.js Transpiler
  37113. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  37114. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  37115. const color = vec3( color_immutable ).toVar();
  37116. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  37117. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  37118. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  37119. return mix( linSeg, powSeg, isAbove );
  37120. } ).setLayout( {
  37121. name: 'mx_srgb_texture_to_lin_rec709',
  37122. type: 'vec3',
  37123. inputs: [
  37124. { name: 'color', type: 'vec3' }
  37125. ]
  37126. } );
  37127. const mx_aastep = ( threshold, value ) => {
  37128. threshold = float( threshold );
  37129. value = float( value );
  37130. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  37131. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  37132. };
  37133. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  37134. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  37135. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  37136. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  37137. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  37138. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  37139. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  37140. const mx_safepower = ( in1, in2 = 1 ) => {
  37141. in1 = float( in1 );
  37142. return in1.abs().pow( in2 ).mul( in1.sign() );
  37143. };
  37144. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  37145. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  37146. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  37147. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  37148. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  37149. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  37150. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  37151. return noise_vec4.mul( amplitude ).add( pivot );
  37152. };
  37153. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  37154. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  37155. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  37156. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  37157. 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 );
  37158. 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 );
  37159. 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 );
  37160. 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 );
  37161. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  37162. // normal is assumed to have unit length
  37163. const x = normal.x, y = normal.y, z = normal.z;
  37164. // band 0
  37165. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  37166. // band 1
  37167. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  37168. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  37169. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  37170. // band 2
  37171. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  37172. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  37173. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  37174. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  37175. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  37176. return result;
  37177. } );
  37178. class PointLightNode extends AnalyticLightNode {
  37179. static get type() {
  37180. return 'PointLightNode';
  37181. }
  37182. constructor( light = null ) {
  37183. super( light );
  37184. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  37185. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  37186. }
  37187. update( frame ) {
  37188. const { light } = this;
  37189. super.update( frame );
  37190. this.cutoffDistanceNode.value = light.distance;
  37191. this.decayExponentNode.value = light.decay;
  37192. }
  37193. setup( builder ) {
  37194. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  37195. const lightingModel = builder.context.lightingModel;
  37196. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  37197. const lightDirection = lVector.normalize();
  37198. const lightDistance = lVector.length();
  37199. const lightAttenuation = getDistanceAttenuation( {
  37200. lightDistance,
  37201. cutoffDistance: cutoffDistanceNode,
  37202. decayExponent: decayExponentNode
  37203. } );
  37204. const lightColor = colorNode.mul( lightAttenuation );
  37205. const reflectedLight = builder.context.reflectedLight;
  37206. lightingModel.direct( {
  37207. lightDirection,
  37208. lightColor,
  37209. reflectedLight
  37210. }, builder.stack, builder );
  37211. }
  37212. }
  37213. class DirectionalLightNode extends AnalyticLightNode {
  37214. static get type() {
  37215. return 'DirectionalLightNode';
  37216. }
  37217. constructor( light = null ) {
  37218. super( light );
  37219. }
  37220. setup( builder ) {
  37221. super.setup( builder );
  37222. const lightingModel = builder.context.lightingModel;
  37223. const lightColor = this.colorNode;
  37224. const lightDirection = lightTargetDirection( this.light );
  37225. const reflectedLight = builder.context.reflectedLight;
  37226. lightingModel.direct( {
  37227. lightDirection,
  37228. lightColor,
  37229. reflectedLight
  37230. }, builder.stack, builder );
  37231. }
  37232. }
  37233. const _matrix41 = /*@__PURE__*/ new Matrix4();
  37234. const _matrix42 = /*@__PURE__*/ new Matrix4();
  37235. let ltcLib = null;
  37236. class RectAreaLightNode extends AnalyticLightNode {
  37237. static get type() {
  37238. return 'RectAreaLightNode';
  37239. }
  37240. constructor( light = null ) {
  37241. super( light );
  37242. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  37243. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  37244. }
  37245. update( frame ) {
  37246. super.update( frame );
  37247. const { light } = this;
  37248. const viewMatrix = frame.camera.matrixWorldInverse;
  37249. _matrix42.identity();
  37250. _matrix41.copy( light.matrixWorld );
  37251. _matrix41.premultiply( viewMatrix );
  37252. _matrix42.extractRotation( _matrix41 );
  37253. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  37254. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  37255. this.halfWidth.value.applyMatrix4( _matrix42 );
  37256. this.halfHeight.value.applyMatrix4( _matrix42 );
  37257. }
  37258. setup( builder ) {
  37259. super.setup( builder );
  37260. let ltc_1, ltc_2;
  37261. if ( builder.isAvailable( 'float32Filterable' ) ) {
  37262. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  37263. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  37264. } else {
  37265. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  37266. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  37267. }
  37268. const { colorNode, light } = this;
  37269. const lightingModel = builder.context.lightingModel;
  37270. const lightPosition = lightViewPosition( light );
  37271. const reflectedLight = builder.context.reflectedLight;
  37272. lightingModel.directRectArea( {
  37273. lightColor: colorNode,
  37274. lightPosition,
  37275. halfWidth: this.halfWidth,
  37276. halfHeight: this.halfHeight,
  37277. reflectedLight,
  37278. ltc_1,
  37279. ltc_2
  37280. }, builder.stack, builder );
  37281. }
  37282. static setLTC( ltc ) {
  37283. ltcLib = ltc;
  37284. }
  37285. }
  37286. class SpotLightNode extends AnalyticLightNode {
  37287. static get type() {
  37288. return 'SpotLightNode';
  37289. }
  37290. constructor( light = null ) {
  37291. super( light );
  37292. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  37293. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  37294. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  37295. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  37296. }
  37297. update( frame ) {
  37298. super.update( frame );
  37299. const { light } = this;
  37300. this.coneCosNode.value = Math.cos( light.angle );
  37301. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  37302. this.cutoffDistanceNode.value = light.distance;
  37303. this.decayExponentNode.value = light.decay;
  37304. }
  37305. getSpotAttenuation( angleCosine ) {
  37306. const { coneCosNode, penumbraCosNode } = this;
  37307. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  37308. }
  37309. setup( builder ) {
  37310. super.setup( builder );
  37311. const lightingModel = builder.context.lightingModel;
  37312. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  37313. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  37314. const lightDirection = lVector.normalize();
  37315. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  37316. const spotAttenuation = this.getSpotAttenuation( angleCos );
  37317. const lightDistance = lVector.length();
  37318. const lightAttenuation = getDistanceAttenuation( {
  37319. lightDistance,
  37320. cutoffDistance: cutoffDistanceNode,
  37321. decayExponent: decayExponentNode
  37322. } );
  37323. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  37324. const reflectedLight = builder.context.reflectedLight;
  37325. lightingModel.direct( {
  37326. lightDirection,
  37327. lightColor,
  37328. reflectedLight
  37329. }, builder.stack, builder );
  37330. }
  37331. }
  37332. class IESSpotLightNode extends SpotLightNode {
  37333. static get type() {
  37334. return 'IESSpotLightNode';
  37335. }
  37336. getSpotAttenuation( angleCosine ) {
  37337. const iesMap = this.light.iesMap;
  37338. let spotAttenuation = null;
  37339. if ( iesMap && iesMap.isTexture === true ) {
  37340. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  37341. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  37342. } else {
  37343. spotAttenuation = super.getSpotAttenuation( angleCosine );
  37344. }
  37345. return spotAttenuation;
  37346. }
  37347. }
  37348. class AmbientLightNode extends AnalyticLightNode {
  37349. static get type() {
  37350. return 'AmbientLightNode';
  37351. }
  37352. constructor( light = null ) {
  37353. super( light );
  37354. }
  37355. setup( { context } ) {
  37356. context.irradiance.addAssign( this.colorNode );
  37357. }
  37358. }
  37359. class HemisphereLightNode extends AnalyticLightNode {
  37360. static get type() {
  37361. return 'HemisphereLightNode';
  37362. }
  37363. constructor( light = null ) {
  37364. super( light );
  37365. this.lightPositionNode = lightPosition( light );
  37366. this.lightDirectionNode = this.lightPositionNode.normalize();
  37367. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  37368. }
  37369. update( frame ) {
  37370. const { light } = this;
  37371. super.update( frame );
  37372. this.lightPositionNode.object3d = light;
  37373. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  37374. }
  37375. setup( builder ) {
  37376. const { colorNode, groundColorNode, lightDirectionNode } = this;
  37377. const dotNL = normalView.dot( lightDirectionNode );
  37378. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  37379. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  37380. builder.context.irradiance.addAssign( irradiance );
  37381. }
  37382. }
  37383. class LightProbeNode extends AnalyticLightNode {
  37384. static get type() {
  37385. return 'LightProbeNode';
  37386. }
  37387. constructor( light = null ) {
  37388. super( light );
  37389. const array = [];
  37390. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  37391. this.lightProbe = uniformArray( array );
  37392. }
  37393. update( frame ) {
  37394. const { light } = this;
  37395. super.update( frame );
  37396. //
  37397. for ( let i = 0; i < 9; i ++ ) {
  37398. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  37399. }
  37400. }
  37401. setup( builder ) {
  37402. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  37403. builder.context.irradiance.addAssign( irradiance );
  37404. }
  37405. }
  37406. class NodeParser {
  37407. parseFunction( /*source*/ ) {
  37408. console.warn( 'Abstract function.' );
  37409. }
  37410. }
  37411. class NodeFunction {
  37412. constructor( type, inputs, name = '', precision = '' ) {
  37413. this.type = type;
  37414. this.inputs = inputs;
  37415. this.name = name;
  37416. this.precision = precision;
  37417. }
  37418. getCode( /*name = this.name*/ ) {
  37419. console.warn( 'Abstract function.' );
  37420. }
  37421. }
  37422. NodeFunction.isNodeFunction = true;
  37423. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  37424. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  37425. const pragmaMain = '#pragma main';
  37426. const parse$1 = ( source ) => {
  37427. source = source.trim();
  37428. const pragmaMainIndex = source.indexOf( pragmaMain );
  37429. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  37430. const declaration = mainCode.match( declarationRegexp$1 );
  37431. if ( declaration !== null && declaration.length === 5 ) {
  37432. // tokenizer
  37433. const inputsCode = declaration[ 4 ];
  37434. const propsMatches = [];
  37435. let nameMatch = null;
  37436. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  37437. propsMatches.push( nameMatch );
  37438. }
  37439. // parser
  37440. const inputs = [];
  37441. let i = 0;
  37442. while ( i < propsMatches.length ) {
  37443. const isConst = propsMatches[ i ][ 0 ] === 'const';
  37444. if ( isConst === true ) {
  37445. i ++;
  37446. }
  37447. let qualifier = propsMatches[ i ][ 0 ];
  37448. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  37449. i ++;
  37450. } else {
  37451. qualifier = '';
  37452. }
  37453. const type = propsMatches[ i ++ ][ 0 ];
  37454. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  37455. if ( Number.isNaN( count ) === false ) i ++;
  37456. else count = null;
  37457. const name = propsMatches[ i ++ ][ 0 ];
  37458. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  37459. }
  37460. //
  37461. const blockCode = mainCode.substring( declaration[ 0 ].length );
  37462. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  37463. const type = declaration[ 2 ];
  37464. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  37465. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  37466. return {
  37467. type,
  37468. inputs,
  37469. name,
  37470. precision,
  37471. inputsCode,
  37472. blockCode,
  37473. headerCode
  37474. };
  37475. } else {
  37476. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  37477. }
  37478. };
  37479. class GLSLNodeFunction extends NodeFunction {
  37480. constructor( source ) {
  37481. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  37482. super( type, inputs, name, precision );
  37483. this.inputsCode = inputsCode;
  37484. this.blockCode = blockCode;
  37485. this.headerCode = headerCode;
  37486. }
  37487. getCode( name = this.name ) {
  37488. let code;
  37489. const blockCode = this.blockCode;
  37490. if ( blockCode !== '' ) {
  37491. const { type, inputsCode, headerCode, precision } = this;
  37492. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  37493. if ( precision !== '' ) {
  37494. declarationCode = `${ precision } ${ declarationCode }`;
  37495. }
  37496. code = headerCode + declarationCode + blockCode;
  37497. } else {
  37498. // interface function
  37499. code = '';
  37500. }
  37501. return code;
  37502. }
  37503. }
  37504. class GLSLNodeParser extends NodeParser {
  37505. parseFunction( source ) {
  37506. return new GLSLNodeFunction( source );
  37507. }
  37508. }
  37509. function painterSortStable( a, b ) {
  37510. if ( a.groupOrder !== b.groupOrder ) {
  37511. return a.groupOrder - b.groupOrder;
  37512. } else if ( a.renderOrder !== b.renderOrder ) {
  37513. return a.renderOrder - b.renderOrder;
  37514. } else if ( a.material.id !== b.material.id ) {
  37515. return a.material.id - b.material.id;
  37516. } else if ( a.z !== b.z ) {
  37517. return a.z - b.z;
  37518. } else {
  37519. return a.id - b.id;
  37520. }
  37521. }
  37522. function reversePainterSortStable( a, b ) {
  37523. if ( a.groupOrder !== b.groupOrder ) {
  37524. return a.groupOrder - b.groupOrder;
  37525. } else if ( a.renderOrder !== b.renderOrder ) {
  37526. return a.renderOrder - b.renderOrder;
  37527. } else if ( a.z !== b.z ) {
  37528. return b.z - a.z;
  37529. } else {
  37530. return a.id - b.id;
  37531. }
  37532. }
  37533. class RenderList {
  37534. constructor() {
  37535. this.renderItems = [];
  37536. this.renderItemsIndex = 0;
  37537. this.opaque = [];
  37538. this.transparent = [];
  37539. this.bundles = [];
  37540. this.lightsNode = new LightsNode( [] );
  37541. this.lightsArray = [];
  37542. this.occlusionQueryCount = 0;
  37543. }
  37544. begin() {
  37545. this.renderItemsIndex = 0;
  37546. this.opaque.length = 0;
  37547. this.transparent.length = 0;
  37548. this.bundles.length = 0;
  37549. this.lightsArray.length = 0;
  37550. this.occlusionQueryCount = 0;
  37551. return this;
  37552. }
  37553. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  37554. let renderItem = this.renderItems[ this.renderItemsIndex ];
  37555. if ( renderItem === undefined ) {
  37556. renderItem = {
  37557. id: object.id,
  37558. object: object,
  37559. geometry: geometry,
  37560. material: material,
  37561. groupOrder: groupOrder,
  37562. renderOrder: object.renderOrder,
  37563. z: z,
  37564. group: group
  37565. };
  37566. this.renderItems[ this.renderItemsIndex ] = renderItem;
  37567. } else {
  37568. renderItem.id = object.id;
  37569. renderItem.object = object;
  37570. renderItem.geometry = geometry;
  37571. renderItem.material = material;
  37572. renderItem.groupOrder = groupOrder;
  37573. renderItem.renderOrder = object.renderOrder;
  37574. renderItem.z = z;
  37575. renderItem.group = group;
  37576. }
  37577. this.renderItemsIndex ++;
  37578. return renderItem;
  37579. }
  37580. push( object, geometry, material, groupOrder, z, group ) {
  37581. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  37582. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  37583. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  37584. }
  37585. unshift( object, geometry, material, groupOrder, z, group ) {
  37586. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  37587. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  37588. }
  37589. pushBundle( group ) {
  37590. this.bundles.push( group );
  37591. }
  37592. pushLight( light ) {
  37593. this.lightsArray.push( light );
  37594. }
  37595. getLightsNode() {
  37596. return this.lightsNode.fromLights( this.lightsArray );
  37597. }
  37598. sort( customOpaqueSort, customTransparentSort ) {
  37599. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  37600. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  37601. }
  37602. finish() {
  37603. // update lights
  37604. this.lightsNode.setLights( this.lightsArray );
  37605. // Clear references from inactive renderItems in the list
  37606. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  37607. const renderItem = this.renderItems[ i ];
  37608. if ( renderItem.id === null ) break;
  37609. renderItem.id = null;
  37610. renderItem.object = null;
  37611. renderItem.geometry = null;
  37612. renderItem.material = null;
  37613. renderItem.groupOrder = null;
  37614. renderItem.renderOrder = null;
  37615. renderItem.z = null;
  37616. renderItem.group = null;
  37617. }
  37618. }
  37619. }
  37620. class RenderLists {
  37621. constructor() {
  37622. this.lists = new ChainMap();
  37623. }
  37624. get( scene, camera ) {
  37625. const lists = this.lists;
  37626. const keys = [ scene, camera ];
  37627. let list = lists.get( keys );
  37628. if ( list === undefined ) {
  37629. list = new RenderList();
  37630. lists.set( keys, list );
  37631. }
  37632. return list;
  37633. }
  37634. dispose() {
  37635. this.lists = new ChainMap();
  37636. }
  37637. }
  37638. let id = 0;
  37639. class RenderContext {
  37640. constructor() {
  37641. this.id = id ++;
  37642. this.color = true;
  37643. this.clearColor = true;
  37644. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  37645. this.depth = true;
  37646. this.clearDepth = true;
  37647. this.clearDepthValue = 1;
  37648. this.stencil = false;
  37649. this.clearStencil = true;
  37650. this.clearStencilValue = 1;
  37651. this.viewport = false;
  37652. this.viewportValue = new Vector4();
  37653. this.scissor = false;
  37654. this.scissorValue = new Vector4();
  37655. this.textures = null;
  37656. this.depthTexture = null;
  37657. this.activeCubeFace = 0;
  37658. this.sampleCount = 1;
  37659. this.width = 0;
  37660. this.height = 0;
  37661. this.isRenderContext = true;
  37662. }
  37663. getCacheKey() {
  37664. return getCacheKey( this );
  37665. }
  37666. }
  37667. function getCacheKey( renderContext ) {
  37668. const { textures, activeCubeFace } = renderContext;
  37669. let key = '';
  37670. for ( const texture of textures ) {
  37671. key += texture.id + ',';
  37672. }
  37673. key += activeCubeFace;
  37674. return key;
  37675. }
  37676. class RenderContexts {
  37677. constructor() {
  37678. this.chainMaps = {};
  37679. }
  37680. get( scene, camera, renderTarget = null ) {
  37681. const chainKey = [ scene, camera ];
  37682. let attachmentState;
  37683. if ( renderTarget === null ) {
  37684. attachmentState = 'default';
  37685. } else {
  37686. const format = renderTarget.texture.format;
  37687. const count = renderTarget.textures.length;
  37688. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  37689. }
  37690. const chainMap = this.getChainMap( attachmentState );
  37691. let renderState = chainMap.get( chainKey );
  37692. if ( renderState === undefined ) {
  37693. renderState = new RenderContext();
  37694. chainMap.set( chainKey, renderState );
  37695. }
  37696. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  37697. return renderState;
  37698. }
  37699. getChainMap( attachmentState ) {
  37700. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  37701. }
  37702. dispose() {
  37703. this.chainMaps = {};
  37704. }
  37705. }
  37706. const _size = /*@__PURE__*/ new Vector3();
  37707. class Textures extends DataMap {
  37708. constructor( renderer, backend, info ) {
  37709. super();
  37710. this.renderer = renderer;
  37711. this.backend = backend;
  37712. this.info = info;
  37713. }
  37714. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  37715. const renderTargetData = this.get( renderTarget );
  37716. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  37717. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  37718. const textures = renderTarget.textures;
  37719. const size = this.getSize( textures[ 0 ] );
  37720. const mipWidth = size.width >> activeMipmapLevel;
  37721. const mipHeight = size.height >> activeMipmapLevel;
  37722. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  37723. let textureNeedsUpdate = false;
  37724. if ( depthTexture === undefined ) {
  37725. depthTexture = new DepthTexture();
  37726. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  37727. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  37728. depthTexture.image.width = mipWidth;
  37729. depthTexture.image.height = mipHeight;
  37730. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  37731. }
  37732. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  37733. textureNeedsUpdate = true;
  37734. depthTexture.needsUpdate = true;
  37735. depthTexture.image.width = mipWidth;
  37736. depthTexture.image.height = mipHeight;
  37737. }
  37738. renderTargetData.width = size.width;
  37739. renderTargetData.height = size.height;
  37740. renderTargetData.textures = textures;
  37741. renderTargetData.depthTexture = depthTexture;
  37742. renderTargetData.depth = renderTarget.depthBuffer;
  37743. renderTargetData.stencil = renderTarget.stencilBuffer;
  37744. renderTargetData.renderTarget = renderTarget;
  37745. if ( renderTargetData.sampleCount !== sampleCount ) {
  37746. textureNeedsUpdate = true;
  37747. depthTexture.needsUpdate = true;
  37748. renderTargetData.sampleCount = sampleCount;
  37749. }
  37750. //
  37751. const options = { sampleCount };
  37752. for ( let i = 0; i < textures.length; i ++ ) {
  37753. const texture = textures[ i ];
  37754. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  37755. this.updateTexture( texture, options );
  37756. }
  37757. this.updateTexture( depthTexture, options );
  37758. // dispose handler
  37759. if ( renderTargetData.initialized !== true ) {
  37760. renderTargetData.initialized = true;
  37761. // dispose
  37762. const onDispose = () => {
  37763. renderTarget.removeEventListener( 'dispose', onDispose );
  37764. for ( let i = 0; i < textures.length; i ++ ) {
  37765. this._destroyTexture( textures[ i ] );
  37766. }
  37767. this._destroyTexture( depthTexture );
  37768. this.delete( renderTarget );
  37769. };
  37770. renderTarget.addEventListener( 'dispose', onDispose );
  37771. }
  37772. }
  37773. updateTexture( texture, options = {} ) {
  37774. const textureData = this.get( texture );
  37775. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  37776. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  37777. const backend = this.backend;
  37778. if ( isRenderTarget && textureData.initialized === true ) {
  37779. // it's an update
  37780. backend.destroySampler( texture );
  37781. backend.destroyTexture( texture );
  37782. }
  37783. //
  37784. if ( texture.isFramebufferTexture ) {
  37785. const renderer = this.renderer;
  37786. const renderTarget = renderer.getRenderTarget();
  37787. if ( renderTarget ) {
  37788. texture.type = renderTarget.texture.type;
  37789. } else {
  37790. texture.type = UnsignedByteType;
  37791. }
  37792. }
  37793. //
  37794. const { width, height, depth } = this.getSize( texture );
  37795. options.width = width;
  37796. options.height = height;
  37797. options.depth = depth;
  37798. options.needsMipmaps = this.needsMipmaps( texture );
  37799. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  37800. //
  37801. if ( isRenderTarget || texture.isStorageTexture === true ) {
  37802. backend.createSampler( texture );
  37803. backend.createTexture( texture, options );
  37804. textureData.generation = texture.version;
  37805. } else {
  37806. const needsCreate = textureData.initialized !== true;
  37807. if ( needsCreate ) backend.createSampler( texture );
  37808. if ( texture.version > 0 ) {
  37809. const image = texture.image;
  37810. if ( image === undefined ) {
  37811. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  37812. } else if ( image.complete === false ) {
  37813. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  37814. } else {
  37815. if ( texture.images ) {
  37816. const images = [];
  37817. for ( const image of texture.images ) {
  37818. images.push( image );
  37819. }
  37820. options.images = images;
  37821. } else {
  37822. options.image = image;
  37823. }
  37824. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  37825. backend.createTexture( texture, options );
  37826. textureData.isDefaultTexture = false;
  37827. textureData.generation = texture.version;
  37828. }
  37829. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  37830. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  37831. }
  37832. } else {
  37833. // async update
  37834. backend.createDefaultTexture( texture );
  37835. textureData.isDefaultTexture = true;
  37836. textureData.generation = texture.version;
  37837. }
  37838. }
  37839. // dispose handler
  37840. if ( textureData.initialized !== true ) {
  37841. textureData.initialized = true;
  37842. textureData.generation = texture.version;
  37843. //
  37844. this.info.memory.textures ++;
  37845. // dispose
  37846. const onDispose = () => {
  37847. texture.removeEventListener( 'dispose', onDispose );
  37848. this._destroyTexture( texture );
  37849. this.info.memory.textures --;
  37850. };
  37851. texture.addEventListener( 'dispose', onDispose );
  37852. }
  37853. //
  37854. textureData.version = texture.version;
  37855. }
  37856. getSize( texture, target = _size ) {
  37857. let image = texture.images ? texture.images[ 0 ] : texture.image;
  37858. if ( image ) {
  37859. if ( image.image !== undefined ) image = image.image;
  37860. target.width = image.width;
  37861. target.height = image.height;
  37862. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  37863. } else {
  37864. target.width = target.height = target.depth = 1;
  37865. }
  37866. return target;
  37867. }
  37868. getMipLevels( texture, width, height ) {
  37869. let mipLevelCount;
  37870. if ( texture.isCompressedTexture ) {
  37871. mipLevelCount = texture.mipmaps.length;
  37872. } else {
  37873. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  37874. }
  37875. return mipLevelCount;
  37876. }
  37877. needsMipmaps( texture ) {
  37878. if ( this.isEnvironmentTexture( texture ) ) return true;
  37879. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  37880. }
  37881. isEnvironmentTexture( texture ) {
  37882. const mapping = texture.mapping;
  37883. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  37884. }
  37885. _destroyTexture( texture ) {
  37886. this.backend.destroySampler( texture );
  37887. this.backend.destroyTexture( texture );
  37888. this.delete( texture );
  37889. }
  37890. }
  37891. class Color4 extends Color {
  37892. constructor( r, g, b, a = 1 ) {
  37893. super( r, g, b );
  37894. this.a = a;
  37895. }
  37896. set( r, g, b, a = 1 ) {
  37897. this.a = a;
  37898. return super.set( r, g, b );
  37899. }
  37900. copy( color ) {
  37901. if ( color.a !== undefined ) this.a = color.a;
  37902. return super.copy( color );
  37903. }
  37904. clone() {
  37905. return new this.constructor( this.r, this.g, this.b, this.a );
  37906. }
  37907. }
  37908. const _clearColor = /*@__PURE__*/ new Color4();
  37909. class Background extends DataMap {
  37910. constructor( renderer, nodes ) {
  37911. super();
  37912. this.renderer = renderer;
  37913. this.nodes = nodes;
  37914. }
  37915. update( scene, renderList, renderContext ) {
  37916. const renderer = this.renderer;
  37917. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  37918. let forceClear = false;
  37919. if ( background === null ) {
  37920. // no background settings, use clear color configuration from the renderer
  37921. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  37922. _clearColor.a = renderer._clearColor.a;
  37923. } else if ( background.isColor === true ) {
  37924. // background is an opaque color
  37925. background.getRGB( _clearColor, LinearSRGBColorSpace );
  37926. _clearColor.a = 1;
  37927. forceClear = true;
  37928. } else if ( background.isNode === true ) {
  37929. const sceneData = this.get( scene );
  37930. const backgroundNode = background;
  37931. _clearColor.copy( renderer._clearColor );
  37932. let backgroundMesh = sceneData.backgroundMesh;
  37933. if ( backgroundMesh === undefined ) {
  37934. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  37935. // @TODO: Add Texture2D support using node context
  37936. getUV: () => normalWorld,
  37937. getTextureLevel: () => backgroundBlurriness
  37938. } );
  37939. let viewProj = modelViewProjection();
  37940. viewProj = viewProj.setZ( viewProj.w );
  37941. const nodeMaterial = new NodeMaterial();
  37942. nodeMaterial.name = 'Background.material';
  37943. nodeMaterial.side = BackSide;
  37944. nodeMaterial.depthTest = false;
  37945. nodeMaterial.depthWrite = false;
  37946. nodeMaterial.fog = false;
  37947. nodeMaterial.lights = false;
  37948. nodeMaterial.vertexNode = viewProj;
  37949. nodeMaterial.colorNode = backgroundMeshNode;
  37950. sceneData.backgroundMeshNode = backgroundMeshNode;
  37951. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  37952. backgroundMesh.frustumCulled = false;
  37953. backgroundMesh.name = 'Background.mesh';
  37954. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  37955. this.matrixWorld.copyPosition( camera.matrixWorld );
  37956. };
  37957. }
  37958. const backgroundCacheKey = backgroundNode.getCacheKey();
  37959. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  37960. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  37961. sceneData.backgroundMeshNode.needsUpdate = true;
  37962. backgroundMesh.material.needsUpdate = true;
  37963. sceneData.backgroundCacheKey = backgroundCacheKey;
  37964. }
  37965. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  37966. } else {
  37967. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  37968. }
  37969. //
  37970. if ( renderer.autoClear === true || forceClear === true ) {
  37971. _clearColor.multiplyScalar( _clearColor.a );
  37972. const clearColorValue = renderContext.clearColorValue;
  37973. clearColorValue.r = _clearColor.r;
  37974. clearColorValue.g = _clearColor.g;
  37975. clearColorValue.b = _clearColor.b;
  37976. clearColorValue.a = _clearColor.a;
  37977. renderContext.depthClearValue = renderer._clearDepth;
  37978. renderContext.stencilClearValue = renderer._clearStencil;
  37979. renderContext.clearColor = renderer.autoClearColor === true;
  37980. renderContext.clearDepth = renderer.autoClearDepth === true;
  37981. renderContext.clearStencil = renderer.autoClearStencil === true;
  37982. } else {
  37983. renderContext.clearColor = false;
  37984. renderContext.clearDepth = false;
  37985. renderContext.clearStencil = false;
  37986. }
  37987. }
  37988. }
  37989. class NodeBuilderState {
  37990. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  37991. this.vertexShader = vertexShader;
  37992. this.fragmentShader = fragmentShader;
  37993. this.computeShader = computeShader;
  37994. this.transforms = transforms;
  37995. this.nodeAttributes = nodeAttributes;
  37996. this.bindings = bindings;
  37997. this.updateNodes = updateNodes;
  37998. this.updateBeforeNodes = updateBeforeNodes;
  37999. this.updateAfterNodes = updateAfterNodes;
  38000. this.monitor = monitor;
  38001. this.usedTimes = 0;
  38002. }
  38003. createBindings() {
  38004. const bindings = [];
  38005. for ( const instanceGroup of this.bindings ) {
  38006. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  38007. if ( shared !== true ) {
  38008. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  38009. bindings.push( bindingsGroup );
  38010. for ( const instanceBinding of instanceGroup.bindings ) {
  38011. bindingsGroup.bindings.push( instanceBinding.clone() );
  38012. }
  38013. } else {
  38014. bindings.push( instanceGroup );
  38015. }
  38016. }
  38017. return bindings;
  38018. }
  38019. }
  38020. const outputNodeMap = new WeakMap();
  38021. class Nodes extends DataMap {
  38022. constructor( renderer, backend ) {
  38023. super();
  38024. this.renderer = renderer;
  38025. this.backend = backend;
  38026. this.nodeFrame = new NodeFrame();
  38027. this.nodeBuilderCache = new Map();
  38028. this.callHashCache = new ChainMap();
  38029. this.groupsData = new ChainMap();
  38030. }
  38031. updateGroup( nodeUniformsGroup ) {
  38032. const groupNode = nodeUniformsGroup.groupNode;
  38033. const name = groupNode.name;
  38034. // objectGroup is every updated
  38035. if ( name === objectGroup.name ) return true;
  38036. // renderGroup is updated once per render/compute call
  38037. if ( name === renderGroup.name ) {
  38038. const uniformsGroupData = this.get( nodeUniformsGroup );
  38039. const renderId = this.nodeFrame.renderId;
  38040. if ( uniformsGroupData.renderId !== renderId ) {
  38041. uniformsGroupData.renderId = renderId;
  38042. return true;
  38043. }
  38044. return false;
  38045. }
  38046. // frameGroup is updated once per frame
  38047. if ( name === frameGroup.name ) {
  38048. const uniformsGroupData = this.get( nodeUniformsGroup );
  38049. const frameId = this.nodeFrame.frameId;
  38050. if ( uniformsGroupData.frameId !== frameId ) {
  38051. uniformsGroupData.frameId = frameId;
  38052. return true;
  38053. }
  38054. return false;
  38055. }
  38056. // other groups are updated just when groupNode.needsUpdate is true
  38057. const groupChain = [ groupNode, nodeUniformsGroup ];
  38058. let groupData = this.groupsData.get( groupChain );
  38059. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  38060. if ( groupData.version !== groupNode.version ) {
  38061. groupData.version = groupNode.version;
  38062. return true;
  38063. }
  38064. return false;
  38065. }
  38066. getForRenderCacheKey( renderObject ) {
  38067. return renderObject.initialCacheKey;
  38068. }
  38069. getForRender( renderObject ) {
  38070. const renderObjectData = this.get( renderObject );
  38071. let nodeBuilderState = renderObjectData.nodeBuilderState;
  38072. if ( nodeBuilderState === undefined ) {
  38073. const { nodeBuilderCache } = this;
  38074. const cacheKey = this.getForRenderCacheKey( renderObject );
  38075. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  38076. if ( nodeBuilderState === undefined ) {
  38077. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  38078. nodeBuilder.scene = renderObject.scene;
  38079. nodeBuilder.material = renderObject.material;
  38080. nodeBuilder.camera = renderObject.camera;
  38081. nodeBuilder.context.material = renderObject.material;
  38082. nodeBuilder.lightsNode = renderObject.lightsNode;
  38083. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  38084. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  38085. nodeBuilder.clippingContext = renderObject.clippingContext;
  38086. nodeBuilder.build();
  38087. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38088. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  38089. }
  38090. nodeBuilderState.usedTimes ++;
  38091. renderObjectData.nodeBuilderState = nodeBuilderState;
  38092. }
  38093. return nodeBuilderState;
  38094. }
  38095. delete( object ) {
  38096. if ( object.isRenderObject ) {
  38097. const nodeBuilderState = this.get( object ).nodeBuilderState;
  38098. nodeBuilderState.usedTimes --;
  38099. if ( nodeBuilderState.usedTimes === 0 ) {
  38100. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  38101. }
  38102. }
  38103. return super.delete( object );
  38104. }
  38105. getForCompute( computeNode ) {
  38106. const computeData = this.get( computeNode );
  38107. let nodeBuilderState = computeData.nodeBuilderState;
  38108. if ( nodeBuilderState === undefined ) {
  38109. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  38110. nodeBuilder.build();
  38111. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  38112. computeData.nodeBuilderState = nodeBuilderState;
  38113. }
  38114. return nodeBuilderState;
  38115. }
  38116. _createNodeBuilderState( nodeBuilder ) {
  38117. return new NodeBuilderState(
  38118. nodeBuilder.vertexShader,
  38119. nodeBuilder.fragmentShader,
  38120. nodeBuilder.computeShader,
  38121. nodeBuilder.getAttributesArray(),
  38122. nodeBuilder.getBindings(),
  38123. nodeBuilder.updateNodes,
  38124. nodeBuilder.updateBeforeNodes,
  38125. nodeBuilder.updateAfterNodes,
  38126. nodeBuilder.monitor,
  38127. nodeBuilder.transforms
  38128. );
  38129. }
  38130. getEnvironmentNode( scene ) {
  38131. return scene.environmentNode || this.get( scene ).environmentNode || null;
  38132. }
  38133. getBackgroundNode( scene ) {
  38134. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  38135. }
  38136. getFogNode( scene ) {
  38137. return scene.fogNode || this.get( scene ).fogNode || null;
  38138. }
  38139. getCacheKey( scene, lightsNode ) {
  38140. const chain = [ scene, lightsNode ];
  38141. const callId = this.renderer.info.calls;
  38142. let cacheKeyData = this.callHashCache.get( chain );
  38143. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  38144. const environmentNode = this.getEnvironmentNode( scene );
  38145. const fogNode = this.getFogNode( scene );
  38146. const cacheKey = [];
  38147. if ( lightsNode ) cacheKey.push( lightsNode.getCacheKey( true ) );
  38148. if ( environmentNode ) cacheKey.push( environmentNode.getCacheKey() );
  38149. if ( fogNode ) cacheKey.push( fogNode.getCacheKey() );
  38150. cacheKeyData = {
  38151. callId,
  38152. cacheKey: cacheKey.join( ',' )
  38153. };
  38154. this.callHashCache.set( chain, cacheKeyData );
  38155. }
  38156. return cacheKeyData.cacheKey;
  38157. }
  38158. updateScene( scene ) {
  38159. this.updateEnvironment( scene );
  38160. this.updateFog( scene );
  38161. this.updateBackground( scene );
  38162. }
  38163. get isToneMappingState() {
  38164. return this.renderer.getRenderTarget() ? false : true;
  38165. }
  38166. updateBackground( scene ) {
  38167. const sceneData = this.get( scene );
  38168. const background = scene.background;
  38169. if ( background ) {
  38170. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  38171. if ( sceneData.background !== background || forceUpdate ) {
  38172. let backgroundNode = null;
  38173. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  38174. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  38175. backgroundNode = pmremTexture( background, normalWorld );
  38176. } else {
  38177. let envMap;
  38178. if ( background.isCubeTexture === true ) {
  38179. envMap = cubeTexture( background );
  38180. } else {
  38181. envMap = texture( background );
  38182. }
  38183. backgroundNode = cubeMapNode( envMap );
  38184. }
  38185. } else if ( background.isTexture === true ) {
  38186. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  38187. } else if ( background.isColor !== true ) {
  38188. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  38189. }
  38190. sceneData.backgroundNode = backgroundNode;
  38191. sceneData.background = background;
  38192. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  38193. }
  38194. } else if ( sceneData.backgroundNode ) {
  38195. delete sceneData.backgroundNode;
  38196. delete sceneData.background;
  38197. }
  38198. }
  38199. updateFog( scene ) {
  38200. const sceneData = this.get( scene );
  38201. const fog = scene.fog;
  38202. if ( fog ) {
  38203. if ( sceneData.fog !== fog ) {
  38204. let fogNode = null;
  38205. if ( fog.isFogExp2 ) {
  38206. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  38207. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  38208. fogNode = densityFog( color, density );
  38209. } else if ( fog.isFog ) {
  38210. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  38211. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  38212. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  38213. fogNode = rangeFog( color, near, far );
  38214. } else {
  38215. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  38216. }
  38217. sceneData.fogNode = fogNode;
  38218. sceneData.fog = fog;
  38219. }
  38220. } else {
  38221. delete sceneData.fogNode;
  38222. delete sceneData.fog;
  38223. }
  38224. }
  38225. updateEnvironment( scene ) {
  38226. const sceneData = this.get( scene );
  38227. const environment = scene.environment;
  38228. if ( environment ) {
  38229. if ( sceneData.environment !== environment ) {
  38230. let environmentNode = null;
  38231. if ( environment.isCubeTexture === true ) {
  38232. environmentNode = cubeTexture( environment );
  38233. } else if ( environment.isTexture === true ) {
  38234. environmentNode = texture( environment );
  38235. } else {
  38236. console.error( 'Nodes: Unsupported environment configuration.', environment );
  38237. }
  38238. sceneData.environmentNode = environmentNode;
  38239. sceneData.environment = environment;
  38240. }
  38241. } else if ( sceneData.environmentNode ) {
  38242. delete sceneData.environmentNode;
  38243. delete sceneData.environment;
  38244. }
  38245. }
  38246. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  38247. const nodeFrame = this.nodeFrame;
  38248. nodeFrame.renderer = renderer;
  38249. nodeFrame.scene = scene;
  38250. nodeFrame.object = object;
  38251. nodeFrame.camera = camera;
  38252. nodeFrame.material = material;
  38253. return nodeFrame;
  38254. }
  38255. getNodeFrameForRender( renderObject ) {
  38256. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  38257. }
  38258. getOutputCacheKey() {
  38259. const renderer = this.renderer;
  38260. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  38261. }
  38262. hasOutputChange( outputTarget ) {
  38263. const cacheKey = outputNodeMap.get( outputTarget );
  38264. return cacheKey !== this.getOutputCacheKey();
  38265. }
  38266. getOutputNode( outputTexture ) {
  38267. const renderer = this.renderer;
  38268. const cacheKey = this.getOutputCacheKey();
  38269. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  38270. outputNodeMap.set( outputTexture, cacheKey );
  38271. return output;
  38272. }
  38273. updateBefore( renderObject ) {
  38274. const nodeBuilder = renderObject.getNodeBuilderState();
  38275. for ( const node of nodeBuilder.updateBeforeNodes ) {
  38276. // update frame state for each node
  38277. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  38278. }
  38279. }
  38280. updateAfter( renderObject ) {
  38281. const nodeBuilder = renderObject.getNodeBuilderState();
  38282. for ( const node of nodeBuilder.updateAfterNodes ) {
  38283. // update frame state for each node
  38284. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  38285. }
  38286. }
  38287. updateForCompute( computeNode ) {
  38288. const nodeFrame = this.getNodeFrame();
  38289. const nodeBuilder = this.getForCompute( computeNode );
  38290. for ( const node of nodeBuilder.updateNodes ) {
  38291. nodeFrame.updateNode( node );
  38292. }
  38293. }
  38294. updateForRender( renderObject ) {
  38295. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38296. const nodeBuilder = renderObject.getNodeBuilderState();
  38297. for ( const node of nodeBuilder.updateNodes ) {
  38298. nodeFrame.updateNode( node );
  38299. }
  38300. }
  38301. needsRefresh( renderObject ) {
  38302. const nodeFrame = this.getNodeFrameForRender( renderObject );
  38303. const monitor = renderObject.getMonitor();
  38304. return monitor.needsRefresh( renderObject, nodeFrame );
  38305. }
  38306. dispose() {
  38307. super.dispose();
  38308. this.nodeFrame = new NodeFrame();
  38309. this.nodeBuilderCache = new Map();
  38310. }
  38311. }
  38312. class RenderBundle {
  38313. constructor( scene, camera ) {
  38314. this.scene = scene;
  38315. this.camera = camera;
  38316. }
  38317. clone() {
  38318. return Object.assign( new this.constructor(), this );
  38319. }
  38320. }
  38321. class RenderBundles {
  38322. constructor() {
  38323. this.lists = new ChainMap();
  38324. }
  38325. get( scene, camera ) {
  38326. const lists = this.lists;
  38327. const keys = [ scene, camera ];
  38328. let list = lists.get( keys );
  38329. if ( list === undefined ) {
  38330. list = new RenderBundle( scene, camera );
  38331. lists.set( keys, list );
  38332. }
  38333. return list;
  38334. }
  38335. dispose() {
  38336. this.lists = new ChainMap();
  38337. }
  38338. }
  38339. class NodeLibrary {
  38340. constructor() {
  38341. this.lightNodes = new WeakMap();
  38342. this.materialNodes = new Map();
  38343. this.toneMappingNodes = new Map();
  38344. this.colorSpaceNodes = new Map();
  38345. }
  38346. fromMaterial( material ) {
  38347. if ( material.isNodeMaterial ) return material;
  38348. let nodeMaterial = null;
  38349. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  38350. if ( nodeMaterialClass !== null ) {
  38351. nodeMaterial = new nodeMaterialClass();
  38352. for ( const key in material ) {
  38353. nodeMaterial[ key ] = material[ key ];
  38354. }
  38355. }
  38356. return nodeMaterial;
  38357. }
  38358. addColorSpace( colorSpaceNode, colorSpace ) {
  38359. this.addType( colorSpaceNode, colorSpace, this.colorSpaceNodes );
  38360. }
  38361. getColorSpaceFunction( colorSpace ) {
  38362. return this.colorSpaceNodes.get( colorSpace ) || null;
  38363. }
  38364. addToneMapping( toneMappingNode, toneMapping ) {
  38365. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  38366. }
  38367. getToneMappingFunction( toneMapping ) {
  38368. return this.toneMappingNodes.get( toneMapping ) || null;
  38369. }
  38370. getMaterialNodeClass( materialType ) {
  38371. return this.materialNodes.get( materialType ) || null;
  38372. }
  38373. addMaterial( materialNodeClass, materialClass ) {
  38374. this.addType( materialNodeClass, materialClass.name, this.materialNodes );
  38375. }
  38376. getLightNodeClass( light ) {
  38377. return this.lightNodes.get( light ) || null;
  38378. }
  38379. addLight( lightNodeClass, lightClass ) {
  38380. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  38381. }
  38382. addType( nodeClass, type, library ) {
  38383. if ( library.has( type ) ) {
  38384. console.warn( `Redefinition of node ${ type }` );
  38385. return;
  38386. }
  38387. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  38388. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  38389. library.set( type, nodeClass );
  38390. }
  38391. addClass( nodeClass, baseClass, library ) {
  38392. if ( library.has( baseClass ) ) {
  38393. console.warn( `Redefinition of node ${ baseClass.name }` );
  38394. return;
  38395. }
  38396. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  38397. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  38398. library.set( baseClass, nodeClass );
  38399. }
  38400. }
  38401. const _scene = /*@__PURE__*/ new Scene();
  38402. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  38403. const _screen = /*@__PURE__*/ new Vector4();
  38404. const _frustum = /*@__PURE__*/ new Frustum();
  38405. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  38406. const _vector4 = /*@__PURE__*/ new Vector4();
  38407. class Renderer {
  38408. constructor( backend, parameters = {} ) {
  38409. this.isRenderer = true;
  38410. //
  38411. const {
  38412. logarithmicDepthBuffer = false,
  38413. alpha = true,
  38414. depth = true,
  38415. stencil = false,
  38416. antialias = false,
  38417. samples = 0,
  38418. getFallback = null
  38419. } = parameters;
  38420. // public
  38421. this.domElement = backend.getDomElement();
  38422. this.backend = backend;
  38423. this.samples = samples || ( antialias === true ) ? 4 : 0;
  38424. this.autoClear = true;
  38425. this.autoClearColor = true;
  38426. this.autoClearDepth = true;
  38427. this.autoClearStencil = true;
  38428. this.alpha = alpha;
  38429. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  38430. this.outputColorSpace = SRGBColorSpace;
  38431. this.toneMapping = NoToneMapping;
  38432. this.toneMappingExposure = 1.0;
  38433. this.sortObjects = true;
  38434. this.depth = depth;
  38435. this.stencil = stencil;
  38436. this.clippingPlanes = [];
  38437. this.info = new Info();
  38438. this.nodes = {
  38439. library: new NodeLibrary(),
  38440. modelViewMatrix: null,
  38441. modelNormalViewMatrix: null
  38442. };
  38443. // internals
  38444. this._getFallback = getFallback;
  38445. this._pixelRatio = 1;
  38446. this._width = this.domElement.width;
  38447. this._height = this.domElement.height;
  38448. this._viewport = new Vector4( 0, 0, this._width, this._height );
  38449. this._scissor = new Vector4( 0, 0, this._width, this._height );
  38450. this._scissorTest = false;
  38451. this._attributes = null;
  38452. this._geometries = null;
  38453. this._nodes = null;
  38454. this._animation = null;
  38455. this._bindings = null;
  38456. this._objects = null;
  38457. this._pipelines = null;
  38458. this._bundles = null;
  38459. this._renderLists = null;
  38460. this._renderContexts = null;
  38461. this._textures = null;
  38462. this._background = null;
  38463. this._quad = new QuadMesh( new NodeMaterial() );
  38464. this._quad.material.type = 'Renderer_output';
  38465. this._currentRenderContext = null;
  38466. this._opaqueSort = null;
  38467. this._transparentSort = null;
  38468. this._frameBufferTarget = null;
  38469. const alphaClear = this.alpha === true ? 0 : 1;
  38470. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  38471. this._clearDepth = 1;
  38472. this._clearStencil = 0;
  38473. this._renderTarget = null;
  38474. this._activeCubeFace = 0;
  38475. this._activeMipmapLevel = 0;
  38476. this._mrt = null;
  38477. this._renderObjectFunction = null;
  38478. this._currentRenderObjectFunction = null;
  38479. this._currentRenderBundle = null;
  38480. this._handleObjectFunction = this._renderObjectDirect;
  38481. this._initialized = false;
  38482. this._initPromise = null;
  38483. this._compilationPromises = null;
  38484. this.transparent = true;
  38485. this.opaque = true;
  38486. this.shadowMap = {
  38487. enabled: false,
  38488. type: PCFShadowMap$1
  38489. };
  38490. this.xr = {
  38491. enabled: false
  38492. };
  38493. this.debug = {
  38494. checkShaderErrors: true,
  38495. onShaderError: null,
  38496. getShaderAsync: async ( scene, camera, object ) => {
  38497. await this.compileAsync( scene, camera );
  38498. const renderList = this._renderLists.get( scene, camera );
  38499. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  38500. const material = scene.overrideMaterial || object.material;
  38501. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext );
  38502. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  38503. return { fragmentShader, vertexShader };
  38504. }
  38505. };
  38506. }
  38507. async init() {
  38508. if ( this._initialized ) {
  38509. throw new Error( 'Renderer: Backend has already been initialized.' );
  38510. }
  38511. if ( this._initPromise !== null ) {
  38512. return this._initPromise;
  38513. }
  38514. this._initPromise = new Promise( async ( resolve, reject ) => {
  38515. let backend = this.backend;
  38516. try {
  38517. await backend.init( this );
  38518. } catch ( error ) {
  38519. if ( this._getFallback !== null ) {
  38520. // try the fallback
  38521. try {
  38522. this.backend = backend = this._getFallback( error );
  38523. await backend.init( this );
  38524. } catch ( error ) {
  38525. reject( error );
  38526. return;
  38527. }
  38528. } else {
  38529. reject( error );
  38530. return;
  38531. }
  38532. }
  38533. this._nodes = new Nodes( this, backend );
  38534. this._animation = new Animation( this._nodes, this.info );
  38535. this._attributes = new Attributes( backend );
  38536. this._background = new Background( this, this._nodes );
  38537. this._geometries = new Geometries( this._attributes, this.info );
  38538. this._textures = new Textures( this, backend, this.info );
  38539. this._pipelines = new Pipelines( backend, this._nodes );
  38540. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  38541. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  38542. this._renderLists = new RenderLists();
  38543. this._bundles = new RenderBundles();
  38544. this._renderContexts = new RenderContexts();
  38545. //
  38546. this._initialized = true;
  38547. resolve();
  38548. } );
  38549. return this._initPromise;
  38550. }
  38551. get coordinateSystem() {
  38552. return this.backend.coordinateSystem;
  38553. }
  38554. async compileAsync( scene, camera, targetScene = null ) {
  38555. if ( this._initialized === false ) await this.init();
  38556. // preserve render tree
  38557. const nodeFrame = this._nodes.nodeFrame;
  38558. const previousRenderId = nodeFrame.renderId;
  38559. const previousRenderContext = this._currentRenderContext;
  38560. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  38561. const previousCompilationPromises = this._compilationPromises;
  38562. //
  38563. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  38564. if ( targetScene === null ) targetScene = scene;
  38565. const renderTarget = this._renderTarget;
  38566. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  38567. const activeMipmapLevel = this._activeMipmapLevel;
  38568. const compilationPromises = [];
  38569. this._currentRenderContext = renderContext;
  38570. this._currentRenderObjectFunction = this.renderObject;
  38571. this._handleObjectFunction = this._createObjectPipeline;
  38572. this._compilationPromises = compilationPromises;
  38573. nodeFrame.renderId ++;
  38574. //
  38575. nodeFrame.update();
  38576. //
  38577. renderContext.depth = this.depth;
  38578. renderContext.stencil = this.stencil;
  38579. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  38580. renderContext.clippingContext.updateGlobal( this, camera );
  38581. //
  38582. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  38583. //
  38584. const renderList = this._renderLists.get( scene, camera );
  38585. renderList.begin();
  38586. this._projectObject( scene, camera, 0, renderList );
  38587. // include lights from target scene
  38588. if ( targetScene !== scene ) {
  38589. targetScene.traverseVisible( function ( object ) {
  38590. if ( object.isLight && object.layers.test( camera.layers ) ) {
  38591. renderList.pushLight( object );
  38592. }
  38593. } );
  38594. }
  38595. renderList.finish();
  38596. //
  38597. if ( renderTarget !== null ) {
  38598. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  38599. const renderTargetData = this._textures.get( renderTarget );
  38600. renderContext.textures = renderTargetData.textures;
  38601. renderContext.depthTexture = renderTargetData.depthTexture;
  38602. } else {
  38603. renderContext.textures = null;
  38604. renderContext.depthTexture = null;
  38605. }
  38606. //
  38607. this._nodes.updateScene( sceneRef );
  38608. //
  38609. this._background.update( sceneRef, renderList, renderContext );
  38610. // process render lists
  38611. const opaqueObjects = renderList.opaque;
  38612. const transparentObjects = renderList.transparent;
  38613. const lightsNode = renderList.lightsNode;
  38614. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38615. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  38616. // restore render tree
  38617. nodeFrame.renderId = previousRenderId;
  38618. this._currentRenderContext = previousRenderContext;
  38619. this._currentRenderObjectFunction = previousRenderObjectFunction;
  38620. this._compilationPromises = previousCompilationPromises;
  38621. this._handleObjectFunction = this._renderObjectDirect;
  38622. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  38623. await Promise.all( compilationPromises );
  38624. }
  38625. async renderAsync( scene, camera ) {
  38626. if ( this._initialized === false ) await this.init();
  38627. const renderContext = this._renderScene( scene, camera );
  38628. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  38629. }
  38630. setMRT( mrt ) {
  38631. this._mrt = mrt;
  38632. return this;
  38633. }
  38634. getMRT() {
  38635. return this._mrt;
  38636. }
  38637. _renderBundle( bundle, sceneRef, lightsNode ) {
  38638. const { bundleGroup, camera, renderList } = bundle;
  38639. const renderContext = this._currentRenderContext;
  38640. //
  38641. const renderBundle = this._bundles.get( bundleGroup, camera );
  38642. const renderBundleData = this.backend.get( renderBundle );
  38643. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  38644. //
  38645. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  38646. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  38647. renderBundleData.renderContexts.add( renderContext );
  38648. if ( renderBundleNeedsUpdate ) {
  38649. this.backend.beginBundle( renderContext );
  38650. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  38651. renderBundleData.renderObjects = [];
  38652. }
  38653. this._currentRenderBundle = renderBundle;
  38654. const opaqueObjects = renderList.opaque;
  38655. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38656. this._currentRenderBundle = null;
  38657. //
  38658. this.backend.finishBundle( renderContext, renderBundle );
  38659. renderBundleData.version = bundleGroup.version;
  38660. } else {
  38661. const { renderObjects } = renderBundleData;
  38662. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  38663. const renderObject = renderObjects[ i ];
  38664. if ( this._nodes.needsRefresh( renderObject ) ) {
  38665. this._nodes.updateBefore( renderObject );
  38666. this._nodes.updateForRender( renderObject );
  38667. this._bindings.updateForRender( renderObject );
  38668. this._nodes.updateAfter( renderObject );
  38669. }
  38670. }
  38671. }
  38672. this.backend.addBundle( renderContext, renderBundle );
  38673. }
  38674. render( scene, camera ) {
  38675. if ( this._initialized === false ) {
  38676. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  38677. return this.renderAsync( scene, camera );
  38678. }
  38679. this._renderScene( scene, camera );
  38680. }
  38681. _getFrameBufferTarget() {
  38682. const { currentToneMapping, currentColorSpace } = this;
  38683. const useToneMapping = currentToneMapping !== NoToneMapping;
  38684. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  38685. if ( useToneMapping === false && useColorSpace === false ) return null;
  38686. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  38687. const { depth, stencil } = this;
  38688. let frameBufferTarget = this._frameBufferTarget;
  38689. if ( frameBufferTarget === null ) {
  38690. frameBufferTarget = new RenderTarget( width, height, {
  38691. depthBuffer: depth,
  38692. stencilBuffer: stencil,
  38693. type: HalfFloatType, // FloatType
  38694. format: RGBAFormat,
  38695. colorSpace: LinearSRGBColorSpace,
  38696. generateMipmaps: false,
  38697. minFilter: LinearFilter,
  38698. magFilter: LinearFilter,
  38699. samples: this.samples
  38700. } );
  38701. frameBufferTarget.isPostProcessingRenderTarget = true;
  38702. this._frameBufferTarget = frameBufferTarget;
  38703. }
  38704. frameBufferTarget.depthBuffer = depth;
  38705. frameBufferTarget.stencilBuffer = stencil;
  38706. frameBufferTarget.setSize( width, height );
  38707. frameBufferTarget.viewport.copy( this._viewport );
  38708. frameBufferTarget.scissor.copy( this._scissor );
  38709. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  38710. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  38711. frameBufferTarget.scissorTest = this._scissorTest;
  38712. return frameBufferTarget;
  38713. }
  38714. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  38715. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  38716. // preserve render tree
  38717. const nodeFrame = this._nodes.nodeFrame;
  38718. const previousRenderId = nodeFrame.renderId;
  38719. const previousRenderContext = this._currentRenderContext;
  38720. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  38721. //
  38722. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  38723. const outputRenderTarget = this._renderTarget;
  38724. const activeCubeFace = this._activeCubeFace;
  38725. const activeMipmapLevel = this._activeMipmapLevel;
  38726. //
  38727. let renderTarget;
  38728. if ( frameBufferTarget !== null ) {
  38729. renderTarget = frameBufferTarget;
  38730. this.setRenderTarget( renderTarget );
  38731. } else {
  38732. renderTarget = outputRenderTarget;
  38733. }
  38734. //
  38735. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  38736. this._currentRenderContext = renderContext;
  38737. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  38738. //
  38739. this.info.calls ++;
  38740. this.info.render.calls ++;
  38741. this.info.render.frameCalls ++;
  38742. nodeFrame.renderId = this.info.calls;
  38743. //
  38744. const coordinateSystem = this.coordinateSystem;
  38745. if ( camera.coordinateSystem !== coordinateSystem ) {
  38746. camera.coordinateSystem = coordinateSystem;
  38747. camera.updateProjectionMatrix();
  38748. }
  38749. //
  38750. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  38751. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  38752. //
  38753. let viewport = this._viewport;
  38754. let scissor = this._scissor;
  38755. let pixelRatio = this._pixelRatio;
  38756. if ( renderTarget !== null ) {
  38757. viewport = renderTarget.viewport;
  38758. scissor = renderTarget.scissor;
  38759. pixelRatio = 1;
  38760. }
  38761. this.getDrawingBufferSize( _drawingBufferSize );
  38762. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  38763. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  38764. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  38765. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  38766. renderContext.viewportValue.width >>= activeMipmapLevel;
  38767. renderContext.viewportValue.height >>= activeMipmapLevel;
  38768. renderContext.viewportValue.minDepth = minDepth;
  38769. renderContext.viewportValue.maxDepth = maxDepth;
  38770. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  38771. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  38772. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  38773. renderContext.scissorValue.width >>= activeMipmapLevel;
  38774. renderContext.scissorValue.height >>= activeMipmapLevel;
  38775. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  38776. renderContext.clippingContext.updateGlobal( this, camera );
  38777. //
  38778. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  38779. //
  38780. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  38781. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  38782. const renderList = this._renderLists.get( scene, camera );
  38783. renderList.begin();
  38784. this._projectObject( scene, camera, 0, renderList );
  38785. renderList.finish();
  38786. if ( this.sortObjects === true ) {
  38787. renderList.sort( this._opaqueSort, this._transparentSort );
  38788. }
  38789. //
  38790. if ( renderTarget !== null ) {
  38791. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  38792. const renderTargetData = this._textures.get( renderTarget );
  38793. renderContext.textures = renderTargetData.textures;
  38794. renderContext.depthTexture = renderTargetData.depthTexture;
  38795. renderContext.width = renderTargetData.width;
  38796. renderContext.height = renderTargetData.height;
  38797. renderContext.renderTarget = renderTarget;
  38798. renderContext.depth = renderTarget.depthBuffer;
  38799. renderContext.stencil = renderTarget.stencilBuffer;
  38800. } else {
  38801. renderContext.textures = null;
  38802. renderContext.depthTexture = null;
  38803. renderContext.width = this.domElement.width;
  38804. renderContext.height = this.domElement.height;
  38805. renderContext.depth = this.depth;
  38806. renderContext.stencil = this.stencil;
  38807. }
  38808. renderContext.width >>= activeMipmapLevel;
  38809. renderContext.height >>= activeMipmapLevel;
  38810. renderContext.activeCubeFace = activeCubeFace;
  38811. renderContext.activeMipmapLevel = activeMipmapLevel;
  38812. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  38813. //
  38814. this._nodes.updateScene( sceneRef );
  38815. //
  38816. this._background.update( sceneRef, renderList, renderContext );
  38817. //
  38818. this.backend.beginRender( renderContext );
  38819. // process render lists
  38820. const {
  38821. bundles,
  38822. lightsNode,
  38823. transparent: transparentObjects,
  38824. opaque: opaqueObjects
  38825. } = renderList;
  38826. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  38827. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38828. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  38829. // finish render pass
  38830. this.backend.finishRender( renderContext );
  38831. // restore render tree
  38832. nodeFrame.renderId = previousRenderId;
  38833. this._currentRenderContext = previousRenderContext;
  38834. this._currentRenderObjectFunction = previousRenderObjectFunction;
  38835. //
  38836. if ( frameBufferTarget !== null ) {
  38837. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  38838. const quad = this._quad;
  38839. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  38840. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  38841. quad.material.needsUpdate = true;
  38842. }
  38843. this._renderScene( quad, quad.camera, false );
  38844. }
  38845. //
  38846. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  38847. //
  38848. return renderContext;
  38849. }
  38850. getMaxAnisotropy() {
  38851. return this.backend.getMaxAnisotropy();
  38852. }
  38853. getActiveCubeFace() {
  38854. return this._activeCubeFace;
  38855. }
  38856. getActiveMipmapLevel() {
  38857. return this._activeMipmapLevel;
  38858. }
  38859. async setAnimationLoop( callback ) {
  38860. if ( this._initialized === false ) await this.init();
  38861. this._animation.setAnimationLoop( callback );
  38862. }
  38863. async getArrayBufferAsync( attribute ) {
  38864. return await this.backend.getArrayBufferAsync( attribute );
  38865. }
  38866. getContext() {
  38867. return this.backend.getContext();
  38868. }
  38869. getPixelRatio() {
  38870. return this._pixelRatio;
  38871. }
  38872. getDrawingBufferSize( target ) {
  38873. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  38874. }
  38875. getSize( target ) {
  38876. return target.set( this._width, this._height );
  38877. }
  38878. setPixelRatio( value = 1 ) {
  38879. this._pixelRatio = value;
  38880. this.setSize( this._width, this._height, false );
  38881. }
  38882. setDrawingBufferSize( width, height, pixelRatio ) {
  38883. this._width = width;
  38884. this._height = height;
  38885. this._pixelRatio = pixelRatio;
  38886. this.domElement.width = Math.floor( width * pixelRatio );
  38887. this.domElement.height = Math.floor( height * pixelRatio );
  38888. this.setViewport( 0, 0, width, height );
  38889. if ( this._initialized ) this.backend.updateSize();
  38890. }
  38891. setSize( width, height, updateStyle = true ) {
  38892. this._width = width;
  38893. this._height = height;
  38894. this.domElement.width = Math.floor( width * this._pixelRatio );
  38895. this.domElement.height = Math.floor( height * this._pixelRatio );
  38896. if ( updateStyle === true ) {
  38897. this.domElement.style.width = width + 'px';
  38898. this.domElement.style.height = height + 'px';
  38899. }
  38900. this.setViewport( 0, 0, width, height );
  38901. if ( this._initialized ) this.backend.updateSize();
  38902. }
  38903. setOpaqueSort( method ) {
  38904. this._opaqueSort = method;
  38905. }
  38906. setTransparentSort( method ) {
  38907. this._transparentSort = method;
  38908. }
  38909. getScissor( target ) {
  38910. const scissor = this._scissor;
  38911. target.x = scissor.x;
  38912. target.y = scissor.y;
  38913. target.width = scissor.width;
  38914. target.height = scissor.height;
  38915. return target;
  38916. }
  38917. setScissor( x, y, width, height ) {
  38918. const scissor = this._scissor;
  38919. if ( x.isVector4 ) {
  38920. scissor.copy( x );
  38921. } else {
  38922. scissor.set( x, y, width, height );
  38923. }
  38924. }
  38925. getScissorTest() {
  38926. return this._scissorTest;
  38927. }
  38928. setScissorTest( boolean ) {
  38929. this._scissorTest = boolean;
  38930. this.backend.setScissorTest( boolean );
  38931. }
  38932. getViewport( target ) {
  38933. return target.copy( this._viewport );
  38934. }
  38935. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  38936. const viewport = this._viewport;
  38937. if ( x.isVector4 ) {
  38938. viewport.copy( x );
  38939. } else {
  38940. viewport.set( x, y, width, height );
  38941. }
  38942. viewport.minDepth = minDepth;
  38943. viewport.maxDepth = maxDepth;
  38944. }
  38945. getClearColor( target ) {
  38946. return target.copy( this._clearColor );
  38947. }
  38948. setClearColor( color, alpha = 1 ) {
  38949. this._clearColor.set( color );
  38950. this._clearColor.a = alpha;
  38951. }
  38952. getClearAlpha() {
  38953. return this._clearColor.a;
  38954. }
  38955. setClearAlpha( alpha ) {
  38956. this._clearColor.a = alpha;
  38957. }
  38958. getClearDepth() {
  38959. return this._clearDepth;
  38960. }
  38961. setClearDepth( depth ) {
  38962. this._clearDepth = depth;
  38963. }
  38964. getClearStencil() {
  38965. return this._clearStencil;
  38966. }
  38967. setClearStencil( stencil ) {
  38968. this._clearStencil = stencil;
  38969. }
  38970. isOccluded( object ) {
  38971. const renderContext = this._currentRenderContext;
  38972. return renderContext && this.backend.isOccluded( renderContext, object );
  38973. }
  38974. clear( color = true, depth = true, stencil = true ) {
  38975. if ( this._initialized === false ) {
  38976. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  38977. return this.clearAsync( color, depth, stencil );
  38978. }
  38979. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38980. let renderTargetData = null;
  38981. if ( renderTarget !== null ) {
  38982. this._textures.updateRenderTarget( renderTarget );
  38983. renderTargetData = this._textures.get( renderTarget );
  38984. }
  38985. this.backend.clear( color, depth, stencil, renderTargetData );
  38986. if ( renderTarget !== null && this._renderTarget === null ) {
  38987. // If a color space transform or tone mapping is required,
  38988. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  38989. const quad = this._quad;
  38990. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  38991. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  38992. quad.material.needsUpdate = true;
  38993. }
  38994. this._renderScene( quad, quad.camera, false );
  38995. }
  38996. }
  38997. clearColor() {
  38998. return this.clear( true, false, false );
  38999. }
  39000. clearDepth() {
  39001. return this.clear( false, true, false );
  39002. }
  39003. clearStencil() {
  39004. return this.clear( false, false, true );
  39005. }
  39006. async clearAsync( color = true, depth = true, stencil = true ) {
  39007. if ( this._initialized === false ) await this.init();
  39008. this.clear( color, depth, stencil );
  39009. }
  39010. clearColorAsync() {
  39011. return this.clearAsync( true, false, false );
  39012. }
  39013. clearDepthAsync() {
  39014. return this.clearAsync( false, true, false );
  39015. }
  39016. clearStencilAsync() {
  39017. return this.clearAsync( false, false, true );
  39018. }
  39019. get currentToneMapping() {
  39020. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  39021. }
  39022. get currentColorSpace() {
  39023. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  39024. }
  39025. dispose() {
  39026. this.info.dispose();
  39027. this._animation.dispose();
  39028. this._objects.dispose();
  39029. this._pipelines.dispose();
  39030. this._nodes.dispose();
  39031. this._bindings.dispose();
  39032. this._renderLists.dispose();
  39033. this._renderContexts.dispose();
  39034. this._textures.dispose();
  39035. this.setRenderTarget( null );
  39036. this.setAnimationLoop( null );
  39037. }
  39038. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  39039. this._renderTarget = renderTarget;
  39040. this._activeCubeFace = activeCubeFace;
  39041. this._activeMipmapLevel = activeMipmapLevel;
  39042. }
  39043. getRenderTarget() {
  39044. return this._renderTarget;
  39045. }
  39046. setRenderObjectFunction( renderObjectFunction ) {
  39047. this._renderObjectFunction = renderObjectFunction;
  39048. }
  39049. getRenderObjectFunction() {
  39050. return this._renderObjectFunction;
  39051. }
  39052. async computeAsync( computeNodes ) {
  39053. if ( this._initialized === false ) await this.init();
  39054. const nodeFrame = this._nodes.nodeFrame;
  39055. const previousRenderId = nodeFrame.renderId;
  39056. //
  39057. this.info.calls ++;
  39058. this.info.compute.calls ++;
  39059. this.info.compute.frameCalls ++;
  39060. nodeFrame.renderId = this.info.calls;
  39061. //
  39062. const backend = this.backend;
  39063. const pipelines = this._pipelines;
  39064. const bindings = this._bindings;
  39065. const nodes = this._nodes;
  39066. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  39067. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  39068. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  39069. }
  39070. backend.beginCompute( computeNodes );
  39071. for ( const computeNode of computeList ) {
  39072. // onInit
  39073. if ( pipelines.has( computeNode ) === false ) {
  39074. const dispose = () => {
  39075. computeNode.removeEventListener( 'dispose', dispose );
  39076. pipelines.delete( computeNode );
  39077. bindings.delete( computeNode );
  39078. nodes.delete( computeNode );
  39079. };
  39080. computeNode.addEventListener( 'dispose', dispose );
  39081. //
  39082. computeNode.onInit( { renderer: this } );
  39083. }
  39084. nodes.updateForCompute( computeNode );
  39085. bindings.updateForCompute( computeNode );
  39086. const computeBindings = bindings.getForCompute( computeNode );
  39087. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  39088. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  39089. }
  39090. backend.finishCompute( computeNodes );
  39091. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  39092. //
  39093. nodeFrame.renderId = previousRenderId;
  39094. }
  39095. async hasFeatureAsync( name ) {
  39096. if ( this._initialized === false ) await this.init();
  39097. return this.backend.hasFeature( name );
  39098. }
  39099. hasFeature( name ) {
  39100. if ( this._initialized === false ) {
  39101. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  39102. return false;
  39103. }
  39104. return this.backend.hasFeature( name );
  39105. }
  39106. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  39107. const renderContext = this._currentRenderContext;
  39108. this._textures.updateTexture( framebufferTexture );
  39109. rectangle = rectangle === null ? _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height ) : rectangle;
  39110. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  39111. }
  39112. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  39113. this._textures.updateTexture( srcTexture );
  39114. this._textures.updateTexture( dstTexture );
  39115. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  39116. }
  39117. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  39118. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  39119. }
  39120. _projectObject( object, camera, groupOrder, renderList ) {
  39121. if ( object.visible === false ) return;
  39122. const visible = object.layers.test( camera.layers );
  39123. if ( visible ) {
  39124. if ( object.isGroup ) {
  39125. groupOrder = object.renderOrder;
  39126. } else if ( object.isLOD ) {
  39127. if ( object.autoUpdate === true ) object.update( camera );
  39128. } else if ( object.isLight ) {
  39129. renderList.pushLight( object );
  39130. } else if ( object.isSprite ) {
  39131. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  39132. if ( this.sortObjects === true ) {
  39133. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  39134. }
  39135. const { geometry, material } = object;
  39136. if ( material.visible ) {
  39137. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  39138. }
  39139. }
  39140. } else if ( object.isLineLoop ) {
  39141. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  39142. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  39143. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  39144. const { geometry, material } = object;
  39145. if ( this.sortObjects === true ) {
  39146. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  39147. _vector4
  39148. .copy( geometry.boundingSphere.center )
  39149. .applyMatrix4( object.matrixWorld )
  39150. .applyMatrix4( _projScreenMatrix );
  39151. }
  39152. if ( Array.isArray( material ) ) {
  39153. const groups = geometry.groups;
  39154. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  39155. const group = groups[ i ];
  39156. const groupMaterial = material[ group.materialIndex ];
  39157. if ( groupMaterial && groupMaterial.visible ) {
  39158. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  39159. }
  39160. }
  39161. } else if ( material.visible ) {
  39162. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  39163. }
  39164. }
  39165. }
  39166. }
  39167. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  39168. const baseRenderList = renderList;
  39169. // replace render list
  39170. renderList = this._renderLists.get( object, camera );
  39171. renderList.begin();
  39172. baseRenderList.pushBundle( {
  39173. bundleGroup: object,
  39174. camera,
  39175. renderList,
  39176. } );
  39177. renderList.finish();
  39178. }
  39179. const children = object.children;
  39180. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39181. this._projectObject( children[ i ], camera, groupOrder, renderList );
  39182. }
  39183. }
  39184. _renderBundles( bundles, sceneRef, lightsNode ) {
  39185. for ( const bundle of bundles ) {
  39186. this._renderBundle( bundle, sceneRef, lightsNode );
  39187. }
  39188. }
  39189. _renderObjects( renderList, camera, scene, lightsNode ) {
  39190. // process renderable objects
  39191. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  39192. const renderItem = renderList[ i ];
  39193. // @TODO: Add support for multiple materials per object. This will require to extract
  39194. // the material from the renderItem object and pass it with its group data to renderObject().
  39195. const { object, geometry, material, group } = renderItem;
  39196. if ( camera.isArrayCamera ) {
  39197. const cameras = camera.cameras;
  39198. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  39199. const camera2 = cameras[ j ];
  39200. if ( object.layers.test( camera2.layers ) ) {
  39201. const vp = camera2.viewport;
  39202. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  39203. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  39204. const viewportValue = this._currentRenderContext.viewportValue;
  39205. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  39206. viewportValue.minDepth = minDepth;
  39207. viewportValue.maxDepth = maxDepth;
  39208. this.backend.updateViewport( this._currentRenderContext );
  39209. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  39210. }
  39211. }
  39212. } else {
  39213. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  39214. }
  39215. }
  39216. }
  39217. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  39218. let overridePositionNode;
  39219. let overrideFragmentNode;
  39220. let overrideDepthNode;
  39221. //
  39222. object.onBeforeRender( this, scene, camera, geometry, material, group );
  39223. //
  39224. if ( scene.overrideMaterial !== null ) {
  39225. const overrideMaterial = scene.overrideMaterial;
  39226. if ( material.positionNode && material.positionNode.isNode ) {
  39227. overridePositionNode = overrideMaterial.positionNode;
  39228. overrideMaterial.positionNode = material.positionNode;
  39229. }
  39230. if ( overrideMaterial.isShadowNodeMaterial ) {
  39231. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  39232. if ( material.depthNode && material.depthNode.isNode ) {
  39233. overrideDepthNode = overrideMaterial.depthNode;
  39234. overrideMaterial.depthNode = material.depthNode;
  39235. }
  39236. if ( material.shadowNode && material.shadowNode.isNode ) {
  39237. overrideFragmentNode = overrideMaterial.fragmentNode;
  39238. overrideMaterial.fragmentNode = material.shadowNode;
  39239. }
  39240. if ( this.localClippingEnabled ) {
  39241. if ( material.clipShadows ) {
  39242. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  39243. overrideMaterial.clippingPlanes = material.clippingPlanes;
  39244. overrideMaterial.needsUpdate = true;
  39245. }
  39246. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  39247. overrideMaterial.clipIntersection = material.clipIntersection;
  39248. }
  39249. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  39250. overrideMaterial.clippingPlanes = null;
  39251. overrideMaterial.needsUpdate = true;
  39252. }
  39253. }
  39254. }
  39255. material = overrideMaterial;
  39256. }
  39257. //
  39258. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  39259. material.side = BackSide;
  39260. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  39261. material.side = FrontSide;
  39262. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  39263. material.side = DoubleSide;
  39264. } else {
  39265. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  39266. }
  39267. //
  39268. if ( overridePositionNode !== undefined ) {
  39269. scene.overrideMaterial.positionNode = overridePositionNode;
  39270. }
  39271. if ( overrideDepthNode !== undefined ) {
  39272. scene.overrideMaterial.depthNode = overrideDepthNode;
  39273. }
  39274. if ( overrideFragmentNode !== undefined ) {
  39275. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  39276. }
  39277. //
  39278. object.onAfterRender( this, scene, camera, geometry, material, group );
  39279. }
  39280. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  39281. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  39282. renderObject.drawRange = object.geometry.drawRange;
  39283. renderObject.group = group;
  39284. //
  39285. const needsRefresh = this._nodes.needsRefresh( renderObject );
  39286. if ( needsRefresh ) {
  39287. this._nodes.updateBefore( renderObject );
  39288. this._geometries.updateForRender( renderObject );
  39289. this._nodes.updateForRender( renderObject );
  39290. this._bindings.updateForRender( renderObject );
  39291. }
  39292. this._pipelines.updateForRender( renderObject );
  39293. //
  39294. if ( this._currentRenderBundle !== null ) {
  39295. const renderBundleData = this.backend.get( this._currentRenderBundle );
  39296. renderBundleData.renderObjects.push( renderObject );
  39297. renderObject.bundle = this._currentRenderBundle.scene;
  39298. }
  39299. this.backend.draw( renderObject, this.info );
  39300. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  39301. }
  39302. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  39303. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  39304. //
  39305. this._nodes.updateBefore( renderObject );
  39306. this._geometries.updateForRender( renderObject );
  39307. this._nodes.updateForRender( renderObject );
  39308. this._bindings.updateForRender( renderObject );
  39309. this._pipelines.getForRender( renderObject, this._compilationPromises );
  39310. this._nodes.updateAfter( renderObject );
  39311. }
  39312. get compute() {
  39313. return this.computeAsync;
  39314. }
  39315. get compile() {
  39316. return this.compileAsync;
  39317. }
  39318. }
  39319. class Binding {
  39320. constructor( name = '' ) {
  39321. this.name = name;
  39322. this.visibility = 0;
  39323. }
  39324. setVisibility( visibility ) {
  39325. this.visibility |= visibility;
  39326. }
  39327. clone() {
  39328. return Object.assign( new this.constructor(), this );
  39329. }
  39330. }
  39331. function getFloatLength( floatLength ) {
  39332. // ensure chunk size alignment (STD140 layout)
  39333. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  39334. }
  39335. class Buffer extends Binding {
  39336. constructor( name, buffer = null ) {
  39337. super( name );
  39338. this.isBuffer = true;
  39339. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  39340. this._buffer = buffer;
  39341. }
  39342. get byteLength() {
  39343. return getFloatLength( this._buffer.byteLength );
  39344. }
  39345. get buffer() {
  39346. return this._buffer;
  39347. }
  39348. update() {
  39349. return true;
  39350. }
  39351. }
  39352. class UniformBuffer extends Buffer {
  39353. constructor( name, buffer = null ) {
  39354. super( name, buffer );
  39355. this.isUniformBuffer = true;
  39356. }
  39357. }
  39358. let _id$4 = 0;
  39359. class NodeUniformBuffer extends UniformBuffer {
  39360. constructor( nodeUniform, groupNode ) {
  39361. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  39362. this.nodeUniform = nodeUniform;
  39363. this.groupNode = groupNode;
  39364. }
  39365. get buffer() {
  39366. return this.nodeUniform.value;
  39367. }
  39368. }
  39369. class UniformsGroup extends UniformBuffer {
  39370. constructor( name ) {
  39371. super( name );
  39372. this.isUniformsGroup = true;
  39373. this._values = null;
  39374. // the order of uniforms in this array must match the order of uniforms in the shader
  39375. this.uniforms = [];
  39376. }
  39377. addUniform( uniform ) {
  39378. this.uniforms.push( uniform );
  39379. return this;
  39380. }
  39381. removeUniform( uniform ) {
  39382. const index = this.uniforms.indexOf( uniform );
  39383. if ( index !== - 1 ) {
  39384. this.uniforms.splice( index, 1 );
  39385. }
  39386. return this;
  39387. }
  39388. get values() {
  39389. if ( this._values === null ) {
  39390. this._values = Array.from( this.buffer );
  39391. }
  39392. return this._values;
  39393. }
  39394. get buffer() {
  39395. let buffer = this._buffer;
  39396. if ( buffer === null ) {
  39397. const byteLength = this.byteLength;
  39398. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  39399. this._buffer = buffer;
  39400. }
  39401. return buffer;
  39402. }
  39403. get byteLength() {
  39404. let offset = 0; // global buffer offset in bytes
  39405. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  39406. const uniform = this.uniforms[ i ];
  39407. const { boundary, itemSize } = uniform;
  39408. // offset within a single chunk in bytes
  39409. const chunkOffset = offset % GPU_CHUNK_BYTES;
  39410. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  39411. // conformance tests
  39412. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  39413. // check for chunk overflow
  39414. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  39415. } else if ( chunkOffset % boundary !== 0 ) {
  39416. // check for correct alignment
  39417. offset += ( chunkOffset % boundary );
  39418. }
  39419. uniform.offset = ( offset / this.bytesPerElement );
  39420. offset += ( itemSize * this.bytesPerElement );
  39421. }
  39422. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  39423. }
  39424. update() {
  39425. let updated = false;
  39426. for ( const uniform of this.uniforms ) {
  39427. if ( this.updateByType( uniform ) === true ) {
  39428. updated = true;
  39429. }
  39430. }
  39431. return updated;
  39432. }
  39433. updateByType( uniform ) {
  39434. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  39435. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  39436. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  39437. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  39438. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  39439. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  39440. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  39441. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  39442. }
  39443. updateNumber( uniform ) {
  39444. let updated = false;
  39445. const a = this.values;
  39446. const v = uniform.getValue();
  39447. const offset = uniform.offset;
  39448. if ( a[ offset ] !== v ) {
  39449. const b = this.buffer;
  39450. b[ offset ] = a[ offset ] = v;
  39451. updated = true;
  39452. }
  39453. return updated;
  39454. }
  39455. updateVector2( uniform ) {
  39456. let updated = false;
  39457. const a = this.values;
  39458. const v = uniform.getValue();
  39459. const offset = uniform.offset;
  39460. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  39461. const b = this.buffer;
  39462. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39463. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39464. updated = true;
  39465. }
  39466. return updated;
  39467. }
  39468. updateVector3( uniform ) {
  39469. let updated = false;
  39470. const a = this.values;
  39471. const v = uniform.getValue();
  39472. const offset = uniform.offset;
  39473. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  39474. const b = this.buffer;
  39475. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39476. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39477. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  39478. updated = true;
  39479. }
  39480. return updated;
  39481. }
  39482. updateVector4( uniform ) {
  39483. let updated = false;
  39484. const a = this.values;
  39485. const v = uniform.getValue();
  39486. const offset = uniform.offset;
  39487. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  39488. const b = this.buffer;
  39489. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39490. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39491. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  39492. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  39493. updated = true;
  39494. }
  39495. return updated;
  39496. }
  39497. updateColor( uniform ) {
  39498. let updated = false;
  39499. const a = this.values;
  39500. const c = uniform.getValue();
  39501. const offset = uniform.offset;
  39502. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  39503. const b = this.buffer;
  39504. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  39505. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  39506. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  39507. updated = true;
  39508. }
  39509. return updated;
  39510. }
  39511. updateMatrix3( uniform ) {
  39512. let updated = false;
  39513. const a = this.values;
  39514. const e = uniform.getValue().elements;
  39515. const offset = uniform.offset;
  39516. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  39517. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  39518. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  39519. const b = this.buffer;
  39520. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  39521. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  39522. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  39523. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  39524. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  39525. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  39526. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  39527. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  39528. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  39529. updated = true;
  39530. }
  39531. return updated;
  39532. }
  39533. updateMatrix4( uniform ) {
  39534. let updated = false;
  39535. const a = this.values;
  39536. const e = uniform.getValue().elements;
  39537. const offset = uniform.offset;
  39538. if ( arraysEqual( a, e, offset ) === false ) {
  39539. const b = this.buffer;
  39540. b.set( e, offset );
  39541. setArray( a, e, offset );
  39542. updated = true;
  39543. }
  39544. return updated;
  39545. }
  39546. }
  39547. function setArray( a, b, offset ) {
  39548. for ( let i = 0, l = b.length; i < l; i ++ ) {
  39549. a[ offset + i ] = b[ i ];
  39550. }
  39551. }
  39552. function arraysEqual( a, b, offset ) {
  39553. for ( let i = 0, l = b.length; i < l; i ++ ) {
  39554. if ( a[ offset + i ] !== b[ i ] ) return false;
  39555. }
  39556. return true;
  39557. }
  39558. let _id$3 = 0;
  39559. class NodeUniformsGroup extends UniformsGroup {
  39560. constructor( name, groupNode ) {
  39561. super( name );
  39562. this.id = _id$3 ++;
  39563. this.groupNode = groupNode;
  39564. this.isNodeUniformsGroup = true;
  39565. }
  39566. getNodes() {
  39567. const nodes = [];
  39568. for ( const uniform of this.uniforms ) {
  39569. const node = uniform.nodeUniform.node;
  39570. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  39571. nodes.push( node );
  39572. }
  39573. return nodes;
  39574. }
  39575. }
  39576. let _id$2 = 0;
  39577. class SampledTexture extends Binding {
  39578. constructor( name, texture ) {
  39579. super( name );
  39580. this.id = _id$2 ++;
  39581. this.texture = texture;
  39582. this.version = texture ? texture.version : 0;
  39583. this.store = false;
  39584. this.generation = null;
  39585. this.isSampledTexture = true;
  39586. }
  39587. needsBindingsUpdate( generation ) {
  39588. const { texture } = this;
  39589. if ( generation !== this.generation ) {
  39590. this.generation = generation;
  39591. return true;
  39592. }
  39593. return texture.isVideoTexture;
  39594. }
  39595. update() {
  39596. const { texture, version } = this;
  39597. if ( version !== texture.version ) {
  39598. this.version = texture.version;
  39599. return true;
  39600. }
  39601. return false;
  39602. }
  39603. }
  39604. class NodeSampledTexture extends SampledTexture {
  39605. constructor( name, textureNode, groupNode, access = null ) {
  39606. super( name, textureNode ? textureNode.value : null );
  39607. this.textureNode = textureNode;
  39608. this.groupNode = groupNode;
  39609. this.access = access;
  39610. }
  39611. needsBindingsUpdate( generation ) {
  39612. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  39613. }
  39614. update() {
  39615. const { textureNode } = this;
  39616. if ( this.texture !== textureNode.value ) {
  39617. this.texture = textureNode.value;
  39618. return true;
  39619. }
  39620. return super.update();
  39621. }
  39622. }
  39623. class NodeSampledCubeTexture extends NodeSampledTexture {
  39624. constructor( name, textureNode, groupNode, access ) {
  39625. super( name, textureNode, groupNode, access );
  39626. this.isSampledCubeTexture = true;
  39627. }
  39628. }
  39629. class NodeSampledTexture3D extends NodeSampledTexture {
  39630. constructor( name, textureNode, groupNode, access ) {
  39631. super( name, textureNode, groupNode, access );
  39632. this.isSampledTexture3D = true;
  39633. }
  39634. }
  39635. const glslMethods = {
  39636. atan2: 'atan',
  39637. textureDimensions: 'textureSize',
  39638. equals: 'equal'
  39639. };
  39640. const precisionLib = {
  39641. low: 'lowp',
  39642. medium: 'mediump',
  39643. high: 'highp'
  39644. };
  39645. const supports$1 = {
  39646. swizzleAssign: true,
  39647. storageBuffer: false
  39648. };
  39649. const defaultPrecisions = `
  39650. precision highp float;
  39651. precision highp int;
  39652. precision highp sampler2D;
  39653. precision highp sampler3D;
  39654. precision highp samplerCube;
  39655. precision highp sampler2DArray;
  39656. precision highp usampler2D;
  39657. precision highp usampler3D;
  39658. precision highp usamplerCube;
  39659. precision highp usampler2DArray;
  39660. precision highp isampler2D;
  39661. precision highp isampler3D;
  39662. precision highp isamplerCube;
  39663. precision highp isampler2DArray;
  39664. precision lowp sampler2DShadow;
  39665. `;
  39666. class GLSLNodeBuilder extends NodeBuilder {
  39667. constructor( object, renderer ) {
  39668. super( object, renderer, new GLSLNodeParser() );
  39669. this.uniformGroups = {};
  39670. this.transforms = [];
  39671. this.extensions = {};
  39672. this.useComparisonMethod = true;
  39673. }
  39674. needsColorSpaceToLinearSRGB( texture ) {
  39675. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  39676. }
  39677. getMethod( method ) {
  39678. return glslMethods[ method ] || method;
  39679. }
  39680. getOutputStructName() {
  39681. return '';
  39682. }
  39683. buildFunctionCode( shaderNode ) {
  39684. const layout = shaderNode.layout;
  39685. const flowData = this.flowShaderNode( shaderNode );
  39686. const parameters = [];
  39687. for ( const input of layout.inputs ) {
  39688. parameters.push( this.getType( input.type ) + ' ' + input.name );
  39689. }
  39690. //
  39691. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  39692. ${ flowData.vars }
  39693. ${ flowData.code }
  39694. return ${ flowData.result };
  39695. }`;
  39696. //
  39697. return code;
  39698. }
  39699. setupPBO( storageBufferNode ) {
  39700. const attribute = storageBufferNode.value;
  39701. if ( attribute.pbo === undefined ) {
  39702. const originalArray = attribute.array;
  39703. const numElements = attribute.count * attribute.itemSize;
  39704. const { itemSize } = attribute;
  39705. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  39706. let format = isInteger ? RedIntegerFormat : RedFormat;
  39707. if ( itemSize === 2 ) {
  39708. format = isInteger ? RGIntegerFormat : RGFormat;
  39709. } else if ( itemSize === 3 ) {
  39710. format = isInteger ? RGBIntegerFormat : RGBFormat;
  39711. } else if ( itemSize === 4 ) {
  39712. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  39713. }
  39714. const typeMap = {
  39715. Float32Array: FloatType,
  39716. Uint8Array: UnsignedByteType,
  39717. Uint16Array: UnsignedShortType,
  39718. Uint32Array: UnsignedIntType,
  39719. Int8Array: ByteType,
  39720. Int16Array: ShortType,
  39721. Int32Array: IntType,
  39722. Uint8ClampedArray: UnsignedByteType,
  39723. };
  39724. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  39725. let height = Math.ceil( ( numElements / itemSize ) / width );
  39726. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  39727. const newSize = width * height * itemSize;
  39728. const newArray = new originalArray.constructor( newSize );
  39729. newArray.set( originalArray, 0 );
  39730. attribute.array = newArray;
  39731. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  39732. pboTexture.needsUpdate = true;
  39733. pboTexture.isPBOTexture = true;
  39734. const pbo = new TextureNode( pboTexture, null, null );
  39735. pbo.setPrecision( 'high' );
  39736. attribute.pboNode = pbo;
  39737. attribute.pbo = pbo.value;
  39738. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39739. }
  39740. }
  39741. getPropertyName( node, shaderStage = this.shaderStage ) {
  39742. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  39743. return shaderStage.charAt( 0 ) + '_' + node.name;
  39744. }
  39745. return super.getPropertyName( node, shaderStage );
  39746. }
  39747. generatePBO( storageArrayElementNode ) {
  39748. const { node, indexNode } = storageArrayElementNode;
  39749. const attribute = node.value;
  39750. if ( this.renderer.backend.has( attribute ) ) {
  39751. const attributeData = this.renderer.backend.get( attribute );
  39752. attributeData.pbo = attribute.pbo;
  39753. }
  39754. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39755. const textureName = this.getPropertyName( nodeUniform );
  39756. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  39757. const indexSnippet = indexNode.build( this, 'uint' );
  39758. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  39759. let propertyName = elementNodeData.propertyName;
  39760. if ( propertyName === undefined ) {
  39761. // property element
  39762. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  39763. propertyName = this.getPropertyName( nodeVar );
  39764. // property size
  39765. const bufferNodeData = this.getDataFromNode( node );
  39766. let propertySizeName = bufferNodeData.propertySizeName;
  39767. if ( propertySizeName === undefined ) {
  39768. propertySizeName = propertyName + 'Size';
  39769. this.getVarFromNode( node, propertySizeName, 'uint' );
  39770. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` );
  39771. bufferNodeData.propertySizeName = propertySizeName;
  39772. }
  39773. //
  39774. const { itemSize } = attribute;
  39775. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  39776. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  39777. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  39778. //
  39779. let prefix = 'vec4';
  39780. if ( attribute.pbo.type === UnsignedIntType ) {
  39781. prefix = 'uvec4';
  39782. } else if ( attribute.pbo.type === IntType ) {
  39783. prefix = 'ivec4';
  39784. }
  39785. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}` );
  39786. elementNodeData.propertyName = propertyName;
  39787. }
  39788. return propertyName;
  39789. }
  39790. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  39791. if ( depthSnippet ) {
  39792. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  39793. } else {
  39794. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  39795. }
  39796. }
  39797. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  39798. if ( texture.isDepthTexture ) {
  39799. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  39800. } else {
  39801. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  39802. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  39803. }
  39804. }
  39805. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  39806. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  39807. }
  39808. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  39809. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  39810. }
  39811. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  39812. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  39813. }
  39814. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  39815. if ( shaderStage === 'fragment' ) {
  39816. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  39817. } else {
  39818. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  39819. }
  39820. }
  39821. getVars( shaderStage ) {
  39822. const snippets = [];
  39823. const vars = this.vars[ shaderStage ];
  39824. if ( vars !== undefined ) {
  39825. for ( const variable of vars ) {
  39826. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  39827. }
  39828. }
  39829. return snippets.join( '\n\t' );
  39830. }
  39831. getUniforms( shaderStage ) {
  39832. const uniforms = this.uniforms[ shaderStage ];
  39833. const bindingSnippets = [];
  39834. const uniformGroups = {};
  39835. for ( const uniform of uniforms ) {
  39836. let snippet = null;
  39837. let group = false;
  39838. if ( uniform.type === 'texture' ) {
  39839. const texture = uniform.node.value;
  39840. let typePrefix = '';
  39841. if ( texture.isDataTexture === true ) {
  39842. if ( texture.type === UnsignedIntType ) {
  39843. typePrefix = 'u';
  39844. } else if ( texture.type === IntType ) {
  39845. typePrefix = 'i';
  39846. }
  39847. }
  39848. if ( texture.compareFunction ) {
  39849. snippet = `sampler2DShadow ${ uniform.name };`;
  39850. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39851. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  39852. } else {
  39853. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  39854. }
  39855. } else if ( uniform.type === 'cubeTexture' ) {
  39856. snippet = `samplerCube ${ uniform.name };`;
  39857. } else if ( uniform.type === 'texture3D' ) {
  39858. snippet = `sampler3D ${ uniform.name };`;
  39859. } else if ( uniform.type === 'buffer' ) {
  39860. const bufferNode = uniform.node;
  39861. const bufferType = this.getType( bufferNode.bufferType );
  39862. const bufferCount = bufferNode.bufferCount;
  39863. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  39864. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  39865. } else {
  39866. const vectorType = this.getVectorType( uniform.type );
  39867. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  39868. group = true;
  39869. }
  39870. const precision = uniform.node.precision;
  39871. if ( precision !== null ) {
  39872. snippet = precisionLib[ precision ] + ' ' + snippet;
  39873. }
  39874. if ( group ) {
  39875. snippet = '\t' + snippet;
  39876. const groupName = uniform.groupNode.name;
  39877. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  39878. groupSnippets.push( snippet );
  39879. } else {
  39880. snippet = 'uniform ' + snippet;
  39881. bindingSnippets.push( snippet );
  39882. }
  39883. }
  39884. let output = '';
  39885. for ( const name in uniformGroups ) {
  39886. const groupSnippets = uniformGroups[ name ];
  39887. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  39888. }
  39889. output += bindingSnippets.join( '\n' );
  39890. return output;
  39891. }
  39892. getTypeFromAttribute( attribute ) {
  39893. let nodeType = super.getTypeFromAttribute( attribute );
  39894. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  39895. let dataAttribute = attribute;
  39896. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  39897. const array = dataAttribute.array;
  39898. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  39899. nodeType = nodeType.slice( 1 );
  39900. }
  39901. }
  39902. return nodeType;
  39903. }
  39904. getAttributes( shaderStage ) {
  39905. let snippet = '';
  39906. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39907. const attributes = this.getAttributesArray();
  39908. let location = 0;
  39909. for ( const attribute of attributes ) {
  39910. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  39911. }
  39912. }
  39913. return snippet;
  39914. }
  39915. getStructMembers( struct ) {
  39916. const snippets = [];
  39917. const members = struct.getMemberTypes();
  39918. for ( let i = 0; i < members.length; i ++ ) {
  39919. const member = members[ i ];
  39920. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  39921. }
  39922. return snippets.join( '\n' );
  39923. }
  39924. getStructs( shaderStage ) {
  39925. const snippets = [];
  39926. const structs = this.structs[ shaderStage ];
  39927. if ( structs.length === 0 ) {
  39928. return 'layout( location = 0 ) out vec4 fragColor;\n';
  39929. }
  39930. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  39931. const struct = structs[ index ];
  39932. let snippet = '\n';
  39933. snippet += this.getStructMembers( struct );
  39934. snippet += '\n';
  39935. snippets.push( snippet );
  39936. }
  39937. return snippets.join( '\n\n' );
  39938. }
  39939. getVaryings( shaderStage ) {
  39940. let snippet = '';
  39941. const varyings = this.varyings;
  39942. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39943. for ( const varying of varyings ) {
  39944. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  39945. const type = varying.type;
  39946. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39947. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  39948. }
  39949. } else if ( shaderStage === 'fragment' ) {
  39950. for ( const varying of varyings ) {
  39951. if ( varying.needsInterpolation ) {
  39952. const type = varying.type;
  39953. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39954. snippet += `${flat}in ${type} ${varying.name};\n`;
  39955. }
  39956. }
  39957. }
  39958. return snippet;
  39959. }
  39960. getVertexIndex() {
  39961. return 'uint( gl_VertexID )';
  39962. }
  39963. getInstanceIndex() {
  39964. return 'uint( gl_InstanceID )';
  39965. }
  39966. getInvocationLocalIndex() {
  39967. const workgroupSize = this.object.workgroupSize;
  39968. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  39969. return `uint( gl_InstanceID ) % ${size}u`;
  39970. }
  39971. getDrawIndex() {
  39972. const extensions = this.renderer.backend.extensions;
  39973. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  39974. return 'uint( gl_DrawID )';
  39975. }
  39976. return null;
  39977. }
  39978. getFrontFacing() {
  39979. return 'gl_FrontFacing';
  39980. }
  39981. getFragCoord() {
  39982. return 'gl_FragCoord.xy';
  39983. }
  39984. getFragDepth() {
  39985. return 'gl_FragDepth';
  39986. }
  39987. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  39988. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  39989. if ( map.has( name ) === false ) {
  39990. map.set( name, {
  39991. name,
  39992. behavior
  39993. } );
  39994. }
  39995. }
  39996. getExtensions( shaderStage ) {
  39997. const snippets = [];
  39998. if ( shaderStage === 'vertex' ) {
  39999. const ext = this.renderer.backend.extensions;
  40000. const isBatchedMesh = this.object.isBatchedMesh;
  40001. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  40002. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  40003. }
  40004. }
  40005. const extensions = this.extensions[ shaderStage ];
  40006. if ( extensions !== undefined ) {
  40007. for ( const { name, behavior } of extensions.values() ) {
  40008. snippets.push( `#extension ${name} : ${behavior}` );
  40009. }
  40010. }
  40011. return snippets.join( '\n' );
  40012. }
  40013. isAvailable( name ) {
  40014. let result = supports$1[ name ];
  40015. if ( result === undefined ) {
  40016. if ( name === 'float32Filterable' ) {
  40017. const extensions = this.renderer.backend.extensions;
  40018. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  40019. extensions.get( 'OES_texture_float_linear' );
  40020. result = true;
  40021. } else {
  40022. result = false;
  40023. }
  40024. }
  40025. supports$1[ name ] = result;
  40026. }
  40027. return result;
  40028. }
  40029. isFlipY() {
  40030. return true;
  40031. }
  40032. registerTransform( varyingName, attributeNode ) {
  40033. this.transforms.push( { varyingName, attributeNode } );
  40034. }
  40035. getTransforms( /* shaderStage */ ) {
  40036. const transforms = this.transforms;
  40037. let snippet = '';
  40038. for ( let i = 0; i < transforms.length; i ++ ) {
  40039. const transform = transforms[ i ];
  40040. const attributeName = this.getPropertyName( transform.attributeNode );
  40041. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  40042. }
  40043. return snippet;
  40044. }
  40045. _getGLSLUniformStruct( name, vars ) {
  40046. return `
  40047. layout( std140 ) uniform ${name} {
  40048. ${vars}
  40049. };`;
  40050. }
  40051. _getGLSLVertexCode( shaderData ) {
  40052. return `#version 300 es
  40053. ${ this.getSignature() }
  40054. // extensions
  40055. ${shaderData.extensions}
  40056. // precision
  40057. ${ defaultPrecisions }
  40058. // uniforms
  40059. ${shaderData.uniforms}
  40060. // varyings
  40061. ${shaderData.varyings}
  40062. // attributes
  40063. ${shaderData.attributes}
  40064. // codes
  40065. ${shaderData.codes}
  40066. void main() {
  40067. // vars
  40068. ${shaderData.vars}
  40069. // transforms
  40070. ${shaderData.transforms}
  40071. // flow
  40072. ${shaderData.flow}
  40073. gl_PointSize = 1.0;
  40074. }
  40075. `;
  40076. }
  40077. _getGLSLFragmentCode( shaderData ) {
  40078. return `#version 300 es
  40079. ${ this.getSignature() }
  40080. // precision
  40081. ${ defaultPrecisions }
  40082. // uniforms
  40083. ${shaderData.uniforms}
  40084. // varyings
  40085. ${shaderData.varyings}
  40086. // codes
  40087. ${shaderData.codes}
  40088. ${shaderData.structs}
  40089. void main() {
  40090. // vars
  40091. ${shaderData.vars}
  40092. // flow
  40093. ${shaderData.flow}
  40094. }
  40095. `;
  40096. }
  40097. buildCode() {
  40098. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  40099. this.sortBindingGroups();
  40100. for ( const shaderStage in shadersData ) {
  40101. let flow = '// code\n\n';
  40102. flow += this.flowCode[ shaderStage ];
  40103. const flowNodes = this.flowNodes[ shaderStage ];
  40104. const mainNode = flowNodes[ flowNodes.length - 1 ];
  40105. for ( const node of flowNodes ) {
  40106. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  40107. const slotName = node.name;
  40108. if ( slotName ) {
  40109. if ( flow.length > 0 ) flow += '\n';
  40110. flow += `\t// flow -> ${ slotName }\n\t`;
  40111. }
  40112. flow += `${ flowSlotData.code }\n\t`;
  40113. if ( node === mainNode && shaderStage !== 'compute' ) {
  40114. flow += '// result\n\t';
  40115. if ( shaderStage === 'vertex' ) {
  40116. flow += 'gl_Position = ';
  40117. flow += `${ flowSlotData.result };`;
  40118. } else if ( shaderStage === 'fragment' ) {
  40119. if ( ! node.outputNode.isOutputStructNode ) {
  40120. flow += 'fragColor = ';
  40121. flow += `${ flowSlotData.result };`;
  40122. }
  40123. }
  40124. }
  40125. }
  40126. const stageData = shadersData[ shaderStage ];
  40127. stageData.extensions = this.getExtensions( shaderStage );
  40128. stageData.uniforms = this.getUniforms( shaderStage );
  40129. stageData.attributes = this.getAttributes( shaderStage );
  40130. stageData.varyings = this.getVaryings( shaderStage );
  40131. stageData.vars = this.getVars( shaderStage );
  40132. stageData.structs = this.getStructs( shaderStage );
  40133. stageData.codes = this.getCodes( shaderStage );
  40134. stageData.transforms = this.getTransforms( shaderStage );
  40135. stageData.flow = flow;
  40136. }
  40137. if ( this.material !== null ) {
  40138. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  40139. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  40140. } else {
  40141. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  40142. }
  40143. }
  40144. getUniformFromNode( node, type, shaderStage, name = null ) {
  40145. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  40146. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  40147. let uniformGPU = nodeData.uniformGPU;
  40148. if ( uniformGPU === undefined ) {
  40149. const group = node.groupNode;
  40150. const groupName = group.name;
  40151. const bindings = this.getBindGroupArray( groupName, shaderStage );
  40152. if ( type === 'texture' ) {
  40153. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  40154. bindings.push( uniformGPU );
  40155. } else if ( type === 'cubeTexture' ) {
  40156. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  40157. bindings.push( uniformGPU );
  40158. } else if ( type === 'texture3D' ) {
  40159. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  40160. bindings.push( uniformGPU );
  40161. } else if ( type === 'buffer' ) {
  40162. node.name = `NodeBuffer_${ node.id }`;
  40163. uniformNode.name = `buffer${ node.id }`;
  40164. const buffer = new NodeUniformBuffer( node, group );
  40165. buffer.name = node.name;
  40166. bindings.push( buffer );
  40167. uniformGPU = buffer;
  40168. } else {
  40169. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  40170. let uniformsGroup = uniformsStage[ groupName ];
  40171. if ( uniformsGroup === undefined ) {
  40172. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  40173. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  40174. uniformsStage[ groupName ] = uniformsGroup;
  40175. bindings.push( uniformsGroup );
  40176. }
  40177. uniformGPU = this.getNodeUniform( uniformNode, type );
  40178. uniformsGroup.addUniform( uniformGPU );
  40179. }
  40180. nodeData.uniformGPU = uniformGPU;
  40181. }
  40182. return uniformNode;
  40183. }
  40184. }
  40185. let vector2 = null;
  40186. let vector4 = null;
  40187. let color4 = null;
  40188. class Backend {
  40189. constructor( parameters = {} ) {
  40190. this.parameters = Object.assign( {}, parameters );
  40191. this.data = new WeakMap();
  40192. this.renderer = null;
  40193. this.domElement = null;
  40194. }
  40195. async init( renderer ) {
  40196. this.renderer = renderer;
  40197. }
  40198. // render context
  40199. begin( /*renderContext*/ ) { }
  40200. finish( /*renderContext*/ ) { }
  40201. // render object
  40202. draw( /*renderObject, info*/ ) { }
  40203. // program
  40204. createProgram( /*program*/ ) { }
  40205. destroyProgram( /*program*/ ) { }
  40206. // bindings
  40207. createBindings( /*bingGroup, bindings*/ ) { }
  40208. updateBindings( /*bingGroup, bindings*/ ) { }
  40209. // pipeline
  40210. createRenderPipeline( /*renderObject*/ ) { }
  40211. createComputePipeline( /*computeNode, pipeline*/ ) { }
  40212. destroyPipeline( /*pipeline*/ ) { }
  40213. // cache key
  40214. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  40215. getRenderCacheKey( /*renderObject*/ ) { } // return String
  40216. // node builder
  40217. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  40218. // textures
  40219. createSampler( /*texture*/ ) { }
  40220. createDefaultTexture( /*texture*/ ) { }
  40221. createTexture( /*texture*/ ) { }
  40222. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  40223. // attributes
  40224. createAttribute( /*attribute*/ ) { }
  40225. createIndexAttribute( /*attribute*/ ) { }
  40226. updateAttribute( /*attribute*/ ) { }
  40227. destroyAttribute( /*attribute*/ ) { }
  40228. // canvas
  40229. getContext() { }
  40230. updateSize() { }
  40231. // utils
  40232. resolveTimestampAsync( /*renderContext, type*/ ) { }
  40233. hasFeatureAsync( /*name*/ ) { } // return Boolean
  40234. hasFeature( /*name*/ ) { } // return Boolean
  40235. getInstanceCount( renderObject ) {
  40236. const { object, geometry } = renderObject;
  40237. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  40238. }
  40239. getDrawingBufferSize() {
  40240. vector2 = vector2 || new Vector2();
  40241. return this.renderer.getDrawingBufferSize( vector2 );
  40242. }
  40243. getScissor() {
  40244. vector4 = vector4 || new Vector4();
  40245. return this.renderer.getScissor( vector4 );
  40246. }
  40247. setScissorTest( /*boolean*/ ) { }
  40248. getClearColor() {
  40249. const renderer = this.renderer;
  40250. color4 = color4 || new Color4();
  40251. renderer.getClearColor( color4 );
  40252. color4.getRGB( color4, this.renderer.currentColorSpace );
  40253. return color4;
  40254. }
  40255. getDomElement() {
  40256. let domElement = this.domElement;
  40257. if ( domElement === null ) {
  40258. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  40259. // OffscreenCanvas does not have setAttribute, see #22811
  40260. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  40261. this.domElement = domElement;
  40262. }
  40263. return domElement;
  40264. }
  40265. // resource properties
  40266. set( object, value ) {
  40267. this.data.set( object, value );
  40268. }
  40269. get( object ) {
  40270. let map = this.data.get( object );
  40271. if ( map === undefined ) {
  40272. map = {};
  40273. this.data.set( object, map );
  40274. }
  40275. return map;
  40276. }
  40277. has( object ) {
  40278. return this.data.has( object );
  40279. }
  40280. delete( object ) {
  40281. this.data.delete( object );
  40282. }
  40283. }
  40284. let _id$1 = 0;
  40285. class DualAttributeData {
  40286. constructor( attributeData, dualBuffer ) {
  40287. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  40288. this.type = attributeData.type;
  40289. this.bufferType = attributeData.bufferType;
  40290. this.pbo = attributeData.pbo;
  40291. this.byteLength = attributeData.byteLength;
  40292. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  40293. this.version = attributeData.version;
  40294. this.isInteger = attributeData.isInteger;
  40295. this.activeBufferIndex = 0;
  40296. this.baseId = attributeData.id;
  40297. }
  40298. get id() {
  40299. return `${ this.baseId }|${ this.activeBufferIndex }`;
  40300. }
  40301. get bufferGPU() {
  40302. return this.buffers[ this.activeBufferIndex ];
  40303. }
  40304. get transformBuffer() {
  40305. return this.buffers[ this.activeBufferIndex ^ 1 ];
  40306. }
  40307. switchBuffers() {
  40308. this.activeBufferIndex ^= 1;
  40309. }
  40310. }
  40311. class WebGLAttributeUtils {
  40312. constructor( backend ) {
  40313. this.backend = backend;
  40314. }
  40315. createAttribute( attribute, bufferType ) {
  40316. const backend = this.backend;
  40317. const { gl } = backend;
  40318. const array = attribute.array;
  40319. const usage = attribute.usage || gl.STATIC_DRAW;
  40320. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  40321. const bufferData = backend.get( bufferAttribute );
  40322. let bufferGPU = bufferData.bufferGPU;
  40323. if ( bufferGPU === undefined ) {
  40324. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  40325. bufferData.bufferGPU = bufferGPU;
  40326. bufferData.bufferType = bufferType;
  40327. bufferData.version = bufferAttribute.version;
  40328. }
  40329. //attribute.onUploadCallback();
  40330. let type;
  40331. if ( array instanceof Float32Array ) {
  40332. type = gl.FLOAT;
  40333. } else if ( array instanceof Uint16Array ) {
  40334. if ( attribute.isFloat16BufferAttribute ) {
  40335. type = gl.HALF_FLOAT;
  40336. } else {
  40337. type = gl.UNSIGNED_SHORT;
  40338. }
  40339. } else if ( array instanceof Int16Array ) {
  40340. type = gl.SHORT;
  40341. } else if ( array instanceof Uint32Array ) {
  40342. type = gl.UNSIGNED_INT;
  40343. } else if ( array instanceof Int32Array ) {
  40344. type = gl.INT;
  40345. } else if ( array instanceof Int8Array ) {
  40346. type = gl.BYTE;
  40347. } else if ( array instanceof Uint8Array ) {
  40348. type = gl.UNSIGNED_BYTE;
  40349. } else if ( array instanceof Uint8ClampedArray ) {
  40350. type = gl.UNSIGNED_BYTE;
  40351. } else {
  40352. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  40353. }
  40354. let attributeData = {
  40355. bufferGPU,
  40356. bufferType,
  40357. type,
  40358. byteLength: array.byteLength,
  40359. bytesPerElement: array.BYTES_PER_ELEMENT,
  40360. version: attribute.version,
  40361. pbo: attribute.pbo,
  40362. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  40363. id: _id$1 ++
  40364. };
  40365. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  40366. // create buffer for tranform feedback use
  40367. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  40368. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  40369. }
  40370. backend.set( attribute, attributeData );
  40371. }
  40372. updateAttribute( attribute ) {
  40373. const backend = this.backend;
  40374. const { gl } = backend;
  40375. const array = attribute.array;
  40376. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  40377. const bufferData = backend.get( bufferAttribute );
  40378. const bufferType = bufferData.bufferType;
  40379. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  40380. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  40381. if ( updateRanges.length === 0 ) {
  40382. // Not using update ranges
  40383. gl.bufferSubData( bufferType, 0, array );
  40384. } else {
  40385. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  40386. const range = updateRanges[ i ];
  40387. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  40388. array, range.start, range.count );
  40389. }
  40390. bufferAttribute.clearUpdateRanges();
  40391. }
  40392. gl.bindBuffer( bufferType, null );
  40393. bufferData.version = bufferAttribute.version;
  40394. }
  40395. destroyAttribute( attribute ) {
  40396. const backend = this.backend;
  40397. const { gl } = backend;
  40398. if ( attribute.isInterleavedBufferAttribute ) {
  40399. backend.delete( attribute.data );
  40400. }
  40401. const attributeData = backend.get( attribute );
  40402. gl.deleteBuffer( attributeData.bufferGPU );
  40403. backend.delete( attribute );
  40404. }
  40405. async getArrayBufferAsync( attribute ) {
  40406. const backend = this.backend;
  40407. const { gl } = backend;
  40408. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  40409. const { bufferGPU } = backend.get( bufferAttribute );
  40410. const array = attribute.array;
  40411. const byteLength = array.byteLength;
  40412. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  40413. const writeBuffer = gl.createBuffer();
  40414. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  40415. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  40416. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  40417. await backend.utils._clientWaitAsync();
  40418. const dstBuffer = new attribute.array.constructor( array.length );
  40419. // Ensure the buffer is bound before reading
  40420. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  40421. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  40422. gl.deleteBuffer( writeBuffer );
  40423. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  40424. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  40425. return dstBuffer.buffer;
  40426. }
  40427. _createBuffer( gl, bufferType, array, usage ) {
  40428. const bufferGPU = gl.createBuffer();
  40429. gl.bindBuffer( bufferType, bufferGPU );
  40430. gl.bufferData( bufferType, array, usage );
  40431. gl.bindBuffer( bufferType, null );
  40432. return bufferGPU;
  40433. }
  40434. }
  40435. let initialized$1 = false, equationToGL, factorToGL;
  40436. class WebGLState {
  40437. constructor( backend ) {
  40438. this.backend = backend;
  40439. this.gl = this.backend.gl;
  40440. this.enabled = {};
  40441. this.currentFlipSided = null;
  40442. this.currentCullFace = null;
  40443. this.currentProgram = null;
  40444. this.currentBlendingEnabled = false;
  40445. this.currentBlending = null;
  40446. this.currentBlendSrc = null;
  40447. this.currentBlendDst = null;
  40448. this.currentBlendSrcAlpha = null;
  40449. this.currentBlendDstAlpha = null;
  40450. this.currentPremultipledAlpha = null;
  40451. this.currentPolygonOffsetFactor = null;
  40452. this.currentPolygonOffsetUnits = null;
  40453. this.currentColorMask = null;
  40454. this.currentDepthFunc = null;
  40455. this.currentDepthMask = null;
  40456. this.currentStencilFunc = null;
  40457. this.currentStencilRef = null;
  40458. this.currentStencilFuncMask = null;
  40459. this.currentStencilFail = null;
  40460. this.currentStencilZFail = null;
  40461. this.currentStencilZPass = null;
  40462. this.currentStencilMask = null;
  40463. this.currentLineWidth = null;
  40464. this.currentBoundFramebuffers = {};
  40465. this.currentDrawbuffers = new WeakMap();
  40466. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  40467. this.currentTextureSlot = null;
  40468. this.currentBoundTextures = {};
  40469. this.currentBoundBufferBases = {};
  40470. if ( initialized$1 === false ) {
  40471. this._init( this.gl );
  40472. initialized$1 = true;
  40473. }
  40474. }
  40475. _init( gl ) {
  40476. // Store only WebGL constants here.
  40477. equationToGL = {
  40478. [ AddEquation ]: gl.FUNC_ADD,
  40479. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  40480. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  40481. };
  40482. factorToGL = {
  40483. [ ZeroFactor ]: gl.ZERO,
  40484. [ OneFactor ]: gl.ONE,
  40485. [ SrcColorFactor ]: gl.SRC_COLOR,
  40486. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  40487. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  40488. [ DstColorFactor ]: gl.DST_COLOR,
  40489. [ DstAlphaFactor ]: gl.DST_ALPHA,
  40490. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  40491. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  40492. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  40493. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  40494. };
  40495. }
  40496. enable( id ) {
  40497. const { enabled } = this;
  40498. if ( enabled[ id ] !== true ) {
  40499. this.gl.enable( id );
  40500. enabled[ id ] = true;
  40501. }
  40502. }
  40503. disable( id ) {
  40504. const { enabled } = this;
  40505. if ( enabled[ id ] !== false ) {
  40506. this.gl.disable( id );
  40507. enabled[ id ] = false;
  40508. }
  40509. }
  40510. setFlipSided( flipSided ) {
  40511. if ( this.currentFlipSided !== flipSided ) {
  40512. const { gl } = this;
  40513. if ( flipSided ) {
  40514. gl.frontFace( gl.CW );
  40515. } else {
  40516. gl.frontFace( gl.CCW );
  40517. }
  40518. this.currentFlipSided = flipSided;
  40519. }
  40520. }
  40521. setCullFace( cullFace ) {
  40522. const { gl } = this;
  40523. if ( cullFace !== CullFaceNone ) {
  40524. this.enable( gl.CULL_FACE );
  40525. if ( cullFace !== this.currentCullFace ) {
  40526. if ( cullFace === CullFaceBack ) {
  40527. gl.cullFace( gl.BACK );
  40528. } else if ( cullFace === CullFaceFront ) {
  40529. gl.cullFace( gl.FRONT );
  40530. } else {
  40531. gl.cullFace( gl.FRONT_AND_BACK );
  40532. }
  40533. }
  40534. } else {
  40535. this.disable( gl.CULL_FACE );
  40536. }
  40537. this.currentCullFace = cullFace;
  40538. }
  40539. setLineWidth( width ) {
  40540. const { currentLineWidth, gl } = this;
  40541. if ( width !== currentLineWidth ) {
  40542. gl.lineWidth( width );
  40543. this.currentLineWidth = width;
  40544. }
  40545. }
  40546. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  40547. const { gl } = this;
  40548. if ( blending === NoBlending ) {
  40549. if ( this.currentBlendingEnabled === true ) {
  40550. this.disable( gl.BLEND );
  40551. this.currentBlendingEnabled = false;
  40552. }
  40553. return;
  40554. }
  40555. if ( this.currentBlendingEnabled === false ) {
  40556. this.enable( gl.BLEND );
  40557. this.currentBlendingEnabled = true;
  40558. }
  40559. if ( blending !== CustomBlending ) {
  40560. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  40561. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  40562. gl.blendEquation( gl.FUNC_ADD );
  40563. this.currentBlendEquation = AddEquation;
  40564. this.currentBlendEquationAlpha = AddEquation;
  40565. }
  40566. if ( premultipliedAlpha ) {
  40567. switch ( blending ) {
  40568. case NormalBlending:
  40569. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  40570. break;
  40571. case AdditiveBlending:
  40572. gl.blendFunc( gl.ONE, gl.ONE );
  40573. break;
  40574. case SubtractiveBlending:
  40575. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  40576. break;
  40577. case MultiplyBlending:
  40578. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  40579. break;
  40580. default:
  40581. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  40582. break;
  40583. }
  40584. } else {
  40585. switch ( blending ) {
  40586. case NormalBlending:
  40587. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  40588. break;
  40589. case AdditiveBlending:
  40590. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  40591. break;
  40592. case SubtractiveBlending:
  40593. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  40594. break;
  40595. case MultiplyBlending:
  40596. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  40597. break;
  40598. default:
  40599. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  40600. break;
  40601. }
  40602. }
  40603. this.currentBlendSrc = null;
  40604. this.currentBlendDst = null;
  40605. this.currentBlendSrcAlpha = null;
  40606. this.currentBlendDstAlpha = null;
  40607. this.currentBlending = blending;
  40608. this.currentPremultipledAlpha = premultipliedAlpha;
  40609. }
  40610. return;
  40611. }
  40612. // custom blending
  40613. blendEquationAlpha = blendEquationAlpha || blendEquation;
  40614. blendSrcAlpha = blendSrcAlpha || blendSrc;
  40615. blendDstAlpha = blendDstAlpha || blendDst;
  40616. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  40617. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  40618. this.currentBlendEquation = blendEquation;
  40619. this.currentBlendEquationAlpha = blendEquationAlpha;
  40620. }
  40621. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  40622. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  40623. this.currentBlendSrc = blendSrc;
  40624. this.currentBlendDst = blendDst;
  40625. this.currentBlendSrcAlpha = blendSrcAlpha;
  40626. this.currentBlendDstAlpha = blendDstAlpha;
  40627. }
  40628. this.currentBlending = blending;
  40629. this.currentPremultipledAlpha = false;
  40630. }
  40631. setColorMask( colorMask ) {
  40632. if ( this.currentColorMask !== colorMask ) {
  40633. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  40634. this.currentColorMask = colorMask;
  40635. }
  40636. }
  40637. setDepthTest( depthTest ) {
  40638. const { gl } = this;
  40639. if ( depthTest ) {
  40640. this.enable( gl.DEPTH_TEST );
  40641. } else {
  40642. this.disable( gl.DEPTH_TEST );
  40643. }
  40644. }
  40645. setDepthMask( depthMask ) {
  40646. if ( this.currentDepthMask !== depthMask ) {
  40647. this.gl.depthMask( depthMask );
  40648. this.currentDepthMask = depthMask;
  40649. }
  40650. }
  40651. setDepthFunc( depthFunc ) {
  40652. if ( this.currentDepthFunc !== depthFunc ) {
  40653. const { gl } = this;
  40654. switch ( depthFunc ) {
  40655. case NeverDepth:
  40656. gl.depthFunc( gl.NEVER );
  40657. break;
  40658. case AlwaysDepth:
  40659. gl.depthFunc( gl.ALWAYS );
  40660. break;
  40661. case LessDepth:
  40662. gl.depthFunc( gl.LESS );
  40663. break;
  40664. case LessEqualDepth:
  40665. gl.depthFunc( gl.LEQUAL );
  40666. break;
  40667. case EqualDepth:
  40668. gl.depthFunc( gl.EQUAL );
  40669. break;
  40670. case GreaterEqualDepth:
  40671. gl.depthFunc( gl.GEQUAL );
  40672. break;
  40673. case GreaterDepth:
  40674. gl.depthFunc( gl.GREATER );
  40675. break;
  40676. case NotEqualDepth:
  40677. gl.depthFunc( gl.NOTEQUAL );
  40678. break;
  40679. default:
  40680. gl.depthFunc( gl.LEQUAL );
  40681. }
  40682. this.currentDepthFunc = depthFunc;
  40683. }
  40684. }
  40685. setStencilTest( stencilTest ) {
  40686. const { gl } = this;
  40687. if ( stencilTest ) {
  40688. this.enable( gl.STENCIL_TEST );
  40689. } else {
  40690. this.disable( gl.STENCIL_TEST );
  40691. }
  40692. }
  40693. setStencilMask( stencilMask ) {
  40694. if ( this.currentStencilMask !== stencilMask ) {
  40695. this.gl.stencilMask( stencilMask );
  40696. this.currentStencilMask = stencilMask;
  40697. }
  40698. }
  40699. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  40700. if ( this.currentStencilFunc !== stencilFunc ||
  40701. this.currentStencilRef !== stencilRef ||
  40702. this.currentStencilFuncMask !== stencilMask ) {
  40703. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  40704. this.currentStencilFunc = stencilFunc;
  40705. this.currentStencilRef = stencilRef;
  40706. this.currentStencilFuncMask = stencilMask;
  40707. }
  40708. }
  40709. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  40710. if ( this.currentStencilFail !== stencilFail ||
  40711. this.currentStencilZFail !== stencilZFail ||
  40712. this.currentStencilZPass !== stencilZPass ) {
  40713. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  40714. this.currentStencilFail = stencilFail;
  40715. this.currentStencilZFail = stencilZFail;
  40716. this.currentStencilZPass = stencilZPass;
  40717. }
  40718. }
  40719. setMaterial( material, frontFaceCW ) {
  40720. const { gl } = this;
  40721. material.side === DoubleSide
  40722. ? this.disable( gl.CULL_FACE )
  40723. : this.enable( gl.CULL_FACE );
  40724. let flipSided = ( material.side === BackSide );
  40725. if ( frontFaceCW ) flipSided = ! flipSided;
  40726. this.setFlipSided( flipSided );
  40727. ( material.blending === NormalBlending && material.transparent === false )
  40728. ? this.setBlending( NoBlending )
  40729. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  40730. this.setDepthFunc( material.depthFunc );
  40731. this.setDepthTest( material.depthTest );
  40732. this.setDepthMask( material.depthWrite );
  40733. this.setColorMask( material.colorWrite );
  40734. const stencilWrite = material.stencilWrite;
  40735. this.setStencilTest( stencilWrite );
  40736. if ( stencilWrite ) {
  40737. this.setStencilMask( material.stencilWriteMask );
  40738. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  40739. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  40740. }
  40741. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  40742. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  40743. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  40744. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  40745. }
  40746. setPolygonOffset( polygonOffset, factor, units ) {
  40747. const { gl } = this;
  40748. if ( polygonOffset ) {
  40749. this.enable( gl.POLYGON_OFFSET_FILL );
  40750. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  40751. gl.polygonOffset( factor, units );
  40752. this.currentPolygonOffsetFactor = factor;
  40753. this.currentPolygonOffsetUnits = units;
  40754. }
  40755. } else {
  40756. this.disable( gl.POLYGON_OFFSET_FILL );
  40757. }
  40758. }
  40759. useProgram( program ) {
  40760. if ( this.currentProgram !== program ) {
  40761. this.gl.useProgram( program );
  40762. this.currentProgram = program;
  40763. return true;
  40764. }
  40765. return false;
  40766. }
  40767. // framebuffer
  40768. bindFramebuffer( target, framebuffer ) {
  40769. const { gl, currentBoundFramebuffers } = this;
  40770. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  40771. gl.bindFramebuffer( target, framebuffer );
  40772. currentBoundFramebuffers[ target ] = framebuffer;
  40773. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  40774. if ( target === gl.DRAW_FRAMEBUFFER ) {
  40775. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  40776. }
  40777. if ( target === gl.FRAMEBUFFER ) {
  40778. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  40779. }
  40780. return true;
  40781. }
  40782. return false;
  40783. }
  40784. drawBuffers( renderContext, framebuffer ) {
  40785. const { gl } = this;
  40786. let drawBuffers = [];
  40787. let needsUpdate = false;
  40788. if ( renderContext.textures !== null ) {
  40789. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  40790. if ( drawBuffers === undefined ) {
  40791. drawBuffers = [];
  40792. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  40793. }
  40794. const textures = renderContext.textures;
  40795. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  40796. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  40797. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  40798. }
  40799. drawBuffers.length = textures.length;
  40800. needsUpdate = true;
  40801. }
  40802. } else {
  40803. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  40804. drawBuffers[ 0 ] = gl.BACK;
  40805. needsUpdate = true;
  40806. }
  40807. }
  40808. if ( needsUpdate ) {
  40809. gl.drawBuffers( drawBuffers );
  40810. }
  40811. }
  40812. // texture
  40813. activeTexture( webglSlot ) {
  40814. const { gl, currentTextureSlot, maxTextures } = this;
  40815. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  40816. if ( currentTextureSlot !== webglSlot ) {
  40817. gl.activeTexture( webglSlot );
  40818. this.currentTextureSlot = webglSlot;
  40819. }
  40820. }
  40821. bindTexture( webglType, webglTexture, webglSlot ) {
  40822. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  40823. if ( webglSlot === undefined ) {
  40824. if ( currentTextureSlot === null ) {
  40825. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  40826. } else {
  40827. webglSlot = currentTextureSlot;
  40828. }
  40829. }
  40830. let boundTexture = currentBoundTextures[ webglSlot ];
  40831. if ( boundTexture === undefined ) {
  40832. boundTexture = { type: undefined, texture: undefined };
  40833. currentBoundTextures[ webglSlot ] = boundTexture;
  40834. }
  40835. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  40836. if ( currentTextureSlot !== webglSlot ) {
  40837. gl.activeTexture( webglSlot );
  40838. this.currentTextureSlot = webglSlot;
  40839. }
  40840. gl.bindTexture( webglType, webglTexture );
  40841. boundTexture.type = webglType;
  40842. boundTexture.texture = webglTexture;
  40843. }
  40844. }
  40845. bindBufferBase( target, index, buffer ) {
  40846. const { gl } = this;
  40847. const key = `${target}-${index}`;
  40848. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  40849. gl.bindBufferBase( target, index, buffer );
  40850. this.currentBoundBufferBases[ key ] = buffer;
  40851. return true;
  40852. }
  40853. return false;
  40854. }
  40855. unbindTexture() {
  40856. const { gl, currentTextureSlot, currentBoundTextures } = this;
  40857. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  40858. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  40859. gl.bindTexture( boundTexture.type, null );
  40860. boundTexture.type = undefined;
  40861. boundTexture.texture = undefined;
  40862. }
  40863. }
  40864. }
  40865. class WebGLUtils {
  40866. constructor( backend ) {
  40867. this.backend = backend;
  40868. this.gl = this.backend.gl;
  40869. this.extensions = backend.extensions;
  40870. }
  40871. convert( p, colorSpace = NoColorSpace ) {
  40872. const { gl, extensions } = this;
  40873. let extension;
  40874. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  40875. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  40876. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  40877. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  40878. if ( p === ByteType ) return gl.BYTE;
  40879. if ( p === ShortType ) return gl.SHORT;
  40880. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  40881. if ( p === IntType ) return gl.INT;
  40882. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  40883. if ( p === FloatType ) return gl.FLOAT;
  40884. if ( p === HalfFloatType ) {
  40885. return gl.HALF_FLOAT;
  40886. }
  40887. if ( p === AlphaFormat ) return gl.ALPHA;
  40888. if ( p === RGBFormat ) return gl.RGB;
  40889. if ( p === RGBAFormat ) return gl.RGBA;
  40890. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  40891. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  40892. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  40893. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  40894. // WebGL2 formats.
  40895. if ( p === RedFormat ) return gl.RED;
  40896. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  40897. if ( p === RGFormat ) return gl.RG;
  40898. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  40899. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  40900. // S3TC
  40901. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  40902. if ( colorSpace === SRGBColorSpace ) {
  40903. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  40904. if ( extension !== null ) {
  40905. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  40906. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  40907. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  40908. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  40909. } else {
  40910. return null;
  40911. }
  40912. } else {
  40913. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  40914. if ( extension !== null ) {
  40915. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  40916. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40917. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40918. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40919. } else {
  40920. return null;
  40921. }
  40922. }
  40923. }
  40924. // PVRTC
  40925. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  40926. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  40927. if ( extension !== null ) {
  40928. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  40929. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  40930. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  40931. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  40932. } else {
  40933. return null;
  40934. }
  40935. }
  40936. // ETC
  40937. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  40938. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  40939. if ( extension !== null ) {
  40940. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  40941. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  40942. } else {
  40943. return null;
  40944. }
  40945. }
  40946. // ASTC
  40947. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  40948. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  40949. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  40950. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  40951. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  40952. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  40953. if ( extension !== null ) {
  40954. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  40955. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  40956. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  40957. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  40958. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  40959. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  40960. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  40961. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  40962. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  40963. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  40964. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  40965. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  40966. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  40967. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  40968. } else {
  40969. return null;
  40970. }
  40971. }
  40972. // BPTC
  40973. if ( p === RGBA_BPTC_Format ) {
  40974. extension = extensions.get( 'EXT_texture_compression_bptc' );
  40975. if ( extension !== null ) {
  40976. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  40977. } else {
  40978. return null;
  40979. }
  40980. }
  40981. // RGTC
  40982. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  40983. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  40984. if ( extension !== null ) {
  40985. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  40986. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  40987. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  40988. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  40989. } else {
  40990. return null;
  40991. }
  40992. }
  40993. //
  40994. if ( p === UnsignedInt248Type ) {
  40995. return gl.UNSIGNED_INT_24_8;
  40996. }
  40997. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  40998. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  40999. }
  41000. _clientWaitAsync() {
  41001. const { gl } = this;
  41002. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  41003. gl.flush();
  41004. return new Promise( ( resolve, reject ) => {
  41005. function test() {
  41006. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  41007. if ( res === gl.WAIT_FAILED ) {
  41008. gl.deleteSync( sync );
  41009. reject();
  41010. return;
  41011. }
  41012. if ( res === gl.TIMEOUT_EXPIRED ) {
  41013. requestAnimationFrame( test );
  41014. return;
  41015. }
  41016. gl.deleteSync( sync );
  41017. resolve();
  41018. }
  41019. test();
  41020. } );
  41021. }
  41022. }
  41023. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  41024. class WebGLTextureUtils {
  41025. constructor( backend ) {
  41026. this.backend = backend;
  41027. this.gl = backend.gl;
  41028. this.extensions = backend.extensions;
  41029. this.defaultTextures = {};
  41030. if ( initialized === false ) {
  41031. this._init( this.gl );
  41032. initialized = true;
  41033. }
  41034. }
  41035. _init( gl ) {
  41036. // Store only WebGL constants here.
  41037. wrappingToGL = {
  41038. [ RepeatWrapping ]: gl.REPEAT,
  41039. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  41040. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  41041. };
  41042. filterToGL = {
  41043. [ NearestFilter ]: gl.NEAREST,
  41044. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  41045. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  41046. [ LinearFilter ]: gl.LINEAR,
  41047. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  41048. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  41049. };
  41050. compareToGL = {
  41051. [ NeverCompare ]: gl.NEVER,
  41052. [ AlwaysCompare ]: gl.ALWAYS,
  41053. [ LessCompare ]: gl.LESS,
  41054. [ LessEqualCompare ]: gl.LEQUAL,
  41055. [ EqualCompare ]: gl.EQUAL,
  41056. [ GreaterEqualCompare ]: gl.GEQUAL,
  41057. [ GreaterCompare ]: gl.GREATER,
  41058. [ NotEqualCompare ]: gl.NOTEQUAL
  41059. };
  41060. }
  41061. filterFallback( f ) {
  41062. const { gl } = this;
  41063. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  41064. return gl.NEAREST;
  41065. }
  41066. return gl.LINEAR;
  41067. }
  41068. getGLTextureType( texture ) {
  41069. const { gl } = this;
  41070. let glTextureType;
  41071. if ( texture.isCubeTexture === true ) {
  41072. glTextureType = gl.TEXTURE_CUBE_MAP;
  41073. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  41074. glTextureType = gl.TEXTURE_2D_ARRAY;
  41075. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  41076. glTextureType = gl.TEXTURE_3D;
  41077. } else {
  41078. glTextureType = gl.TEXTURE_2D;
  41079. }
  41080. return glTextureType;
  41081. }
  41082. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  41083. const { gl, extensions } = this;
  41084. if ( internalFormatName !== null ) {
  41085. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  41086. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  41087. }
  41088. let internalFormat = glFormat;
  41089. if ( glFormat === gl.RED ) {
  41090. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  41091. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  41092. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  41093. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  41094. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  41095. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  41096. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  41097. if ( glType === gl.INT ) internalFormat = gl.R32I;
  41098. }
  41099. if ( glFormat === gl.RED_INTEGER ) {
  41100. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  41101. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  41102. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  41103. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  41104. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  41105. if ( glType === gl.INT ) internalFormat = gl.R32I;
  41106. }
  41107. if ( glFormat === gl.RG ) {
  41108. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  41109. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  41110. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  41111. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  41112. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  41113. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  41114. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  41115. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  41116. }
  41117. if ( glFormat === gl.RG_INTEGER ) {
  41118. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  41119. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  41120. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  41121. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  41122. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  41123. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  41124. }
  41125. if ( glFormat === gl.RGB ) {
  41126. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  41127. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  41128. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  41129. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  41130. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  41131. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  41132. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  41133. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  41134. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  41135. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  41136. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  41137. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  41138. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  41139. }
  41140. if ( glFormat === gl.RGB_INTEGER ) {
  41141. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  41142. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  41143. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  41144. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  41145. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  41146. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  41147. }
  41148. if ( glFormat === gl.RGBA ) {
  41149. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  41150. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  41151. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  41152. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  41153. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  41154. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  41155. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  41156. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  41157. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  41158. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  41159. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  41160. }
  41161. if ( glFormat === gl.RGBA_INTEGER ) {
  41162. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  41163. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  41164. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  41165. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  41166. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  41167. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  41168. }
  41169. if ( glFormat === gl.DEPTH_COMPONENT ) {
  41170. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  41171. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  41172. }
  41173. if ( glFormat === gl.DEPTH_STENCIL ) {
  41174. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  41175. }
  41176. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  41177. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  41178. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  41179. extensions.get( 'EXT_color_buffer_float' );
  41180. }
  41181. return internalFormat;
  41182. }
  41183. setTextureParameters( textureType, texture ) {
  41184. const { gl, extensions, backend } = this;
  41185. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  41186. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  41187. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  41188. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  41189. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  41190. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  41191. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  41192. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  41193. }
  41194. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  41195. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  41196. // follow WebGPU backend mapping for texture filtering
  41197. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  41198. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  41199. if ( texture.compareFunction ) {
  41200. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  41201. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  41202. }
  41203. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  41204. if ( texture.magFilter === NearestFilter ) return;
  41205. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  41206. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  41207. if ( texture.anisotropy > 1 ) {
  41208. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  41209. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  41210. }
  41211. }
  41212. }
  41213. createDefaultTexture( texture ) {
  41214. const { gl, backend, defaultTextures } = this;
  41215. const glTextureType = this.getGLTextureType( texture );
  41216. let textureGPU = defaultTextures[ glTextureType ];
  41217. if ( textureGPU === undefined ) {
  41218. textureGPU = gl.createTexture();
  41219. backend.state.bindTexture( glTextureType, textureGPU );
  41220. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  41221. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  41222. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  41223. defaultTextures[ glTextureType ] = textureGPU;
  41224. }
  41225. backend.set( texture, {
  41226. textureGPU,
  41227. glTextureType,
  41228. isDefault: true
  41229. } );
  41230. }
  41231. createTexture( texture, options ) {
  41232. const { gl, backend } = this;
  41233. const { levels, width, height, depth } = options;
  41234. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  41235. const glType = backend.utils.convert( texture.type );
  41236. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  41237. const textureGPU = gl.createTexture();
  41238. const glTextureType = this.getGLTextureType( texture );
  41239. backend.state.bindTexture( glTextureType, textureGPU );
  41240. this.setTextureParameters( glTextureType, texture );
  41241. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  41242. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  41243. } else if ( texture.isData3DTexture ) {
  41244. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  41245. } else if ( ! texture.isVideoTexture ) {
  41246. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  41247. }
  41248. backend.set( texture, {
  41249. textureGPU,
  41250. glTextureType,
  41251. glFormat,
  41252. glType,
  41253. glInternalFormat
  41254. } );
  41255. }
  41256. copyBufferToTexture( buffer, texture ) {
  41257. const { gl, backend } = this;
  41258. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  41259. const { width, height } = texture.source.data;
  41260. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  41261. backend.state.bindTexture( glTextureType, textureGPU );
  41262. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  41263. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  41264. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  41265. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  41266. backend.state.unbindTexture();
  41267. // debug
  41268. // const framebuffer = gl.createFramebuffer();
  41269. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  41270. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  41271. // const readout = new Float32Array( width * height * 4 );
  41272. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  41273. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  41274. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  41275. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  41276. // console.log( readout );
  41277. }
  41278. updateTexture( texture, options ) {
  41279. const { gl } = this;
  41280. const { width, height } = options;
  41281. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  41282. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  41283. return;
  41284. const getImage = ( source ) => {
  41285. if ( source.isDataTexture ) {
  41286. return source.image.data;
  41287. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  41288. return source;
  41289. }
  41290. return source.data;
  41291. };
  41292. this.backend.state.bindTexture( glTextureType, textureGPU );
  41293. this.setTextureParameters( glTextureType, texture );
  41294. if ( texture.isCompressedTexture ) {
  41295. const mipmaps = texture.mipmaps;
  41296. const image = options.image;
  41297. for ( let i = 0; i < mipmaps.length; i ++ ) {
  41298. const mipmap = mipmaps[ i ];
  41299. if ( texture.isCompressedArrayTexture ) {
  41300. if ( texture.format !== gl.RGBA ) {
  41301. if ( glFormat !== null ) {
  41302. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  41303. } else {
  41304. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  41305. }
  41306. } else {
  41307. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  41308. }
  41309. } else {
  41310. if ( glFormat !== null ) {
  41311. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  41312. } else {
  41313. console.warn( 'Unsupported compressed texture format' );
  41314. }
  41315. }
  41316. }
  41317. } else if ( texture.isCubeTexture ) {
  41318. const images = options.images;
  41319. for ( let i = 0; i < 6; i ++ ) {
  41320. const image = getImage( images[ i ] );
  41321. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  41322. }
  41323. } else if ( texture.isDataArrayTexture ) {
  41324. const image = options.image;
  41325. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  41326. } else if ( texture.isData3DTexture ) {
  41327. const image = options.image;
  41328. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  41329. } else if ( texture.isVideoTexture ) {
  41330. texture.update();
  41331. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  41332. } else {
  41333. const image = getImage( options.image );
  41334. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  41335. }
  41336. }
  41337. generateMipmaps( texture ) {
  41338. const { gl, backend } = this;
  41339. const { textureGPU, glTextureType } = backend.get( texture );
  41340. backend.state.bindTexture( glTextureType, textureGPU );
  41341. gl.generateMipmap( glTextureType );
  41342. }
  41343. deallocateRenderBuffers( renderTarget ) {
  41344. const { gl, backend } = this;
  41345. // remove framebuffer reference
  41346. if ( renderTarget ) {
  41347. const renderContextData = backend.get( renderTarget );
  41348. renderContextData.renderBufferStorageSetup = undefined;
  41349. if ( renderContextData.framebuffers ) {
  41350. for ( const cacheKey in renderContextData.framebuffers ) {
  41351. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  41352. }
  41353. delete renderContextData.framebuffers;
  41354. }
  41355. if ( renderContextData.depthRenderbuffer ) {
  41356. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  41357. delete renderContextData.depthRenderbuffer;
  41358. }
  41359. if ( renderContextData.stencilRenderbuffer ) {
  41360. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  41361. delete renderContextData.stencilRenderbuffer;
  41362. }
  41363. if ( renderContextData.msaaFrameBuffer ) {
  41364. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  41365. delete renderContextData.msaaFrameBuffer;
  41366. }
  41367. if ( renderContextData.msaaRenderbuffers ) {
  41368. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  41369. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  41370. }
  41371. delete renderContextData.msaaRenderbuffers;
  41372. }
  41373. }
  41374. }
  41375. destroyTexture( texture ) {
  41376. const { gl, backend } = this;
  41377. const { textureGPU, renderTarget } = backend.get( texture );
  41378. this.deallocateRenderBuffers( renderTarget );
  41379. gl.deleteTexture( textureGPU );
  41380. backend.delete( texture );
  41381. }
  41382. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  41383. const { gl, backend } = this;
  41384. const { state } = this.backend;
  41385. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  41386. let width, height, minX, minY;
  41387. let dstX, dstY;
  41388. if ( srcRegion !== null ) {
  41389. width = srcRegion.max.x - srcRegion.min.x;
  41390. height = srcRegion.max.y - srcRegion.min.y;
  41391. minX = srcRegion.min.x;
  41392. minY = srcRegion.min.y;
  41393. } else {
  41394. width = srcTexture.image.width;
  41395. height = srcTexture.image.height;
  41396. minX = 0;
  41397. minY = 0;
  41398. }
  41399. if ( dstPosition !== null ) {
  41400. dstX = dstPosition.x;
  41401. dstY = dstPosition.y;
  41402. } else {
  41403. dstX = 0;
  41404. dstY = 0;
  41405. }
  41406. state.bindTexture( glTextureType, dstTextureGPU );
  41407. // As another texture upload may have changed pixelStorei
  41408. // parameters, make sure they are correct for the dstTexture
  41409. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  41410. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  41411. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  41412. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  41413. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  41414. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  41415. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  41416. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  41417. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  41418. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  41419. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  41420. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  41421. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  41422. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  41423. if ( srcTexture.isDataTexture ) {
  41424. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  41425. } else {
  41426. if ( srcTexture.isCompressedTexture ) {
  41427. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  41428. } else {
  41429. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  41430. }
  41431. }
  41432. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  41433. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  41434. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  41435. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  41436. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  41437. // Generate mipmaps only when copying level 0
  41438. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  41439. state.unbindTexture();
  41440. }
  41441. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41442. const { gl } = this;
  41443. const { state } = this.backend;
  41444. const { textureGPU } = this.backend.get( texture );
  41445. const { x, y, z: width, w: height } = rectangle;
  41446. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  41447. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  41448. if ( requireDrawFrameBuffer ) {
  41449. const partial = ( x !== 0 || y !== 0 );
  41450. let mask;
  41451. let attachment;
  41452. if ( texture.isDepthTexture === true ) {
  41453. mask = gl.DEPTH_BUFFER_BIT;
  41454. attachment = gl.DEPTH_ATTACHMENT;
  41455. if ( renderContext.stencil ) {
  41456. mask |= gl.STENCIL_BUFFER_BIT;
  41457. }
  41458. } else {
  41459. mask = gl.COLOR_BUFFER_BIT;
  41460. attachment = gl.COLOR_ATTACHMENT0;
  41461. }
  41462. if ( partial ) {
  41463. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  41464. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41465. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41466. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41467. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41468. const flippedY = srcHeight - y - height;
  41469. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  41470. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  41471. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  41472. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  41473. state.unbindTexture();
  41474. } else {
  41475. const fb = gl.createFramebuffer();
  41476. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41477. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  41478. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  41479. gl.deleteFramebuffer( fb );
  41480. }
  41481. } else {
  41482. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  41483. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  41484. state.unbindTexture();
  41485. }
  41486. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  41487. this.backend._setFramebuffer( renderContext );
  41488. }
  41489. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  41490. setupRenderBufferStorage( renderbuffer, renderContext ) {
  41491. const { gl } = this;
  41492. const renderTarget = renderContext.renderTarget;
  41493. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  41494. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  41495. if ( depthBuffer && ! stencilBuffer ) {
  41496. let glInternalFormat = gl.DEPTH_COMPONENT24;
  41497. if ( samples > 0 ) {
  41498. if ( depthTexture && depthTexture.isDepthTexture ) {
  41499. if ( depthTexture.type === gl.FLOAT ) {
  41500. glInternalFormat = gl.DEPTH_COMPONENT32F;
  41501. }
  41502. }
  41503. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  41504. } else {
  41505. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  41506. }
  41507. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  41508. } else if ( depthBuffer && stencilBuffer ) {
  41509. if ( samples > 0 ) {
  41510. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  41511. } else {
  41512. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  41513. }
  41514. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  41515. }
  41516. }
  41517. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41518. const { backend, gl } = this;
  41519. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  41520. const fb = gl.createFramebuffer();
  41521. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  41522. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  41523. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  41524. const typedArrayType = this._getTypedArrayType( glType );
  41525. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  41526. const elementCount = width * height;
  41527. const byteLength = elementCount * bytesPerTexel;
  41528. const buffer = gl.createBuffer();
  41529. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  41530. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  41531. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  41532. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  41533. await backend.utils._clientWaitAsync();
  41534. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  41535. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  41536. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  41537. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  41538. gl.deleteFramebuffer( fb );
  41539. return dstBuffer;
  41540. }
  41541. _getTypedArrayType( glType ) {
  41542. const { gl } = this;
  41543. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  41544. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  41545. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  41546. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  41547. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  41548. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  41549. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  41550. if ( glType === gl.FLOAT ) return Float32Array;
  41551. throw new Error( `Unsupported WebGL type: ${glType}` );
  41552. }
  41553. _getBytesPerTexel( glType, glFormat ) {
  41554. const { gl } = this;
  41555. let bytesPerComponent = 0;
  41556. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  41557. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  41558. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  41559. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  41560. glType === gl.UNSIGNED_SHORT ||
  41561. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  41562. if ( glType === gl.UNSIGNED_INT ||
  41563. glType === gl.FLOAT ) bytesPerComponent = 4;
  41564. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  41565. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  41566. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  41567. }
  41568. }
  41569. class WebGLExtensions {
  41570. constructor( backend ) {
  41571. this.backend = backend;
  41572. this.gl = this.backend.gl;
  41573. this.availableExtensions = this.gl.getSupportedExtensions();
  41574. this.extensions = {};
  41575. }
  41576. get( name ) {
  41577. let extension = this.extensions[ name ];
  41578. if ( extension === undefined ) {
  41579. extension = this.gl.getExtension( name );
  41580. this.extensions[ name ] = extension;
  41581. }
  41582. return extension;
  41583. }
  41584. has( name ) {
  41585. return this.availableExtensions.includes( name );
  41586. }
  41587. }
  41588. class WebGLCapabilities {
  41589. constructor( backend ) {
  41590. this.backend = backend;
  41591. this.maxAnisotropy = null;
  41592. }
  41593. getMaxAnisotropy() {
  41594. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  41595. const gl = this.backend.gl;
  41596. const extensions = this.backend.extensions;
  41597. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  41598. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  41599. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  41600. } else {
  41601. this.maxAnisotropy = 0;
  41602. }
  41603. return this.maxAnisotropy;
  41604. }
  41605. }
  41606. const GLFeatureName = {
  41607. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  41608. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  41609. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  41610. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  41611. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41612. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41613. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  41614. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  41615. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  41616. };
  41617. class WebGLBufferRenderer {
  41618. constructor( backend ) {
  41619. this.gl = backend.gl;
  41620. this.extensions = backend.extensions;
  41621. this.info = backend.renderer.info;
  41622. this.mode = null;
  41623. this.index = 0;
  41624. this.type = null;
  41625. this.object = null;
  41626. }
  41627. render( start, count ) {
  41628. const { gl, mode, object, type, info, index } = this;
  41629. if ( index !== 0 ) {
  41630. gl.drawElements( mode, count, type, start );
  41631. } else {
  41632. gl.drawArrays( mode, start, count );
  41633. }
  41634. info.update( object, count, mode, 1 );
  41635. }
  41636. renderInstances( start, count, primcount ) {
  41637. const { gl, mode, type, index, object, info } = this;
  41638. if ( primcount === 0 ) return;
  41639. if ( index !== 0 ) {
  41640. gl.drawElementsInstanced( mode, count, type, start, primcount );
  41641. } else {
  41642. gl.drawArraysInstanced( mode, start, count, primcount );
  41643. }
  41644. info.update( object, count, mode, primcount );
  41645. }
  41646. renderMultiDraw( starts, counts, drawCount ) {
  41647. const { extensions, mode, object, info } = this;
  41648. if ( drawCount === 0 ) return;
  41649. const extension = extensions.get( 'WEBGL_multi_draw' );
  41650. if ( extension === null ) {
  41651. for ( let i = 0; i < drawCount; i ++ ) {
  41652. this.render( starts[ i ], counts[ i ] );
  41653. }
  41654. } else {
  41655. if ( this.index !== 0 ) {
  41656. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  41657. } else {
  41658. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  41659. }
  41660. let elementCount = 0;
  41661. for ( let i = 0; i < drawCount; i ++ ) {
  41662. elementCount += counts[ i ];
  41663. }
  41664. info.update( object, elementCount, mode, 1 );
  41665. }
  41666. }
  41667. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  41668. const { extensions, mode, object, info } = this;
  41669. if ( drawCount === 0 ) return;
  41670. const extension = extensions.get( 'WEBGL_multi_draw' );
  41671. if ( extension === null ) {
  41672. for ( let i = 0; i < drawCount; i ++ ) {
  41673. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  41674. }
  41675. } else {
  41676. if ( this.index !== 0 ) {
  41677. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  41678. } else {
  41679. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  41680. }
  41681. let elementCount = 0;
  41682. for ( let i = 0; i < drawCount; i ++ ) {
  41683. elementCount += counts[ i ];
  41684. }
  41685. for ( let i = 0; i < primcount.length; i ++ ) {
  41686. info.update( object, elementCount, mode, primcount[ i ] );
  41687. }
  41688. }
  41689. }
  41690. //
  41691. }
  41692. //
  41693. class WebGLBackend extends Backend {
  41694. constructor( parameters = {} ) {
  41695. super( parameters );
  41696. this.isWebGLBackend = true;
  41697. }
  41698. init( renderer ) {
  41699. super.init( renderer );
  41700. //
  41701. const parameters = this.parameters;
  41702. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  41703. this.gl = glContext;
  41704. this.extensions = new WebGLExtensions( this );
  41705. this.capabilities = new WebGLCapabilities( this );
  41706. this.attributeUtils = new WebGLAttributeUtils( this );
  41707. this.textureUtils = new WebGLTextureUtils( this );
  41708. this.bufferRenderer = new WebGLBufferRenderer( this );
  41709. this.state = new WebGLState( this );
  41710. this.utils = new WebGLUtils( this );
  41711. this.vaoCache = {};
  41712. this.transformFeedbackCache = {};
  41713. this.discard = false;
  41714. this.trackTimestamp = ( parameters.trackTimestamp === true );
  41715. this.extensions.get( 'EXT_color_buffer_float' );
  41716. this.extensions.get( 'WEBGL_clip_cull_distance' );
  41717. this.extensions.get( 'OES_texture_float_linear' );
  41718. this.extensions.get( 'EXT_color_buffer_half_float' );
  41719. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  41720. this.extensions.get( 'WEBGL_render_shared_exponent' );
  41721. this.extensions.get( 'WEBGL_multi_draw' );
  41722. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  41723. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  41724. this._currentContext = null;
  41725. }
  41726. get coordinateSystem() {
  41727. return WebGLCoordinateSystem;
  41728. }
  41729. async getArrayBufferAsync( attribute ) {
  41730. return await this.attributeUtils.getArrayBufferAsync( attribute );
  41731. }
  41732. initTimestampQuery( renderContext ) {
  41733. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41734. const renderContextData = this.get( renderContext );
  41735. if ( this.queryRunning ) {
  41736. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  41737. renderContextData.queryQueue.push( renderContext );
  41738. return;
  41739. }
  41740. if ( renderContextData.activeQuery ) {
  41741. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  41742. renderContextData.activeQuery = null;
  41743. }
  41744. renderContextData.activeQuery = this.gl.createQuery();
  41745. if ( renderContextData.activeQuery !== null ) {
  41746. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  41747. this.queryRunning = true;
  41748. }
  41749. }
  41750. // timestamp utils
  41751. prepareTimestampBuffer( renderContext ) {
  41752. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41753. const renderContextData = this.get( renderContext );
  41754. if ( renderContextData.activeQuery ) {
  41755. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  41756. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  41757. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  41758. renderContextData.activeQuery = null;
  41759. this.queryRunning = false;
  41760. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  41761. const nextRenderContext = renderContextData.queryQueue.shift();
  41762. this.initTimestampQuery( nextRenderContext );
  41763. }
  41764. }
  41765. }
  41766. async resolveTimestampAsync( renderContext, type = 'render' ) {
  41767. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41768. const renderContextData = this.get( renderContext );
  41769. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  41770. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  41771. const queryInfo = renderContextData.gpuQueries[ i ];
  41772. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  41773. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  41774. if ( available && ! disjoint ) {
  41775. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  41776. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  41777. this.gl.deleteQuery( queryInfo.query );
  41778. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  41779. i --;
  41780. this.renderer.info.updateTimestamp( type, duration );
  41781. }
  41782. }
  41783. }
  41784. getContext() {
  41785. return this.gl;
  41786. }
  41787. beginRender( renderContext ) {
  41788. const { gl } = this;
  41789. const renderContextData = this.get( renderContext );
  41790. //
  41791. //
  41792. this.initTimestampQuery( renderContext );
  41793. renderContextData.previousContext = this._currentContext;
  41794. this._currentContext = renderContext;
  41795. this._setFramebuffer( renderContext );
  41796. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  41797. //
  41798. if ( renderContext.viewport ) {
  41799. this.updateViewport( renderContext );
  41800. } else {
  41801. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41802. }
  41803. if ( renderContext.scissor ) {
  41804. const { x, y, width, height } = renderContext.scissorValue;
  41805. gl.scissor( x, renderContext.height - height - y, width, height );
  41806. }
  41807. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41808. if ( occlusionQueryCount > 0 ) {
  41809. // Get a reference to the array of objects with queries. The renderContextData property
  41810. // can be changed by another render pass before the async reading of all previous queries complete
  41811. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  41812. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  41813. renderContextData.lastOcclusionObject = null;
  41814. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  41815. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  41816. renderContextData.occlusionQueryIndex = 0;
  41817. }
  41818. }
  41819. finishRender( renderContext ) {
  41820. const { gl, state } = this;
  41821. const renderContextData = this.get( renderContext );
  41822. const previousContext = renderContextData.previousContext;
  41823. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41824. if ( occlusionQueryCount > 0 ) {
  41825. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  41826. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41827. }
  41828. this.resolveOccludedAsync( renderContext );
  41829. }
  41830. const textures = renderContext.textures;
  41831. if ( textures !== null ) {
  41832. for ( let i = 0; i < textures.length; i ++ ) {
  41833. const texture = textures[ i ];
  41834. if ( texture.generateMipmaps ) {
  41835. this.generateMipmaps( texture );
  41836. }
  41837. }
  41838. }
  41839. this._currentContext = previousContext;
  41840. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  41841. const renderTargetContextData = this.get( renderContext.renderTarget );
  41842. const { samples } = renderContext.renderTarget;
  41843. if ( samples > 0 ) {
  41844. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41845. const mask = gl.COLOR_BUFFER_BIT;
  41846. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41847. const textures = renderContext.textures;
  41848. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41849. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41850. for ( let i = 0; i < textures.length; i ++ ) {
  41851. // TODO Add support for MRT
  41852. if ( renderContext.scissor ) {
  41853. const { x, y, width, height } = renderContext.scissorValue;
  41854. const viewY = renderContext.height - height - y;
  41855. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  41856. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  41857. } else {
  41858. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  41859. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  41860. }
  41861. }
  41862. }
  41863. }
  41864. if ( previousContext !== null ) {
  41865. this._setFramebuffer( previousContext );
  41866. if ( previousContext.viewport ) {
  41867. this.updateViewport( previousContext );
  41868. } else {
  41869. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41870. }
  41871. }
  41872. this.prepareTimestampBuffer( renderContext );
  41873. }
  41874. resolveOccludedAsync( renderContext ) {
  41875. const renderContextData = this.get( renderContext );
  41876. // handle occlusion query results
  41877. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  41878. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  41879. const occluded = new WeakSet();
  41880. const { gl } = this;
  41881. renderContextData.currentOcclusionQueryObjects = null;
  41882. renderContextData.currentOcclusionQueries = null;
  41883. const check = () => {
  41884. let completed = 0;
  41885. // check all queries and requeue as appropriate
  41886. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  41887. const query = currentOcclusionQueries[ i ];
  41888. if ( query === null ) continue;
  41889. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  41890. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  41891. currentOcclusionQueries[ i ] = null;
  41892. gl.deleteQuery( query );
  41893. completed ++;
  41894. }
  41895. }
  41896. if ( completed < currentOcclusionQueries.length ) {
  41897. requestAnimationFrame( check );
  41898. } else {
  41899. renderContextData.occluded = occluded;
  41900. }
  41901. };
  41902. check();
  41903. }
  41904. }
  41905. isOccluded( renderContext, object ) {
  41906. const renderContextData = this.get( renderContext );
  41907. return renderContextData.occluded && renderContextData.occluded.has( object );
  41908. }
  41909. updateViewport( renderContext ) {
  41910. const gl = this.gl;
  41911. const { x, y, width, height } = renderContext.viewportValue;
  41912. gl.viewport( x, renderContext.height - height - y, width, height );
  41913. }
  41914. setScissorTest( boolean ) {
  41915. const gl = this.gl;
  41916. if ( boolean ) {
  41917. gl.enable( gl.SCISSOR_TEST );
  41918. } else {
  41919. gl.disable( gl.SCISSOR_TEST );
  41920. }
  41921. }
  41922. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  41923. const { gl } = this;
  41924. if ( descriptor === null ) {
  41925. descriptor = {
  41926. textures: null,
  41927. clearColorValue: this.getClearColor()
  41928. };
  41929. }
  41930. //
  41931. let clear = 0;
  41932. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  41933. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  41934. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  41935. if ( clear !== 0 ) {
  41936. const clearColor = descriptor.clearColorValue || this.getClearColor();
  41937. // premultiply alpha
  41938. clearColor.r *= clearColor.a;
  41939. clearColor.g *= clearColor.a;
  41940. clearColor.b *= clearColor.a;
  41941. if ( depth ) this.state.setDepthMask( true );
  41942. if ( descriptor.textures === null ) {
  41943. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  41944. gl.clear( clear );
  41945. } else {
  41946. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  41947. if ( color ) {
  41948. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  41949. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  41950. }
  41951. }
  41952. if ( depth && stencil ) {
  41953. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  41954. } else if ( depth ) {
  41955. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  41956. } else if ( stencil ) {
  41957. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  41958. }
  41959. }
  41960. }
  41961. }
  41962. beginCompute( computeGroup ) {
  41963. const { state, gl } = this;
  41964. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  41965. this.initTimestampQuery( computeGroup );
  41966. }
  41967. compute( computeGroup, computeNode, bindings, pipeline ) {
  41968. const { state, gl } = this;
  41969. if ( ! this.discard ) {
  41970. // required here to handle async behaviour of render.compute()
  41971. gl.enable( gl.RASTERIZER_DISCARD );
  41972. this.discard = true;
  41973. }
  41974. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  41975. const vaoKey = this._getVaoKey( null, attributes );
  41976. const vaoGPU = this.vaoCache[ vaoKey ];
  41977. if ( vaoGPU === undefined ) {
  41978. this._createVao( null, attributes );
  41979. } else {
  41980. gl.bindVertexArray( vaoGPU );
  41981. }
  41982. state.useProgram( programGPU );
  41983. this._bindUniforms( bindings );
  41984. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  41985. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41986. gl.beginTransformFeedback( gl.POINTS );
  41987. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  41988. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  41989. } else {
  41990. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  41991. }
  41992. gl.endTransformFeedback();
  41993. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41994. // switch active buffers
  41995. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41996. const dualAttributeData = transformBuffers[ i ];
  41997. if ( dualAttributeData.pbo ) {
  41998. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  41999. }
  42000. dualAttributeData.switchBuffers();
  42001. }
  42002. }
  42003. finishCompute( computeGroup ) {
  42004. const gl = this.gl;
  42005. this.discard = false;
  42006. gl.disable( gl.RASTERIZER_DISCARD );
  42007. this.prepareTimestampBuffer( computeGroup );
  42008. }
  42009. draw( renderObject/*, info*/ ) {
  42010. const { object, pipeline, material, context } = renderObject;
  42011. const { programGPU } = this.get( pipeline );
  42012. const { gl, state } = this;
  42013. const contextData = this.get( context );
  42014. const drawParms = renderObject.getDrawParameters();
  42015. if ( drawParms === null ) return;
  42016. //
  42017. this._bindUniforms( renderObject.getBindings() );
  42018. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  42019. state.setMaterial( material, frontFaceCW );
  42020. state.useProgram( programGPU );
  42021. //
  42022. let vaoGPU = renderObject.staticVao;
  42023. if ( vaoGPU === undefined ) {
  42024. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  42025. vaoGPU = this.vaoCache[ vaoKey ];
  42026. if ( vaoGPU === undefined ) {
  42027. let staticVao;
  42028. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  42029. if ( staticVao ) renderObject.staticVao = vaoGPU;
  42030. }
  42031. }
  42032. gl.bindVertexArray( vaoGPU );
  42033. //
  42034. const index = renderObject.getIndex();
  42035. //
  42036. const lastObject = contextData.lastOcclusionObject;
  42037. if ( lastObject !== object && lastObject !== undefined ) {
  42038. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  42039. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  42040. contextData.occlusionQueryIndex ++;
  42041. }
  42042. if ( object.occlusionTest === true ) {
  42043. const query = gl.createQuery();
  42044. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  42045. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  42046. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  42047. }
  42048. contextData.lastOcclusionObject = object;
  42049. }
  42050. //
  42051. const renderer = this.bufferRenderer;
  42052. if ( object.isPoints ) renderer.mode = gl.POINTS;
  42053. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  42054. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  42055. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  42056. else {
  42057. if ( material.wireframe === true ) {
  42058. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  42059. renderer.mode = gl.LINES;
  42060. } else {
  42061. renderer.mode = gl.TRIANGLES;
  42062. }
  42063. }
  42064. //
  42065. const { vertexCount, instanceCount } = drawParms;
  42066. let { firstVertex } = drawParms;
  42067. renderer.object = object;
  42068. if ( index !== null ) {
  42069. firstVertex *= index.array.BYTES_PER_ELEMENT;
  42070. const indexData = this.get( index );
  42071. renderer.index = index.count;
  42072. renderer.type = indexData.type;
  42073. } else {
  42074. renderer.index = 0;
  42075. }
  42076. if ( object.isBatchedMesh ) {
  42077. if ( object._multiDrawInstances !== null ) {
  42078. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  42079. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  42080. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  42081. } else {
  42082. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  42083. }
  42084. } else if ( instanceCount > 1 ) {
  42085. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  42086. } else {
  42087. renderer.render( firstVertex, vertexCount );
  42088. }
  42089. //
  42090. gl.bindVertexArray( null );
  42091. }
  42092. needsRenderUpdate( /*renderObject*/ ) {
  42093. return false;
  42094. }
  42095. getRenderCacheKey( /*renderObject*/ ) {
  42096. return '';
  42097. }
  42098. // textures
  42099. createDefaultTexture( texture ) {
  42100. this.textureUtils.createDefaultTexture( texture );
  42101. }
  42102. createTexture( texture, options ) {
  42103. this.textureUtils.createTexture( texture, options );
  42104. }
  42105. updateTexture( texture, options ) {
  42106. this.textureUtils.updateTexture( texture, options );
  42107. }
  42108. generateMipmaps( texture ) {
  42109. this.textureUtils.generateMipmaps( texture );
  42110. }
  42111. destroyTexture( texture ) {
  42112. this.textureUtils.destroyTexture( texture );
  42113. }
  42114. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42115. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  42116. }
  42117. createSampler( /*texture*/ ) {
  42118. //console.warn( 'Abstract class.' );
  42119. }
  42120. destroySampler() {}
  42121. // node builder
  42122. createNodeBuilder( object, renderer ) {
  42123. return new GLSLNodeBuilder( object, renderer );
  42124. }
  42125. // program
  42126. createProgram( program ) {
  42127. const gl = this.gl;
  42128. const { stage, code } = program;
  42129. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  42130. gl.shaderSource( shader, code );
  42131. gl.compileShader( shader );
  42132. this.set( program, {
  42133. shaderGPU: shader
  42134. } );
  42135. }
  42136. destroyProgram( /*program*/ ) {
  42137. console.warn( 'Abstract class.' );
  42138. }
  42139. createRenderPipeline( renderObject, promises ) {
  42140. const gl = this.gl;
  42141. const pipeline = renderObject.pipeline;
  42142. // Program
  42143. const { fragmentProgram, vertexProgram } = pipeline;
  42144. const programGPU = gl.createProgram();
  42145. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  42146. const vertexShader = this.get( vertexProgram ).shaderGPU;
  42147. gl.attachShader( programGPU, fragmentShader );
  42148. gl.attachShader( programGPU, vertexShader );
  42149. gl.linkProgram( programGPU );
  42150. this.set( pipeline, {
  42151. programGPU,
  42152. fragmentShader,
  42153. vertexShader
  42154. } );
  42155. if ( promises !== null && this.parallel ) {
  42156. const p = new Promise( ( resolve /*, reject*/ ) => {
  42157. const parallel = this.parallel;
  42158. const checkStatus = () => {
  42159. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  42160. this._completeCompile( renderObject, pipeline );
  42161. resolve();
  42162. } else {
  42163. requestAnimationFrame( checkStatus );
  42164. }
  42165. };
  42166. checkStatus();
  42167. } );
  42168. promises.push( p );
  42169. return;
  42170. }
  42171. this._completeCompile( renderObject, pipeline );
  42172. }
  42173. _handleSource( string, errorLine ) {
  42174. const lines = string.split( '\n' );
  42175. const lines2 = [];
  42176. const from = Math.max( errorLine - 6, 0 );
  42177. const to = Math.min( errorLine + 6, lines.length );
  42178. for ( let i = from; i < to; i ++ ) {
  42179. const line = i + 1;
  42180. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  42181. }
  42182. return lines2.join( '\n' );
  42183. }
  42184. _getShaderErrors( gl, shader, type ) {
  42185. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  42186. const errors = gl.getShaderInfoLog( shader ).trim();
  42187. if ( status && errors === '' ) return '';
  42188. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  42189. if ( errorMatches ) {
  42190. const errorLine = parseInt( errorMatches[ 1 ] );
  42191. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  42192. } else {
  42193. return errors;
  42194. }
  42195. }
  42196. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  42197. if ( this.renderer.debug.checkShaderErrors ) {
  42198. const gl = this.gl;
  42199. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  42200. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42201. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  42202. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  42203. } else {
  42204. // default error reporting
  42205. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  42206. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  42207. console.error(
  42208. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  42209. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  42210. 'Program Info Log: ' + programLog + '\n' +
  42211. vertexErrors + '\n' +
  42212. fragmentErrors
  42213. );
  42214. }
  42215. } else if ( programLog !== '' ) {
  42216. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  42217. }
  42218. }
  42219. }
  42220. _completeCompile( renderObject, pipeline ) {
  42221. const { state, gl } = this;
  42222. const pipelineData = this.get( pipeline );
  42223. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  42224. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42225. this._logProgramError( programGPU, fragmentShader, vertexShader );
  42226. }
  42227. state.useProgram( programGPU );
  42228. // Bindings
  42229. const bindings = renderObject.getBindings();
  42230. this._setupBindings( bindings, programGPU );
  42231. //
  42232. this.set( pipeline, {
  42233. programGPU
  42234. } );
  42235. }
  42236. createComputePipeline( computePipeline, bindings ) {
  42237. const { state, gl } = this;
  42238. // Program
  42239. const fragmentProgram = {
  42240. stage: 'fragment',
  42241. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  42242. };
  42243. this.createProgram( fragmentProgram );
  42244. const { computeProgram } = computePipeline;
  42245. const programGPU = gl.createProgram();
  42246. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  42247. const vertexShader = this.get( computeProgram ).shaderGPU;
  42248. const transforms = computeProgram.transforms;
  42249. const transformVaryingNames = [];
  42250. const transformAttributeNodes = [];
  42251. for ( let i = 0; i < transforms.length; i ++ ) {
  42252. const transform = transforms[ i ];
  42253. transformVaryingNames.push( transform.varyingName );
  42254. transformAttributeNodes.push( transform.attributeNode );
  42255. }
  42256. gl.attachShader( programGPU, fragmentShader );
  42257. gl.attachShader( programGPU, vertexShader );
  42258. gl.transformFeedbackVaryings(
  42259. programGPU,
  42260. transformVaryingNames,
  42261. gl.SEPARATE_ATTRIBS
  42262. );
  42263. gl.linkProgram( programGPU );
  42264. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42265. this._logProgramError( programGPU, fragmentShader, vertexShader );
  42266. }
  42267. state.useProgram( programGPU );
  42268. // Bindings
  42269. this.createBindings( null, bindings );
  42270. this._setupBindings( bindings, programGPU );
  42271. const attributeNodes = computeProgram.attributes;
  42272. const attributes = [];
  42273. const transformBuffers = [];
  42274. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  42275. const attribute = attributeNodes[ i ].node.attribute;
  42276. attributes.push( attribute );
  42277. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42278. }
  42279. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  42280. const attribute = transformAttributeNodes[ i ].attribute;
  42281. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42282. const attributeData = this.get( attribute );
  42283. transformBuffers.push( attributeData );
  42284. }
  42285. //
  42286. this.set( computePipeline, {
  42287. programGPU,
  42288. transformBuffers,
  42289. attributes
  42290. } );
  42291. }
  42292. createBindings( bindGroup, bindings ) {
  42293. this.updateBindings( bindGroup, bindings );
  42294. }
  42295. updateBindings( bindGroup, bindings ) {
  42296. if ( ! bindGroup ) return;
  42297. const { gl } = this;
  42298. const bindingsData = this.get( bindings );
  42299. const bindGroupData = this.get( bindGroup );
  42300. if ( bindingsData.textureIndex === undefined ) bindingsData.textureIndex = 0;
  42301. if ( bindGroupData.textureIndex === undefined ) {
  42302. bindGroupData.textureIndex = bindingsData.textureIndex;
  42303. } else {
  42304. // reset textureIndex to match previous mappimgs when rebuilt
  42305. bindingsData.textureIndex = bindGroupData.textureIndex;
  42306. }
  42307. let i = 0;
  42308. for ( const binding of bindGroup.bindings ) {
  42309. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42310. const data = binding.buffer;
  42311. const bufferGPU = gl.createBuffer();
  42312. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42313. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  42314. this.set( binding, {
  42315. index: bindGroup.index * 2 + i ++,
  42316. bufferGPU
  42317. } );
  42318. } else if ( binding.isSampledTexture ) {
  42319. const { textureGPU, glTextureType } = this.get( binding.texture );
  42320. this.set( binding, {
  42321. index: bindingsData.textureIndex ++,
  42322. textureGPU,
  42323. glTextureType
  42324. } );
  42325. }
  42326. }
  42327. }
  42328. updateBinding( binding ) {
  42329. const gl = this.gl;
  42330. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42331. const bindingData = this.get( binding );
  42332. const bufferGPU = bindingData.bufferGPU;
  42333. const data = binding.buffer;
  42334. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42335. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  42336. }
  42337. }
  42338. // attributes
  42339. createIndexAttribute( attribute ) {
  42340. const gl = this.gl;
  42341. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  42342. }
  42343. createAttribute( attribute ) {
  42344. if ( this.has( attribute ) ) return;
  42345. const gl = this.gl;
  42346. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42347. }
  42348. createStorageAttribute( attribute ) {
  42349. if ( this.has( attribute ) ) return;
  42350. const gl = this.gl;
  42351. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42352. }
  42353. updateAttribute( attribute ) {
  42354. this.attributeUtils.updateAttribute( attribute );
  42355. }
  42356. destroyAttribute( attribute ) {
  42357. this.attributeUtils.destroyAttribute( attribute );
  42358. }
  42359. updateSize() {
  42360. //console.warn( 'Abstract class.' );
  42361. }
  42362. hasFeature( name ) {
  42363. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  42364. const extensions = this.extensions;
  42365. for ( let i = 0; i < keysMatching.length; i ++ ) {
  42366. if ( extensions.has( keysMatching[ i ] ) ) return true;
  42367. }
  42368. return false;
  42369. }
  42370. getMaxAnisotropy() {
  42371. return this.capabilities.getMaxAnisotropy();
  42372. }
  42373. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  42374. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  42375. }
  42376. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  42377. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  42378. }
  42379. _setFramebuffer( descriptor ) {
  42380. const { gl, state } = this;
  42381. let currentFrameBuffer = null;
  42382. if ( descriptor.textures !== null ) {
  42383. const renderTarget = descriptor.renderTarget;
  42384. const renderTargetContextData = this.get( renderTarget );
  42385. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  42386. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  42387. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  42388. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  42389. const cacheKey = getCacheKey( descriptor );
  42390. let fb;
  42391. if ( isCube ) {
  42392. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  42393. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  42394. } else {
  42395. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  42396. fb = renderTargetContextData.framebuffers[ cacheKey ];
  42397. }
  42398. if ( fb === undefined ) {
  42399. fb = gl.createFramebuffer();
  42400. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  42401. const textures = descriptor.textures;
  42402. if ( isCube ) {
  42403. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  42404. const { textureGPU } = this.get( textures[ 0 ] );
  42405. const cubeFace = this.renderer._activeCubeFace;
  42406. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  42407. } else {
  42408. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  42409. for ( let i = 0; i < textures.length; i ++ ) {
  42410. const texture = textures[ i ];
  42411. const textureData = this.get( texture );
  42412. textureData.renderTarget = descriptor.renderTarget;
  42413. const attachment = gl.COLOR_ATTACHMENT0 + i;
  42414. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42415. }
  42416. state.drawBuffers( descriptor, fb );
  42417. }
  42418. if ( descriptor.depthTexture !== null ) {
  42419. const textureData = this.get( descriptor.depthTexture );
  42420. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42421. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42422. }
  42423. }
  42424. if ( samples > 0 ) {
  42425. if ( msaaFb === undefined ) {
  42426. const invalidationArray = [];
  42427. msaaFb = gl.createFramebuffer();
  42428. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  42429. const msaaRenderbuffers = [];
  42430. const textures = descriptor.textures;
  42431. for ( let i = 0; i < textures.length; i ++ ) {
  42432. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  42433. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42434. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  42435. if ( depthBuffer ) {
  42436. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42437. invalidationArray.push( depthStyle );
  42438. }
  42439. const texture = descriptor.textures[ i ];
  42440. const textureData = this.get( texture );
  42441. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  42442. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42443. }
  42444. renderTargetContextData.msaaFrameBuffer = msaaFb;
  42445. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  42446. if ( depthRenderbuffer === undefined ) {
  42447. depthRenderbuffer = gl.createRenderbuffer();
  42448. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  42449. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  42450. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42451. invalidationArray.push( depthStyle );
  42452. }
  42453. renderTargetContextData.invalidationArray = invalidationArray;
  42454. }
  42455. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42456. } else {
  42457. currentFrameBuffer = fb;
  42458. }
  42459. }
  42460. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  42461. }
  42462. _getVaoKey( index, attributes ) {
  42463. let key = [];
  42464. if ( index !== null ) {
  42465. const indexData = this.get( index );
  42466. key += ':' + indexData.id;
  42467. }
  42468. for ( let i = 0; i < attributes.length; i ++ ) {
  42469. const attributeData = this.get( attributes[ i ] );
  42470. key += ':' + attributeData.id;
  42471. }
  42472. return key;
  42473. }
  42474. _createVao( index, attributes ) {
  42475. const { gl } = this;
  42476. const vaoGPU = gl.createVertexArray();
  42477. let key = '';
  42478. let staticVao = true;
  42479. gl.bindVertexArray( vaoGPU );
  42480. if ( index !== null ) {
  42481. const indexData = this.get( index );
  42482. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  42483. key += ':' + indexData.id;
  42484. }
  42485. for ( let i = 0; i < attributes.length; i ++ ) {
  42486. const attribute = attributes[ i ];
  42487. const attributeData = this.get( attribute );
  42488. key += ':' + attributeData.id;
  42489. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  42490. gl.enableVertexAttribArray( i );
  42491. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  42492. let stride, offset;
  42493. if ( attribute.isInterleavedBufferAttribute === true ) {
  42494. stride = attribute.data.stride * attributeData.bytesPerElement;
  42495. offset = attribute.offset * attributeData.bytesPerElement;
  42496. } else {
  42497. stride = 0;
  42498. offset = 0;
  42499. }
  42500. if ( attributeData.isInteger ) {
  42501. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  42502. } else {
  42503. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  42504. }
  42505. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  42506. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  42507. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  42508. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  42509. }
  42510. }
  42511. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  42512. this.vaoCache[ key ] = vaoGPU;
  42513. return { vaoGPU, staticVao };
  42514. }
  42515. _getTransformFeedback( transformBuffers ) {
  42516. let key = '';
  42517. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42518. key += ':' + transformBuffers[ i ].id;
  42519. }
  42520. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  42521. if ( transformFeedbackGPU !== undefined ) {
  42522. return transformFeedbackGPU;
  42523. }
  42524. const { gl } = this;
  42525. transformFeedbackGPU = gl.createTransformFeedback();
  42526. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  42527. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42528. const attributeData = transformBuffers[ i ];
  42529. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  42530. }
  42531. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  42532. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  42533. return transformFeedbackGPU;
  42534. }
  42535. _setupBindings( bindings, programGPU ) {
  42536. const gl = this.gl;
  42537. for ( const bindGroup of bindings ) {
  42538. for ( const binding of bindGroup.bindings ) {
  42539. const bindingData = this.get( binding );
  42540. const index = bindingData.index;
  42541. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42542. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  42543. gl.uniformBlockBinding( programGPU, location, index );
  42544. } else if ( binding.isSampledTexture ) {
  42545. const location = gl.getUniformLocation( programGPU, binding.name );
  42546. gl.uniform1i( location, index );
  42547. }
  42548. }
  42549. }
  42550. }
  42551. _bindUniforms( bindings ) {
  42552. const { gl, state } = this;
  42553. for ( const bindGroup of bindings ) {
  42554. for ( const binding of bindGroup.bindings ) {
  42555. const bindingData = this.get( binding );
  42556. const index = bindingData.index;
  42557. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42558. // TODO USE bindBufferRange to group multiple uniform buffers
  42559. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  42560. } else if ( binding.isSampledTexture ) {
  42561. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  42562. }
  42563. }
  42564. }
  42565. }
  42566. }
  42567. class Sampler extends Binding {
  42568. constructor( name, texture ) {
  42569. super( name );
  42570. this.texture = texture;
  42571. this.version = texture ? texture.version : 0;
  42572. this.isSampler = true;
  42573. }
  42574. }
  42575. class NodeSampler extends Sampler {
  42576. constructor( name, textureNode, groupNode ) {
  42577. super( name, textureNode ? textureNode.value : null );
  42578. this.textureNode = textureNode;
  42579. this.groupNode = groupNode;
  42580. }
  42581. update() {
  42582. this.texture = this.textureNode.value;
  42583. }
  42584. }
  42585. class StorageBuffer extends Buffer {
  42586. constructor( name, attribute ) {
  42587. super( name, attribute ? attribute.array : null );
  42588. this.attribute = attribute;
  42589. this.isStorageBuffer = true;
  42590. }
  42591. }
  42592. let _id = 0;
  42593. class NodeStorageBuffer extends StorageBuffer {
  42594. constructor( nodeUniform, groupNode ) {
  42595. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  42596. this.nodeUniform = nodeUniform;
  42597. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  42598. this.groupNode = groupNode;
  42599. }
  42600. get buffer() {
  42601. return this.nodeUniform.value;
  42602. }
  42603. }
  42604. class WebGPUTexturePassUtils extends DataMap {
  42605. constructor( device ) {
  42606. super();
  42607. this.device = device;
  42608. const mipmapVertexSource = `
  42609. struct VarysStruct {
  42610. @builtin( position ) Position: vec4<f32>,
  42611. @location( 0 ) vTex : vec2<f32>
  42612. };
  42613. @vertex
  42614. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  42615. var Varys : VarysStruct;
  42616. var pos = array< vec2<f32>, 4 >(
  42617. vec2<f32>( -1.0, 1.0 ),
  42618. vec2<f32>( 1.0, 1.0 ),
  42619. vec2<f32>( -1.0, -1.0 ),
  42620. vec2<f32>( 1.0, -1.0 )
  42621. );
  42622. var tex = array< vec2<f32>, 4 >(
  42623. vec2<f32>( 0.0, 0.0 ),
  42624. vec2<f32>( 1.0, 0.0 ),
  42625. vec2<f32>( 0.0, 1.0 ),
  42626. vec2<f32>( 1.0, 1.0 )
  42627. );
  42628. Varys.vTex = tex[ vertexIndex ];
  42629. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  42630. return Varys;
  42631. }
  42632. `;
  42633. const mipmapFragmentSource = `
  42634. @group( 0 ) @binding( 0 )
  42635. var imgSampler : sampler;
  42636. @group( 0 ) @binding( 1 )
  42637. var img : texture_2d<f32>;
  42638. @fragment
  42639. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42640. return textureSample( img, imgSampler, vTex );
  42641. }
  42642. `;
  42643. const flipYFragmentSource = `
  42644. @group( 0 ) @binding( 0 )
  42645. var imgSampler : sampler;
  42646. @group( 0 ) @binding( 1 )
  42647. var img : texture_2d<f32>;
  42648. @fragment
  42649. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42650. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  42651. }
  42652. `;
  42653. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  42654. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  42655. // We'll need a new pipeline for every texture format used.
  42656. this.transferPipelines = {};
  42657. this.flipYPipelines = {};
  42658. this.mipmapVertexShaderModule = device.createShaderModule( {
  42659. label: 'mipmapVertex',
  42660. code: mipmapVertexSource
  42661. } );
  42662. this.mipmapFragmentShaderModule = device.createShaderModule( {
  42663. label: 'mipmapFragment',
  42664. code: mipmapFragmentSource
  42665. } );
  42666. this.flipYFragmentShaderModule = device.createShaderModule( {
  42667. label: 'flipYFragment',
  42668. code: flipYFragmentSource
  42669. } );
  42670. }
  42671. getTransferPipeline( format ) {
  42672. let pipeline = this.transferPipelines[ format ];
  42673. if ( pipeline === undefined ) {
  42674. pipeline = this.device.createRenderPipeline( {
  42675. label: `mipmap-${ format }`,
  42676. vertex: {
  42677. module: this.mipmapVertexShaderModule,
  42678. entryPoint: 'main'
  42679. },
  42680. fragment: {
  42681. module: this.mipmapFragmentShaderModule,
  42682. entryPoint: 'main',
  42683. targets: [ { format } ]
  42684. },
  42685. primitive: {
  42686. topology: GPUPrimitiveTopology.TriangleStrip,
  42687. stripIndexFormat: GPUIndexFormat.Uint32
  42688. },
  42689. layout: 'auto'
  42690. } );
  42691. this.transferPipelines[ format ] = pipeline;
  42692. }
  42693. return pipeline;
  42694. }
  42695. getFlipYPipeline( format ) {
  42696. let pipeline = this.flipYPipelines[ format ];
  42697. if ( pipeline === undefined ) {
  42698. pipeline = this.device.createRenderPipeline( {
  42699. label: `flipY-${ format }`,
  42700. vertex: {
  42701. module: this.mipmapVertexShaderModule,
  42702. entryPoint: 'main'
  42703. },
  42704. fragment: {
  42705. module: this.flipYFragmentShaderModule,
  42706. entryPoint: 'main',
  42707. targets: [ { format } ]
  42708. },
  42709. primitive: {
  42710. topology: GPUPrimitiveTopology.TriangleStrip,
  42711. stripIndexFormat: GPUIndexFormat.Uint32
  42712. },
  42713. layout: 'auto'
  42714. } );
  42715. this.flipYPipelines[ format ] = pipeline;
  42716. }
  42717. return pipeline;
  42718. }
  42719. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42720. const format = textureGPUDescriptor.format;
  42721. const { width, height } = textureGPUDescriptor.size;
  42722. const transferPipeline = this.getTransferPipeline( format );
  42723. const flipYPipeline = this.getFlipYPipeline( format );
  42724. const tempTexture = this.device.createTexture( {
  42725. size: { width, height, depthOrArrayLayers: 1 },
  42726. format,
  42727. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  42728. } );
  42729. const srcView = textureGPU.createView( {
  42730. baseMipLevel: 0,
  42731. mipLevelCount: 1,
  42732. dimension: GPUTextureViewDimension.TwoD,
  42733. baseArrayLayer
  42734. } );
  42735. const dstView = tempTexture.createView( {
  42736. baseMipLevel: 0,
  42737. mipLevelCount: 1,
  42738. dimension: GPUTextureViewDimension.TwoD,
  42739. baseArrayLayer: 0
  42740. } );
  42741. const commandEncoder = this.device.createCommandEncoder( {} );
  42742. const pass = ( pipeline, sourceView, destinationView ) => {
  42743. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42744. const bindGroup = this.device.createBindGroup( {
  42745. layout: bindGroupLayout,
  42746. entries: [ {
  42747. binding: 0,
  42748. resource: this.flipYSampler
  42749. }, {
  42750. binding: 1,
  42751. resource: sourceView
  42752. } ]
  42753. } );
  42754. const passEncoder = commandEncoder.beginRenderPass( {
  42755. colorAttachments: [ {
  42756. view: destinationView,
  42757. loadOp: GPULoadOp.Clear,
  42758. storeOp: GPUStoreOp.Store,
  42759. clearValue: [ 0, 0, 0, 0 ]
  42760. } ]
  42761. } );
  42762. passEncoder.setPipeline( pipeline );
  42763. passEncoder.setBindGroup( 0, bindGroup );
  42764. passEncoder.draw( 4, 1, 0, 0 );
  42765. passEncoder.end();
  42766. };
  42767. pass( transferPipeline, srcView, dstView );
  42768. pass( flipYPipeline, dstView, srcView );
  42769. this.device.queue.submit( [ commandEncoder.finish() ] );
  42770. tempTexture.destroy();
  42771. }
  42772. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42773. const textureData = this.get( textureGPU );
  42774. if ( textureData.useCount === undefined ) {
  42775. textureData.useCount = 0;
  42776. textureData.layers = [];
  42777. }
  42778. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  42779. const commandEncoder = this.device.createCommandEncoder( {} );
  42780. this._mipmapRunBundles( commandEncoder, passes );
  42781. this.device.queue.submit( [ commandEncoder.finish() ] );
  42782. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  42783. textureData.useCount ++;
  42784. }
  42785. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  42786. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  42787. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42788. let srcView = textureGPU.createView( {
  42789. baseMipLevel: 0,
  42790. mipLevelCount: 1,
  42791. dimension: GPUTextureViewDimension.TwoD,
  42792. baseArrayLayer
  42793. } );
  42794. const passes = [];
  42795. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  42796. const bindGroup = this.device.createBindGroup( {
  42797. layout: bindGroupLayout,
  42798. entries: [ {
  42799. binding: 0,
  42800. resource: this.mipmapSampler
  42801. }, {
  42802. binding: 1,
  42803. resource: srcView
  42804. } ]
  42805. } );
  42806. const dstView = textureGPU.createView( {
  42807. baseMipLevel: i,
  42808. mipLevelCount: 1,
  42809. dimension: GPUTextureViewDimension.TwoD,
  42810. baseArrayLayer
  42811. } );
  42812. const passDescriptor = {
  42813. colorAttachments: [ {
  42814. view: dstView,
  42815. loadOp: GPULoadOp.Clear,
  42816. storeOp: GPUStoreOp.Store,
  42817. clearValue: [ 0, 0, 0, 0 ]
  42818. } ]
  42819. };
  42820. const passEncoder = this.device.createRenderBundleEncoder( {
  42821. colorFormats: [ textureGPUDescriptor.format ]
  42822. } );
  42823. passEncoder.setPipeline( pipeline );
  42824. passEncoder.setBindGroup( 0, bindGroup );
  42825. passEncoder.draw( 4, 1, 0, 0 );
  42826. passes.push( {
  42827. renderBundles: [ passEncoder.finish() ],
  42828. passDescriptor
  42829. } );
  42830. srcView = dstView;
  42831. }
  42832. return passes;
  42833. }
  42834. _mipmapRunBundles( commandEncoder, passes ) {
  42835. const levels = passes.length;
  42836. for ( let i = 0; i < levels; i ++ ) {
  42837. const pass = passes[ i ];
  42838. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  42839. passEncoder.executeBundles( pass.renderBundles );
  42840. passEncoder.end();
  42841. }
  42842. }
  42843. }
  42844. const _compareToWebGPU = {
  42845. [ NeverCompare ]: 'never',
  42846. [ LessCompare ]: 'less',
  42847. [ EqualCompare ]: 'equal',
  42848. [ LessEqualCompare ]: 'less-equal',
  42849. [ GreaterCompare ]: 'greater',
  42850. [ GreaterEqualCompare ]: 'greater-equal',
  42851. [ AlwaysCompare ]: 'always',
  42852. [ NotEqualCompare ]: 'not-equal'
  42853. };
  42854. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  42855. class WebGPUTextureUtils {
  42856. constructor( backend ) {
  42857. this.backend = backend;
  42858. this._passUtils = null;
  42859. this.defaultTexture = {};
  42860. this.defaultCubeTexture = {};
  42861. this.defaultVideoFrame = null;
  42862. this.colorBuffer = null;
  42863. this.depthTexture = new DepthTexture();
  42864. this.depthTexture.name = 'depthBuffer';
  42865. }
  42866. createSampler( texture ) {
  42867. const backend = this.backend;
  42868. const device = backend.device;
  42869. const textureGPU = backend.get( texture );
  42870. const samplerDescriptorGPU = {
  42871. addressModeU: this._convertAddressMode( texture.wrapS ),
  42872. addressModeV: this._convertAddressMode( texture.wrapT ),
  42873. addressModeW: this._convertAddressMode( texture.wrapR ),
  42874. magFilter: this._convertFilterMode( texture.magFilter ),
  42875. minFilter: this._convertFilterMode( texture.minFilter ),
  42876. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  42877. maxAnisotropy: texture.anisotropy
  42878. };
  42879. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  42880. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  42881. }
  42882. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  42883. }
  42884. createDefaultTexture( texture ) {
  42885. let textureGPU;
  42886. const format = getFormat( texture );
  42887. if ( texture.isCubeTexture ) {
  42888. textureGPU = this._getDefaultCubeTextureGPU( format );
  42889. } else if ( texture.isVideoTexture ) {
  42890. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  42891. } else {
  42892. textureGPU = this._getDefaultTextureGPU( format );
  42893. }
  42894. this.backend.get( texture ).texture = textureGPU;
  42895. }
  42896. createTexture( texture, options = {} ) {
  42897. const backend = this.backend;
  42898. const textureData = backend.get( texture );
  42899. if ( textureData.initialized ) {
  42900. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  42901. }
  42902. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  42903. if ( options.levels === undefined ) options.levels = 1;
  42904. if ( options.depth === undefined ) options.depth = 1;
  42905. const { width, height, depth, levels } = options;
  42906. const dimension = this._getDimension( texture );
  42907. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  42908. textureData.format = format;
  42909. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  42910. sampleCount = backend.utils.getSampleCount( sampleCount );
  42911. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  42912. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  42913. if ( texture.isStorageTexture === true ) {
  42914. usage |= GPUTextureUsage.STORAGE_BINDING;
  42915. }
  42916. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  42917. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  42918. }
  42919. const textureDescriptorGPU = {
  42920. label: texture.name,
  42921. size: {
  42922. width: width,
  42923. height: height,
  42924. depthOrArrayLayers: depth,
  42925. },
  42926. mipLevelCount: levels,
  42927. sampleCount: primarySampleCount,
  42928. dimension: dimension,
  42929. format: format,
  42930. usage: usage
  42931. };
  42932. // texture creation
  42933. if ( texture.isVideoTexture ) {
  42934. const video = texture.source.data;
  42935. const videoFrame = new VideoFrame( video );
  42936. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  42937. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  42938. videoFrame.close();
  42939. textureData.externalTexture = video;
  42940. } else {
  42941. if ( format === undefined ) {
  42942. console.warn( 'WebGPURenderer: Texture format not supported.' );
  42943. return this.createDefaultTexture( texture );
  42944. }
  42945. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  42946. }
  42947. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  42948. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  42949. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  42950. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  42951. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  42952. }
  42953. textureData.initialized = true;
  42954. textureData.textureDescriptorGPU = textureDescriptorGPU;
  42955. }
  42956. destroyTexture( texture ) {
  42957. const backend = this.backend;
  42958. const textureData = backend.get( texture );
  42959. textureData.texture.destroy();
  42960. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  42961. backend.delete( texture );
  42962. }
  42963. destroySampler( texture ) {
  42964. const backend = this.backend;
  42965. const textureData = backend.get( texture );
  42966. delete textureData.sampler;
  42967. }
  42968. generateMipmaps( texture ) {
  42969. const textureData = this.backend.get( texture );
  42970. if ( texture.isCubeTexture ) {
  42971. for ( let i = 0; i < 6; i ++ ) {
  42972. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42973. }
  42974. } else {
  42975. const depth = texture.image.depth || 1;
  42976. for ( let i = 0; i < depth; i ++ ) {
  42977. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42978. }
  42979. }
  42980. }
  42981. getColorBuffer() {
  42982. if ( this.colorBuffer ) this.colorBuffer.destroy();
  42983. const backend = this.backend;
  42984. const { width, height } = backend.getDrawingBufferSize();
  42985. this.colorBuffer = backend.device.createTexture( {
  42986. label: 'colorBuffer',
  42987. size: {
  42988. width: width,
  42989. height: height,
  42990. depthOrArrayLayers: 1
  42991. },
  42992. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  42993. format: backend.utils.getPreferredCanvasFormat(),
  42994. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  42995. } );
  42996. return this.colorBuffer;
  42997. }
  42998. getDepthBuffer( depth = true, stencil = false ) {
  42999. const backend = this.backend;
  43000. const { width, height } = backend.getDrawingBufferSize();
  43001. const depthTexture = this.depthTexture;
  43002. const depthTextureGPU = backend.get( depthTexture ).texture;
  43003. let format, type;
  43004. if ( stencil ) {
  43005. format = DepthStencilFormat;
  43006. type = UnsignedInt248Type;
  43007. } else if ( depth ) {
  43008. format = DepthFormat;
  43009. type = UnsignedIntType;
  43010. }
  43011. if ( depthTextureGPU !== undefined ) {
  43012. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  43013. return depthTextureGPU;
  43014. }
  43015. this.destroyTexture( depthTexture );
  43016. }
  43017. depthTexture.name = 'depthBuffer';
  43018. depthTexture.format = format;
  43019. depthTexture.type = type;
  43020. depthTexture.image.width = width;
  43021. depthTexture.image.height = height;
  43022. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  43023. return backend.get( depthTexture ).texture;
  43024. }
  43025. updateTexture( texture, options ) {
  43026. const textureData = this.backend.get( texture );
  43027. const { textureDescriptorGPU } = textureData;
  43028. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  43029. return;
  43030. // transfer texture data
  43031. if ( texture.isDataTexture ) {
  43032. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  43033. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  43034. for ( let i = 0; i < options.image.depth; i ++ ) {
  43035. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  43036. }
  43037. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  43038. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  43039. } else if ( texture.isCubeTexture ) {
  43040. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  43041. } else if ( texture.isVideoTexture ) {
  43042. const video = texture.source.data;
  43043. textureData.externalTexture = video;
  43044. } else {
  43045. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  43046. }
  43047. //
  43048. textureData.version = texture.version;
  43049. if ( texture.onUpdate ) texture.onUpdate( texture );
  43050. }
  43051. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  43052. const device = this.backend.device;
  43053. const textureData = this.backend.get( texture );
  43054. const textureGPU = textureData.texture;
  43055. const format = textureData.textureDescriptorGPU.format;
  43056. const bytesPerTexel = this._getBytesPerTexel( format );
  43057. let bytesPerRow = width * bytesPerTexel;
  43058. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  43059. const readBuffer = device.createBuffer(
  43060. {
  43061. size: width * height * bytesPerTexel,
  43062. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43063. }
  43064. );
  43065. const encoder = device.createCommandEncoder();
  43066. encoder.copyTextureToBuffer(
  43067. {
  43068. texture: textureGPU,
  43069. origin: { x, y, z: faceIndex },
  43070. },
  43071. {
  43072. buffer: readBuffer,
  43073. bytesPerRow: bytesPerRow
  43074. },
  43075. {
  43076. width: width,
  43077. height: height
  43078. }
  43079. );
  43080. const typedArrayType = this._getTypedArrayType( format );
  43081. device.queue.submit( [ encoder.finish() ] );
  43082. await readBuffer.mapAsync( GPUMapMode.READ );
  43083. const buffer = readBuffer.getMappedRange();
  43084. return new typedArrayType( buffer );
  43085. }
  43086. _isEnvironmentTexture( texture ) {
  43087. const mapping = texture.mapping;
  43088. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  43089. }
  43090. _getDefaultTextureGPU( format ) {
  43091. let defaultTexture = this.defaultTexture[ format ];
  43092. if ( defaultTexture === undefined ) {
  43093. const texture = new Texture();
  43094. texture.minFilter = NearestFilter;
  43095. texture.magFilter = NearestFilter;
  43096. this.createTexture( texture, { width: 1, height: 1, format } );
  43097. this.defaultTexture[ format ] = defaultTexture = texture;
  43098. }
  43099. return this.backend.get( defaultTexture ).texture;
  43100. }
  43101. _getDefaultCubeTextureGPU( format ) {
  43102. let defaultCubeTexture = this.defaultTexture[ format ];
  43103. if ( defaultCubeTexture === undefined ) {
  43104. const texture = new CubeTexture();
  43105. texture.minFilter = NearestFilter;
  43106. texture.magFilter = NearestFilter;
  43107. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  43108. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  43109. }
  43110. return this.backend.get( defaultCubeTexture ).texture;
  43111. }
  43112. _getDefaultVideoFrame() {
  43113. let defaultVideoFrame = this.defaultVideoFrame;
  43114. if ( defaultVideoFrame === null ) {
  43115. const init = {
  43116. timestamp: 0,
  43117. codedWidth: 1,
  43118. codedHeight: 1,
  43119. format: 'RGBA',
  43120. };
  43121. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  43122. }
  43123. return defaultVideoFrame;
  43124. }
  43125. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  43126. for ( let i = 0; i < 6; i ++ ) {
  43127. const image = images[ i ];
  43128. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  43129. if ( image.isDataTexture ) {
  43130. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  43131. } else {
  43132. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  43133. }
  43134. }
  43135. }
  43136. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  43137. const device = this.backend.device;
  43138. device.queue.copyExternalImageToTexture(
  43139. {
  43140. source: image
  43141. }, {
  43142. texture: textureGPU,
  43143. mipLevel: 0,
  43144. origin: { x: 0, y: 0, z: originDepth }
  43145. }, {
  43146. width: image.width,
  43147. height: image.height,
  43148. depthOrArrayLayers: 1
  43149. }
  43150. );
  43151. if ( flipY === true ) {
  43152. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  43153. }
  43154. }
  43155. _getPassUtils() {
  43156. let passUtils = this._passUtils;
  43157. if ( passUtils === null ) {
  43158. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  43159. }
  43160. return passUtils;
  43161. }
  43162. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  43163. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  43164. }
  43165. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  43166. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  43167. }
  43168. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  43169. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  43170. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  43171. const device = this.backend.device;
  43172. const data = image.data;
  43173. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  43174. const bytesPerRow = image.width * bytesPerTexel;
  43175. device.queue.writeTexture(
  43176. {
  43177. texture: textureGPU,
  43178. mipLevel: 0,
  43179. origin: { x: 0, y: 0, z: originDepth }
  43180. },
  43181. data,
  43182. {
  43183. offset: image.width * image.height * bytesPerTexel * depth,
  43184. bytesPerRow
  43185. },
  43186. {
  43187. width: image.width,
  43188. height: image.height,
  43189. depthOrArrayLayers: 1
  43190. } );
  43191. if ( flipY === true ) {
  43192. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  43193. }
  43194. }
  43195. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  43196. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  43197. const device = this.backend.device;
  43198. const blockData = this._getBlockData( textureDescriptorGPU.format );
  43199. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  43200. for ( let i = 0; i < mipmaps.length; i ++ ) {
  43201. const mipmap = mipmaps[ i ];
  43202. const width = mipmap.width;
  43203. const height = mipmap.height;
  43204. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  43205. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  43206. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  43207. for ( let j = 0; j < depth; j ++ ) {
  43208. device.queue.writeTexture(
  43209. {
  43210. texture: textureGPU,
  43211. mipLevel: i,
  43212. origin: { x: 0, y: 0, z: j }
  43213. },
  43214. mipmap.data,
  43215. {
  43216. offset: j * bytesPerImage,
  43217. bytesPerRow,
  43218. rowsPerImage: Math.ceil( height / blockData.height )
  43219. },
  43220. {
  43221. width: Math.ceil( width / blockData.width ) * blockData.width,
  43222. height: Math.ceil( height / blockData.height ) * blockData.height,
  43223. depthOrArrayLayers: 1
  43224. }
  43225. );
  43226. }
  43227. }
  43228. }
  43229. _getBlockData( format ) {
  43230. // this method is only relevant for compressed texture formats
  43231. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  43232. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  43233. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  43234. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  43235. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  43236. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  43237. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  43238. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  43239. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  43240. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  43241. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  43242. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  43243. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  43244. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  43245. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  43246. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  43247. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  43248. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  43249. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  43250. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  43251. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  43252. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  43253. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  43254. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  43255. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  43256. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  43257. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  43258. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  43259. }
  43260. _convertAddressMode( value ) {
  43261. let addressMode = GPUAddressMode.ClampToEdge;
  43262. if ( value === RepeatWrapping ) {
  43263. addressMode = GPUAddressMode.Repeat;
  43264. } else if ( value === MirroredRepeatWrapping ) {
  43265. addressMode = GPUAddressMode.MirrorRepeat;
  43266. }
  43267. return addressMode;
  43268. }
  43269. _convertFilterMode( value ) {
  43270. let filterMode = GPUFilterMode.Linear;
  43271. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  43272. filterMode = GPUFilterMode.Nearest;
  43273. }
  43274. return filterMode;
  43275. }
  43276. _getBytesPerTexel( format ) {
  43277. // 8-bit formats
  43278. if ( format === GPUTextureFormat.R8Unorm ||
  43279. format === GPUTextureFormat.R8Snorm ||
  43280. format === GPUTextureFormat.R8Uint ||
  43281. format === GPUTextureFormat.R8Sint ) return 1;
  43282. // 16-bit formats
  43283. if ( format === GPUTextureFormat.R16Uint ||
  43284. format === GPUTextureFormat.R16Sint ||
  43285. format === GPUTextureFormat.R16Float ||
  43286. format === GPUTextureFormat.RG8Unorm ||
  43287. format === GPUTextureFormat.RG8Snorm ||
  43288. format === GPUTextureFormat.RG8Uint ||
  43289. format === GPUTextureFormat.RG8Sint ) return 2;
  43290. // 32-bit formats
  43291. if ( format === GPUTextureFormat.R32Uint ||
  43292. format === GPUTextureFormat.R32Sint ||
  43293. format === GPUTextureFormat.R32Float ||
  43294. format === GPUTextureFormat.RG16Uint ||
  43295. format === GPUTextureFormat.RG16Sint ||
  43296. format === GPUTextureFormat.RG16Float ||
  43297. format === GPUTextureFormat.RGBA8Unorm ||
  43298. format === GPUTextureFormat.RGBA8UnormSRGB ||
  43299. format === GPUTextureFormat.RGBA8Snorm ||
  43300. format === GPUTextureFormat.RGBA8Uint ||
  43301. format === GPUTextureFormat.RGBA8Sint ||
  43302. format === GPUTextureFormat.BGRA8Unorm ||
  43303. format === GPUTextureFormat.BGRA8UnormSRGB ||
  43304. // Packed 32-bit formats
  43305. format === GPUTextureFormat.RGB9E5UFloat ||
  43306. format === GPUTextureFormat.RGB10A2Unorm ||
  43307. format === GPUTextureFormat.RG11B10UFloat ||
  43308. format === GPUTextureFormat.Depth32Float ||
  43309. format === GPUTextureFormat.Depth24Plus ||
  43310. format === GPUTextureFormat.Depth24PlusStencil8 ||
  43311. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  43312. // 64-bit formats
  43313. if ( format === GPUTextureFormat.RG32Uint ||
  43314. format === GPUTextureFormat.RG32Sint ||
  43315. format === GPUTextureFormat.RG32Float ||
  43316. format === GPUTextureFormat.RGBA16Uint ||
  43317. format === GPUTextureFormat.RGBA16Sint ||
  43318. format === GPUTextureFormat.RGBA16Float ) return 8;
  43319. // 128-bit formats
  43320. if ( format === GPUTextureFormat.RGBA32Uint ||
  43321. format === GPUTextureFormat.RGBA32Sint ||
  43322. format === GPUTextureFormat.RGBA32Float ) return 16;
  43323. }
  43324. _getTypedArrayType( format ) {
  43325. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  43326. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  43327. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  43328. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  43329. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  43330. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  43331. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  43332. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  43333. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  43334. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  43335. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  43336. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  43337. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  43338. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  43339. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  43340. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  43341. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  43342. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  43343. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  43344. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  43345. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  43346. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  43347. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  43348. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  43349. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  43350. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  43351. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  43352. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  43353. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  43354. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  43355. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  43356. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  43357. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  43358. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  43359. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  43360. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  43361. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  43362. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  43363. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  43364. }
  43365. _getDimension( texture ) {
  43366. let dimension;
  43367. if ( texture.isData3DTexture ) {
  43368. dimension = GPUTextureDimension.ThreeD;
  43369. } else {
  43370. dimension = GPUTextureDimension.TwoD;
  43371. }
  43372. return dimension;
  43373. }
  43374. }
  43375. function getFormat( texture, device = null ) {
  43376. const format = texture.format;
  43377. const type = texture.type;
  43378. const colorSpace = texture.colorSpace;
  43379. let formatGPU;
  43380. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  43381. formatGPU = GPUTextureFormat.BGRA8Unorm;
  43382. } else if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  43383. switch ( format ) {
  43384. case RGBA_S3TC_DXT1_Format:
  43385. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  43386. break;
  43387. case RGBA_S3TC_DXT3_Format:
  43388. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  43389. break;
  43390. case RGBA_S3TC_DXT5_Format:
  43391. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  43392. break;
  43393. case RGB_ETC2_Format:
  43394. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  43395. break;
  43396. case RGBA_ETC2_EAC_Format:
  43397. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  43398. break;
  43399. case RGBA_ASTC_4x4_Format:
  43400. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  43401. break;
  43402. case RGBA_ASTC_5x4_Format:
  43403. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  43404. break;
  43405. case RGBA_ASTC_5x5_Format:
  43406. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  43407. break;
  43408. case RGBA_ASTC_6x5_Format:
  43409. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  43410. break;
  43411. case RGBA_ASTC_6x6_Format:
  43412. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  43413. break;
  43414. case RGBA_ASTC_8x5_Format:
  43415. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  43416. break;
  43417. case RGBA_ASTC_8x6_Format:
  43418. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  43419. break;
  43420. case RGBA_ASTC_8x8_Format:
  43421. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  43422. break;
  43423. case RGBA_ASTC_10x5_Format:
  43424. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  43425. break;
  43426. case RGBA_ASTC_10x6_Format:
  43427. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  43428. break;
  43429. case RGBA_ASTC_10x8_Format:
  43430. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  43431. break;
  43432. case RGBA_ASTC_10x10_Format:
  43433. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  43434. break;
  43435. case RGBA_ASTC_12x10_Format:
  43436. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  43437. break;
  43438. case RGBA_ASTC_12x12_Format:
  43439. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  43440. break;
  43441. default:
  43442. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43443. }
  43444. } else {
  43445. switch ( format ) {
  43446. case RGBAFormat:
  43447. switch ( type ) {
  43448. case ByteType:
  43449. formatGPU = GPUTextureFormat.RGBA8Snorm;
  43450. break;
  43451. case ShortType:
  43452. formatGPU = GPUTextureFormat.RGBA16Sint;
  43453. break;
  43454. case UnsignedShortType:
  43455. formatGPU = GPUTextureFormat.RGBA16Uint;
  43456. break;
  43457. case UnsignedIntType:
  43458. formatGPU = GPUTextureFormat.RGBA32Uint;
  43459. break;
  43460. case IntType:
  43461. formatGPU = GPUTextureFormat.RGBA32Sint;
  43462. break;
  43463. case UnsignedByteType:
  43464. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  43465. break;
  43466. case HalfFloatType:
  43467. formatGPU = GPUTextureFormat.RGBA16Float;
  43468. break;
  43469. case FloatType:
  43470. formatGPU = GPUTextureFormat.RGBA32Float;
  43471. break;
  43472. default:
  43473. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  43474. }
  43475. break;
  43476. case RGBFormat:
  43477. switch ( type ) {
  43478. case UnsignedInt5999Type:
  43479. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  43480. break;
  43481. default:
  43482. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  43483. }
  43484. break;
  43485. case RedFormat:
  43486. switch ( type ) {
  43487. case ByteType:
  43488. formatGPU = GPUTextureFormat.R8Snorm;
  43489. break;
  43490. case ShortType:
  43491. formatGPU = GPUTextureFormat.R16Sint;
  43492. break;
  43493. case UnsignedShortType:
  43494. formatGPU = GPUTextureFormat.R16Uint;
  43495. break;
  43496. case UnsignedIntType:
  43497. formatGPU = GPUTextureFormat.R32Uint;
  43498. break;
  43499. case IntType:
  43500. formatGPU = GPUTextureFormat.R32Sint;
  43501. break;
  43502. case UnsignedByteType:
  43503. formatGPU = GPUTextureFormat.R8Unorm;
  43504. break;
  43505. case HalfFloatType:
  43506. formatGPU = GPUTextureFormat.R16Float;
  43507. break;
  43508. case FloatType:
  43509. formatGPU = GPUTextureFormat.R32Float;
  43510. break;
  43511. default:
  43512. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  43513. }
  43514. break;
  43515. case RGFormat:
  43516. switch ( type ) {
  43517. case ByteType:
  43518. formatGPU = GPUTextureFormat.RG8Snorm;
  43519. break;
  43520. case ShortType:
  43521. formatGPU = GPUTextureFormat.RG16Sint;
  43522. break;
  43523. case UnsignedShortType:
  43524. formatGPU = GPUTextureFormat.RG16Uint;
  43525. break;
  43526. case UnsignedIntType:
  43527. formatGPU = GPUTextureFormat.RG32Uint;
  43528. break;
  43529. case IntType:
  43530. formatGPU = GPUTextureFormat.RG32Sint;
  43531. break;
  43532. case UnsignedByteType:
  43533. formatGPU = GPUTextureFormat.RG8Unorm;
  43534. break;
  43535. case HalfFloatType:
  43536. formatGPU = GPUTextureFormat.RG16Float;
  43537. break;
  43538. case FloatType:
  43539. formatGPU = GPUTextureFormat.RG32Float;
  43540. break;
  43541. default:
  43542. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  43543. }
  43544. break;
  43545. case DepthFormat:
  43546. switch ( type ) {
  43547. case UnsignedShortType:
  43548. formatGPU = GPUTextureFormat.Depth16Unorm;
  43549. break;
  43550. case UnsignedIntType:
  43551. formatGPU = GPUTextureFormat.Depth24Plus;
  43552. break;
  43553. case FloatType:
  43554. formatGPU = GPUTextureFormat.Depth32Float;
  43555. break;
  43556. default:
  43557. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  43558. }
  43559. break;
  43560. case DepthStencilFormat:
  43561. switch ( type ) {
  43562. case UnsignedInt248Type:
  43563. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  43564. break;
  43565. case FloatType:
  43566. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  43567. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  43568. }
  43569. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  43570. break;
  43571. default:
  43572. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  43573. }
  43574. break;
  43575. case RedIntegerFormat:
  43576. switch ( type ) {
  43577. case IntType:
  43578. formatGPU = GPUTextureFormat.R32Sint;
  43579. break;
  43580. case UnsignedIntType:
  43581. formatGPU = GPUTextureFormat.R32Uint;
  43582. break;
  43583. default:
  43584. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  43585. }
  43586. break;
  43587. case RGIntegerFormat:
  43588. switch ( type ) {
  43589. case IntType:
  43590. formatGPU = GPUTextureFormat.RG32Sint;
  43591. break;
  43592. case UnsignedIntType:
  43593. formatGPU = GPUTextureFormat.RG32Uint;
  43594. break;
  43595. default:
  43596. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  43597. }
  43598. break;
  43599. case RGBAIntegerFormat:
  43600. switch ( type ) {
  43601. case IntType:
  43602. formatGPU = GPUTextureFormat.RGBA32Sint;
  43603. break;
  43604. case UnsignedIntType:
  43605. formatGPU = GPUTextureFormat.RGBA32Uint;
  43606. break;
  43607. default:
  43608. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  43609. }
  43610. break;
  43611. default:
  43612. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43613. }
  43614. }
  43615. return formatGPU;
  43616. }
  43617. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  43618. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  43619. const wgslTypeLib$1 = {
  43620. 'f32': 'float',
  43621. 'i32': 'int',
  43622. 'u32': 'uint',
  43623. 'bool': 'bool',
  43624. 'vec2<f32>': 'vec2',
  43625. 'vec2<i32>': 'ivec2',
  43626. 'vec2<u32>': 'uvec2',
  43627. 'vec2<bool>': 'bvec2',
  43628. 'vec2f': 'vec2',
  43629. 'vec2i': 'ivec2',
  43630. 'vec2u': 'uvec2',
  43631. 'vec2b': 'bvec2',
  43632. 'vec3<f32>': 'vec3',
  43633. 'vec3<i32>': 'ivec3',
  43634. 'vec3<u32>': 'uvec3',
  43635. 'vec3<bool>': 'bvec3',
  43636. 'vec3f': 'vec3',
  43637. 'vec3i': 'ivec3',
  43638. 'vec3u': 'uvec3',
  43639. 'vec3b': 'bvec3',
  43640. 'vec4<f32>': 'vec4',
  43641. 'vec4<i32>': 'ivec4',
  43642. 'vec4<u32>': 'uvec4',
  43643. 'vec4<bool>': 'bvec4',
  43644. 'vec4f': 'vec4',
  43645. 'vec4i': 'ivec4',
  43646. 'vec4u': 'uvec4',
  43647. 'vec4b': 'bvec4',
  43648. 'mat2x2<f32>': 'mat2',
  43649. 'mat2x2f': 'mat2',
  43650. 'mat3x3<f32>': 'mat3',
  43651. 'mat3x3f': 'mat3',
  43652. 'mat4x4<f32>': 'mat4',
  43653. 'mat4x4f': 'mat4',
  43654. 'sampler': 'sampler',
  43655. 'texture_1d': 'texture',
  43656. 'texture_2d': 'texture',
  43657. 'texture_2d_array': 'texture',
  43658. 'texture_multisampled_2d': 'cubeTexture',
  43659. 'texture_depth_2d': 'depthTexture',
  43660. 'texture_3d': 'texture3D',
  43661. 'texture_cube': 'cubeTexture',
  43662. 'texture_cube_array': 'cubeTexture',
  43663. 'texture_storage_1d': 'storageTexture',
  43664. 'texture_storage_2d': 'storageTexture',
  43665. 'texture_storage_2d_array': 'storageTexture',
  43666. 'texture_storage_3d': 'storageTexture'
  43667. };
  43668. const parse = ( source ) => {
  43669. source = source.trim();
  43670. const declaration = source.match( declarationRegexp );
  43671. if ( declaration !== null && declaration.length === 4 ) {
  43672. const inputsCode = declaration[ 2 ];
  43673. const propsMatches = [];
  43674. let match = null;
  43675. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  43676. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  43677. }
  43678. // Process matches to correctly pair names and types
  43679. const inputs = [];
  43680. for ( let i = 0; i < propsMatches.length; i ++ ) {
  43681. const { name, type } = propsMatches[ i ];
  43682. let resolvedType = type;
  43683. if ( resolvedType.startsWith( 'texture' ) ) {
  43684. resolvedType = type.split( '<' )[ 0 ];
  43685. }
  43686. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  43687. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  43688. }
  43689. const blockCode = source.substring( declaration[ 0 ].length );
  43690. const outputType = declaration[ 3 ] || 'void';
  43691. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  43692. const type = wgslTypeLib$1[ outputType ] || outputType;
  43693. return {
  43694. type,
  43695. inputs,
  43696. name,
  43697. inputsCode,
  43698. blockCode,
  43699. outputType
  43700. };
  43701. } else {
  43702. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  43703. }
  43704. };
  43705. class WGSLNodeFunction extends NodeFunction {
  43706. constructor( source ) {
  43707. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  43708. super( type, inputs, name );
  43709. this.inputsCode = inputsCode;
  43710. this.blockCode = blockCode;
  43711. this.outputType = outputType;
  43712. }
  43713. getCode( name = this.name ) {
  43714. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  43715. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  43716. }
  43717. }
  43718. class WGSLNodeParser extends NodeParser {
  43719. parseFunction( source ) {
  43720. return new WGSLNodeFunction( source );
  43721. }
  43722. }
  43723. // GPUShaderStage is not defined in browsers not supporting WebGPU
  43724. const GPUShaderStage = self.GPUShaderStage;
  43725. const gpuShaderStageLib = {
  43726. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  43727. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  43728. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  43729. };
  43730. const supports = {
  43731. instance: true,
  43732. swizzleAssign: false,
  43733. storageBuffer: true
  43734. };
  43735. const wgslFnOpLib = {
  43736. '^^': 'tsl_xor'
  43737. };
  43738. const wgslTypeLib = {
  43739. float: 'f32',
  43740. int: 'i32',
  43741. uint: 'u32',
  43742. bool: 'bool',
  43743. color: 'vec3<f32>',
  43744. vec2: 'vec2<f32>',
  43745. ivec2: 'vec2<i32>',
  43746. uvec2: 'vec2<u32>',
  43747. bvec2: 'vec2<bool>',
  43748. vec3: 'vec3<f32>',
  43749. ivec3: 'vec3<i32>',
  43750. uvec3: 'vec3<u32>',
  43751. bvec3: 'vec3<bool>',
  43752. vec4: 'vec4<f32>',
  43753. ivec4: 'vec4<i32>',
  43754. uvec4: 'vec4<u32>',
  43755. bvec4: 'vec4<bool>',
  43756. mat2: 'mat2x2<f32>',
  43757. imat2: 'mat2x2<i32>',
  43758. umat2: 'mat2x2<u32>',
  43759. bmat2: 'mat2x2<bool>',
  43760. mat3: 'mat3x3<f32>',
  43761. imat3: 'mat3x3<i32>',
  43762. umat3: 'mat3x3<u32>',
  43763. bmat3: 'mat3x3<bool>',
  43764. mat4: 'mat4x4<f32>',
  43765. imat4: 'mat4x4<i32>',
  43766. umat4: 'mat4x4<u32>',
  43767. bmat4: 'mat4x4<bool>'
  43768. };
  43769. const wgslPolyfill = {
  43770. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  43771. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  43772. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  43773. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  43774. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  43775. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  43776. 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 ); }' ),
  43777. 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 ); }' ),
  43778. 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 ); }' ),
  43779. repeatWrapping: new CodeNode( `
  43780. fn tsl_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  43781. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  43782. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  43783. }
  43784. ` ),
  43785. biquadraticTexture: new CodeNode( `
  43786. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  43787. let res = vec2f( textureDimensions( map, level ) );
  43788. let uvScaled = coord * res;
  43789. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  43790. // https://www.shadertoy.com/view/WtyXRy
  43791. let uv = uvWrapping - 0.5;
  43792. let iuv = floor( uv );
  43793. let f = fract( uv );
  43794. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ), level );
  43795. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ), level );
  43796. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ), level );
  43797. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ), level );
  43798. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  43799. }
  43800. ` )
  43801. };
  43802. const wgslMethods = {
  43803. dFdx: 'dpdx',
  43804. dFdy: '- dpdy',
  43805. mod_float: 'tsl_mod_float',
  43806. mod_vec2: 'tsl_mod_vec2',
  43807. mod_vec3: 'tsl_mod_vec3',
  43808. mod_vec4: 'tsl_mod_vec4',
  43809. equals_bool: 'tsl_equals_bool',
  43810. equals_bvec2: 'tsl_equals_bvec2',
  43811. equals_bvec3: 'tsl_equals_bvec3',
  43812. equals_bvec4: 'tsl_equals_bvec4',
  43813. inversesqrt: 'inverseSqrt',
  43814. bitcast: 'bitcast<f32>'
  43815. };
  43816. // WebGPU issue: does not support pow() with negative base on Windows
  43817. if ( /Windows/g.test( navigator.userAgent ) ) {
  43818. 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 ); }' );
  43819. 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 ] );
  43820. 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 ] );
  43821. 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 ] );
  43822. wgslMethods.pow_float = 'tsl_pow_float';
  43823. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  43824. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  43825. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  43826. }
  43827. //
  43828. let diagnostics = '';
  43829. if ( /Firefox/g.test( navigator.userAgent ) !== true ) {
  43830. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  43831. }
  43832. //
  43833. class WGSLNodeBuilder extends NodeBuilder {
  43834. constructor( object, renderer ) {
  43835. super( object, renderer, new WGSLNodeParser() );
  43836. this.uniformGroups = {};
  43837. this.builtins = {};
  43838. this.directives = {};
  43839. this.scopedArrays = new Map();
  43840. }
  43841. needsToWorkingColorSpace( texture ) {
  43842. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  43843. }
  43844. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43845. if ( shaderStage === 'fragment' ) {
  43846. if ( depthSnippet ) {
  43847. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  43848. } else {
  43849. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  43850. }
  43851. } else if ( this.isFilteredTexture( texture ) ) {
  43852. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  43853. } else {
  43854. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  43855. }
  43856. }
  43857. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  43858. if ( shaderStage === 'fragment' ) {
  43859. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  43860. } else {
  43861. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  43862. }
  43863. }
  43864. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43865. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  43866. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  43867. } else if ( this.isFilteredTexture( texture ) ) {
  43868. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  43869. } else {
  43870. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  43871. }
  43872. }
  43873. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  43874. this._include( 'biquadraticTexture' );
  43875. return `tsl_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  43876. }
  43877. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  43878. this._include( 'repeatWrapping' );
  43879. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  43880. return `textureLoad( ${ textureProperty }, tsl_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  43881. }
  43882. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  43883. if ( depthSnippet ) {
  43884. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  43885. } else {
  43886. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  43887. }
  43888. }
  43889. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  43890. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  43891. }
  43892. isUnfilterable( texture ) {
  43893. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  43894. }
  43895. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43896. let snippet = null;
  43897. if ( texture.isVideoTexture === true ) {
  43898. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43899. } else if ( this.isUnfilterable( texture ) ) {
  43900. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  43901. } else {
  43902. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  43903. }
  43904. return snippet;
  43905. }
  43906. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43907. if ( shaderStage === 'fragment' ) {
  43908. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  43909. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  43910. } else {
  43911. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  43912. }
  43913. }
  43914. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43915. if ( shaderStage === 'fragment' ) {
  43916. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  43917. } else {
  43918. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  43919. }
  43920. }
  43921. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43922. let snippet = null;
  43923. if ( texture.isVideoTexture === true ) {
  43924. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43925. } else {
  43926. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  43927. }
  43928. return snippet;
  43929. }
  43930. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43931. if ( shaderStage === 'fragment' ) {
  43932. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  43933. } else {
  43934. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  43935. }
  43936. }
  43937. getPropertyName( node, shaderStage = this.shaderStage ) {
  43938. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  43939. if ( shaderStage === 'vertex' ) {
  43940. return `varyings.${ node.name }`;
  43941. }
  43942. } else if ( node.isNodeUniform === true ) {
  43943. const name = node.name;
  43944. const type = node.type;
  43945. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43946. return name;
  43947. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  43948. return `NodeBuffer_${ node.id }.${name}`;
  43949. } else {
  43950. return node.groupNode.name + '.' + name;
  43951. }
  43952. }
  43953. return super.getPropertyName( node );
  43954. }
  43955. getOutputStructName() {
  43956. return 'output';
  43957. }
  43958. _getUniformGroupCount( shaderStage ) {
  43959. return Object.keys( this.uniforms[ shaderStage ] ).length;
  43960. }
  43961. getFunctionOperator( op ) {
  43962. const fnOp = wgslFnOpLib[ op ];
  43963. if ( fnOp !== undefined ) {
  43964. this._include( fnOp );
  43965. return fnOp;
  43966. }
  43967. return null;
  43968. }
  43969. getStorageAccess( node ) {
  43970. if ( node.isStorageTextureNode ) {
  43971. switch ( node.access ) {
  43972. case GPUStorageTextureAccess.ReadOnly:
  43973. return 'read';
  43974. case GPUStorageTextureAccess.WriteOnly:
  43975. return 'write';
  43976. default:
  43977. return 'read_write';
  43978. }
  43979. } else {
  43980. switch ( node.access ) {
  43981. case GPUBufferBindingType.Storage:
  43982. return 'read_write';
  43983. case GPUBufferBindingType.ReadOnlyStorage:
  43984. return 'read';
  43985. default:
  43986. return 'write';
  43987. }
  43988. }
  43989. }
  43990. getUniformFromNode( node, type, shaderStage, name = null ) {
  43991. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  43992. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  43993. if ( nodeData.uniformGPU === undefined ) {
  43994. let uniformGPU;
  43995. const group = node.groupNode;
  43996. const groupName = group.name;
  43997. const bindings = this.getBindGroupArray( groupName, shaderStage );
  43998. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43999. let texture = null;
  44000. if ( type === 'texture' || type === 'storageTexture' ) {
  44001. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  44002. } else if ( type === 'cubeTexture' ) {
  44003. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  44004. } else if ( type === 'texture3D' ) {
  44005. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  44006. }
  44007. texture.store = node.isStorageTextureNode === true;
  44008. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44009. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  44010. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  44011. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44012. bindings.push( sampler, texture );
  44013. uniformGPU = [ sampler, texture ];
  44014. } else {
  44015. bindings.push( texture );
  44016. uniformGPU = [ texture ];
  44017. }
  44018. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  44019. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  44020. const buffer = new bufferClass( node, group );
  44021. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44022. bindings.push( buffer );
  44023. uniformGPU = buffer;
  44024. } else {
  44025. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  44026. let uniformsGroup = uniformsStage[ groupName ];
  44027. if ( uniformsGroup === undefined ) {
  44028. uniformsGroup = new NodeUniformsGroup( groupName, group );
  44029. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44030. uniformsStage[ groupName ] = uniformsGroup;
  44031. bindings.push( uniformsGroup );
  44032. }
  44033. uniformGPU = this.getNodeUniform( uniformNode, type );
  44034. uniformsGroup.addUniform( uniformGPU );
  44035. }
  44036. nodeData.uniformGPU = uniformGPU;
  44037. }
  44038. return uniformNode;
  44039. }
  44040. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  44041. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  44042. if ( map.has( name ) === false ) {
  44043. map.set( name, {
  44044. name,
  44045. property,
  44046. type
  44047. } );
  44048. }
  44049. return property;
  44050. }
  44051. getVertexIndex() {
  44052. if ( this.shaderStage === 'vertex' ) {
  44053. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  44054. }
  44055. return 'vertexIndex';
  44056. }
  44057. buildFunctionCode( shaderNode ) {
  44058. const layout = shaderNode.layout;
  44059. const flowData = this.flowShaderNode( shaderNode );
  44060. const parameters = [];
  44061. for ( const input of layout.inputs ) {
  44062. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  44063. }
  44064. //
  44065. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  44066. ${ flowData.vars }
  44067. ${ flowData.code }
  44068. `;
  44069. if ( flowData.result ) {
  44070. code += `\treturn ${ flowData.result };\n`;
  44071. }
  44072. code += '\n}\n';
  44073. //
  44074. return code;
  44075. }
  44076. getInstanceIndex() {
  44077. if ( this.shaderStage === 'vertex' ) {
  44078. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  44079. }
  44080. return 'instanceIndex';
  44081. }
  44082. getInvocationLocalIndex() {
  44083. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  44084. }
  44085. getSubgroupSize() {
  44086. this.enableSubGroups();
  44087. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  44088. }
  44089. getSubgroupIndex() {
  44090. this.enableSubGroups();
  44091. return this.getBuiltin( 'subgroup_invocation_id', 'subgroupIndex', 'u32', 'attribute' );
  44092. }
  44093. getDrawIndex() {
  44094. return null;
  44095. }
  44096. getFrontFacing() {
  44097. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  44098. }
  44099. getFragCoord() {
  44100. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  44101. }
  44102. getFragDepth() {
  44103. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  44104. }
  44105. isFlipY() {
  44106. return false;
  44107. }
  44108. enableDirective( name, shaderStage = this.shaderStage ) {
  44109. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  44110. stage.add( name );
  44111. }
  44112. getDirectives( shaderStage ) {
  44113. const snippets = [];
  44114. const directives = this.directives[ shaderStage ];
  44115. if ( directives !== undefined ) {
  44116. for ( const directive of directives ) {
  44117. snippets.push( `enable ${directive};` );
  44118. }
  44119. }
  44120. return snippets.join( '\n' );
  44121. }
  44122. enableSubGroups() {
  44123. this.enableDirective( 'subgroups' );
  44124. }
  44125. enableSubgroupsF16() {
  44126. this.enableDirective( 'subgroups-f16' );
  44127. }
  44128. enableClipDistances() {
  44129. this.enableDirective( 'clip_distances' );
  44130. }
  44131. enableShaderF16() {
  44132. this.enableDirective( 'f16' );
  44133. }
  44134. enableDualSourceBlending() {
  44135. this.enableDirective( 'dual_source_blending' );
  44136. }
  44137. getBuiltins( shaderStage ) {
  44138. const snippets = [];
  44139. const builtins = this.builtins[ shaderStage ];
  44140. if ( builtins !== undefined ) {
  44141. for ( const { name, property, type } of builtins.values() ) {
  44142. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  44143. }
  44144. }
  44145. return snippets.join( ',\n\t' );
  44146. }
  44147. getScopedArray( name, scope, bufferType, bufferCount ) {
  44148. if ( this.scopedArrays.has( name ) === false ) {
  44149. this.scopedArrays.set( name, {
  44150. name,
  44151. scope,
  44152. bufferType,
  44153. bufferCount
  44154. } );
  44155. }
  44156. return name;
  44157. }
  44158. getScopedArrays( shaderStage ) {
  44159. if ( shaderStage !== 'compute' ) {
  44160. return;
  44161. }
  44162. const snippets = [];
  44163. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  44164. const type = this.getType( bufferType );
  44165. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  44166. }
  44167. return snippets.join( '\n' );
  44168. }
  44169. getAttributes( shaderStage ) {
  44170. const snippets = [];
  44171. if ( shaderStage === 'compute' ) {
  44172. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  44173. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  44174. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  44175. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  44176. }
  44177. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44178. const builtins = this.getBuiltins( 'attribute' );
  44179. if ( builtins ) snippets.push( builtins );
  44180. const attributes = this.getAttributesArray();
  44181. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  44182. const attribute = attributes[ index ];
  44183. const name = attribute.name;
  44184. const type = this.getType( attribute.type );
  44185. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  44186. }
  44187. }
  44188. return snippets.join( ',\n\t' );
  44189. }
  44190. getStructMembers( struct ) {
  44191. const snippets = [];
  44192. const members = struct.getMemberTypes();
  44193. for ( let i = 0; i < members.length; i ++ ) {
  44194. const member = members[ i ];
  44195. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  44196. }
  44197. const builtins = this.getBuiltins( 'output' );
  44198. if ( builtins ) snippets.push( '\t' + builtins );
  44199. return snippets.join( ',\n' );
  44200. }
  44201. getStructs( shaderStage ) {
  44202. const snippets = [];
  44203. const structs = this.structs[ shaderStage ];
  44204. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  44205. const struct = structs[ index ];
  44206. const name = struct.name;
  44207. let snippet = `\struct ${ name } {\n`;
  44208. snippet += this.getStructMembers( struct );
  44209. snippet += '\n}';
  44210. snippets.push( snippet );
  44211. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  44212. }
  44213. return snippets.join( '\n\n' );
  44214. }
  44215. getVar( type, name ) {
  44216. return `var ${ name } : ${ this.getType( type ) }`;
  44217. }
  44218. getVars( shaderStage ) {
  44219. const snippets = [];
  44220. const vars = this.vars[ shaderStage ];
  44221. if ( vars !== undefined ) {
  44222. for ( const variable of vars ) {
  44223. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  44224. }
  44225. }
  44226. return `\n${ snippets.join( '\n' ) }\n`;
  44227. }
  44228. getVaryings( shaderStage ) {
  44229. const snippets = [];
  44230. if ( shaderStage === 'vertex' ) {
  44231. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  44232. }
  44233. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  44234. const varyings = this.varyings;
  44235. const vars = this.vars[ shaderStage ];
  44236. for ( let index = 0; index < varyings.length; index ++ ) {
  44237. const varying = varyings[ index ];
  44238. if ( varying.needsInterpolation ) {
  44239. let attributesSnippet = `@location( ${index} )`;
  44240. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  44241. attributesSnippet += ' @interpolate( flat )';
  44242. }
  44243. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  44244. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  44245. vars.push( varying );
  44246. }
  44247. }
  44248. }
  44249. const builtins = this.getBuiltins( shaderStage );
  44250. if ( builtins ) snippets.push( builtins );
  44251. const code = snippets.join( ',\n\t' );
  44252. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  44253. }
  44254. getUniforms( shaderStage ) {
  44255. const uniforms = this.uniforms[ shaderStage ];
  44256. const bindingSnippets = [];
  44257. const bufferSnippets = [];
  44258. const structSnippets = [];
  44259. const uniformGroups = {};
  44260. for ( const uniform of uniforms ) {
  44261. const groupName = uniform.groupNode.name;
  44262. const uniformIndexes = this.bindingsIndexes[ groupName ];
  44263. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  44264. const texture = uniform.node.value;
  44265. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  44266. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  44267. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  44268. } else {
  44269. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  44270. }
  44271. }
  44272. let textureType;
  44273. let multisampled = '';
  44274. if ( texture.isMultisampleRenderTargetTexture === true ) {
  44275. multisampled = '_multisampled';
  44276. }
  44277. if ( texture.isCubeTexture === true ) {
  44278. textureType = 'texture_cube<f32>';
  44279. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44280. textureType = 'texture_2d_array<f32>';
  44281. } else if ( texture.isDepthTexture === true ) {
  44282. textureType = `texture_depth${multisampled}_2d`;
  44283. } else if ( texture.isVideoTexture === true ) {
  44284. textureType = 'texture_external';
  44285. } else if ( texture.isData3DTexture === true ) {
  44286. textureType = 'texture_3d<f32>';
  44287. } else if ( uniform.node.isStorageTextureNode === true ) {
  44288. const format = getFormat( texture );
  44289. const access = this.getStorageAccess( uniform.node );
  44290. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  44291. } else {
  44292. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  44293. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  44294. }
  44295. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  44296. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  44297. const bufferNode = uniform.node;
  44298. const bufferType = this.getType( bufferNode.bufferType );
  44299. const bufferCount = bufferNode.bufferCount;
  44300. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  44301. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  44302. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  44303. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  44304. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  44305. } else {
  44306. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  44307. const groupName = uniform.groupNode.name;
  44308. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  44309. index: uniformIndexes.binding ++,
  44310. id: uniformIndexes.group,
  44311. snippets: []
  44312. } );
  44313. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  44314. }
  44315. }
  44316. for ( const name in uniformGroups ) {
  44317. const group = uniformGroups[ name ];
  44318. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  44319. }
  44320. let code = bindingSnippets.join( '\n' );
  44321. code += bufferSnippets.join( '\n' );
  44322. code += structSnippets.join( '\n' );
  44323. return code;
  44324. }
  44325. buildCode() {
  44326. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  44327. this.sortBindingGroups();
  44328. for ( const shaderStage in shadersData ) {
  44329. const stageData = shadersData[ shaderStage ];
  44330. stageData.uniforms = this.getUniforms( shaderStage );
  44331. stageData.attributes = this.getAttributes( shaderStage );
  44332. stageData.varyings = this.getVaryings( shaderStage );
  44333. stageData.structs = this.getStructs( shaderStage );
  44334. stageData.vars = this.getVars( shaderStage );
  44335. stageData.codes = this.getCodes( shaderStage );
  44336. stageData.directives = this.getDirectives( shaderStage );
  44337. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  44338. //
  44339. let flow = '// code\n\n';
  44340. flow += this.flowCode[ shaderStage ];
  44341. const flowNodes = this.flowNodes[ shaderStage ];
  44342. const mainNode = flowNodes[ flowNodes.length - 1 ];
  44343. const outputNode = mainNode.outputNode;
  44344. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  44345. for ( const node of flowNodes ) {
  44346. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  44347. const slotName = node.name;
  44348. if ( slotName ) {
  44349. if ( flow.length > 0 ) flow += '\n';
  44350. flow += `\t// flow -> ${ slotName }\n\t`;
  44351. }
  44352. flow += `${ flowSlotData.code }\n\t`;
  44353. if ( node === mainNode && shaderStage !== 'compute' ) {
  44354. flow += '// result\n\n\t';
  44355. if ( shaderStage === 'vertex' ) {
  44356. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  44357. } else if ( shaderStage === 'fragment' ) {
  44358. if ( isOutputStruct ) {
  44359. stageData.returnType = outputNode.nodeType;
  44360. flow += `return ${ flowSlotData.result };`;
  44361. } else {
  44362. let structSnippet = '\t@location(0) color: vec4<f32>';
  44363. const builtins = this.getBuiltins( 'output' );
  44364. if ( builtins ) structSnippet += ',\n\t' + builtins;
  44365. stageData.returnType = 'OutputStruct';
  44366. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  44367. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  44368. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  44369. }
  44370. }
  44371. }
  44372. }
  44373. stageData.flow = flow;
  44374. }
  44375. if ( this.material !== null ) {
  44376. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  44377. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  44378. } else {
  44379. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  44380. }
  44381. }
  44382. getMethod( method, output = null ) {
  44383. let wgslMethod;
  44384. if ( output !== null ) {
  44385. wgslMethod = this._getWGSLMethod( method + '_' + output );
  44386. }
  44387. if ( wgslMethod === undefined ) {
  44388. wgslMethod = this._getWGSLMethod( method );
  44389. }
  44390. return wgslMethod || method;
  44391. }
  44392. getType( type ) {
  44393. return wgslTypeLib[ type ] || type;
  44394. }
  44395. isAvailable( name ) {
  44396. let result = supports[ name ];
  44397. if ( result === undefined ) {
  44398. if ( name === 'float32Filterable' ) {
  44399. result = this.renderer.hasFeature( 'float32-filterable' );
  44400. }
  44401. supports[ name ] = result;
  44402. }
  44403. return result;
  44404. }
  44405. _getWGSLMethod( method ) {
  44406. if ( wgslPolyfill[ method ] !== undefined ) {
  44407. this._include( method );
  44408. }
  44409. return wgslMethods[ method ];
  44410. }
  44411. _include( name ) {
  44412. const codeNode = wgslPolyfill[ name ];
  44413. codeNode.build( this );
  44414. if ( this.currentFunctionNode !== null ) {
  44415. this.currentFunctionNode.includes.push( codeNode );
  44416. }
  44417. return codeNode;
  44418. }
  44419. _getWGSLVertexCode( shaderData ) {
  44420. return `${ this.getSignature() }
  44421. // directives
  44422. ${shaderData.directives}
  44423. // uniforms
  44424. ${shaderData.uniforms}
  44425. // varyings
  44426. ${shaderData.varyings}
  44427. var<private> varyings : VaryingsStruct;
  44428. // codes
  44429. ${shaderData.codes}
  44430. @vertex
  44431. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  44432. // vars
  44433. ${shaderData.vars}
  44434. // flow
  44435. ${shaderData.flow}
  44436. return varyings;
  44437. }
  44438. `;
  44439. }
  44440. _getWGSLFragmentCode( shaderData ) {
  44441. return `${ this.getSignature() }
  44442. // global
  44443. ${ diagnostics }
  44444. // uniforms
  44445. ${shaderData.uniforms}
  44446. // structs
  44447. ${shaderData.structs}
  44448. // codes
  44449. ${shaderData.codes}
  44450. @fragment
  44451. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  44452. // vars
  44453. ${shaderData.vars}
  44454. // flow
  44455. ${shaderData.flow}
  44456. }
  44457. `;
  44458. }
  44459. _getWGSLComputeCode( shaderData, workgroupSize ) {
  44460. return `${ this.getSignature() }
  44461. // directives
  44462. ${shaderData.directives}
  44463. // system
  44464. var<private> instanceIndex : u32;
  44465. // locals
  44466. ${shaderData.scopedArrays}
  44467. // uniforms
  44468. ${shaderData.uniforms}
  44469. // codes
  44470. ${shaderData.codes}
  44471. @compute @workgroup_size( ${workgroupSize} )
  44472. fn main( ${shaderData.attributes} ) {
  44473. // system
  44474. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  44475. // vars
  44476. ${shaderData.vars}
  44477. // flow
  44478. ${shaderData.flow}
  44479. }
  44480. `;
  44481. }
  44482. _getWGSLStruct( name, vars ) {
  44483. return `
  44484. struct ${name} {
  44485. ${vars}
  44486. };`;
  44487. }
  44488. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  44489. const structName = name + 'Struct';
  44490. const structSnippet = this._getWGSLStruct( structName, vars );
  44491. return `${structSnippet}
  44492. @binding( ${binding} ) @group( ${group} )
  44493. var<${access}> ${name} : ${structName};`;
  44494. }
  44495. }
  44496. class WebGPUUtils {
  44497. constructor( backend ) {
  44498. this.backend = backend;
  44499. }
  44500. getCurrentDepthStencilFormat( renderContext ) {
  44501. let format;
  44502. if ( renderContext.depthTexture !== null ) {
  44503. format = this.getTextureFormatGPU( renderContext.depthTexture );
  44504. } else if ( renderContext.depth && renderContext.stencil ) {
  44505. format = GPUTextureFormat.Depth24PlusStencil8;
  44506. } else if ( renderContext.depth ) {
  44507. format = GPUTextureFormat.Depth24Plus;
  44508. }
  44509. return format;
  44510. }
  44511. getTextureFormatGPU( texture ) {
  44512. return this.backend.get( texture ).format;
  44513. }
  44514. getCurrentColorFormat( renderContext ) {
  44515. let format;
  44516. if ( renderContext.textures !== null ) {
  44517. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  44518. } else {
  44519. format = this.getPreferredCanvasFormat(); // default context format
  44520. }
  44521. return format;
  44522. }
  44523. getCurrentColorSpace( renderContext ) {
  44524. if ( renderContext.textures !== null ) {
  44525. return renderContext.textures[ 0 ].colorSpace;
  44526. }
  44527. return this.backend.renderer.outputColorSpace;
  44528. }
  44529. getPrimitiveTopology( object, material ) {
  44530. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  44531. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  44532. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  44533. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  44534. }
  44535. getSampleCount( sampleCount ) {
  44536. let count = 1;
  44537. if ( sampleCount > 1 ) {
  44538. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  44539. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  44540. if ( count === 2 ) {
  44541. count = 4;
  44542. }
  44543. }
  44544. return count;
  44545. }
  44546. getSampleCountRenderContext( renderContext ) {
  44547. if ( renderContext.textures !== null ) {
  44548. return this.getSampleCount( renderContext.sampleCount );
  44549. }
  44550. return this.getSampleCount( this.backend.renderer.samples );
  44551. }
  44552. getPreferredCanvasFormat() {
  44553. // TODO: Remove this check when Quest 34.5 is out
  44554. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  44555. if ( navigator.userAgent.includes( 'Quest' ) ) {
  44556. return GPUTextureFormat.BGRA8Unorm;
  44557. } else {
  44558. return navigator.gpu.getPreferredCanvasFormat();
  44559. }
  44560. }
  44561. }
  44562. const typedArraysToVertexFormatPrefix = new Map( [
  44563. [ Int8Array, [ 'sint8', 'snorm8' ]],
  44564. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  44565. [ Int16Array, [ 'sint16', 'snorm16' ]],
  44566. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  44567. [ Int32Array, [ 'sint32', 'snorm32' ]],
  44568. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  44569. [ Float32Array, [ 'float32', ]],
  44570. ] );
  44571. const typedAttributeToVertexFormatPrefix = new Map( [
  44572. [ Float16BufferAttribute, [ 'float16', ]],
  44573. ] );
  44574. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  44575. [ Int32Array, 'sint32' ],
  44576. [ Int16Array, 'sint32' ], // patch for INT16
  44577. [ Uint32Array, 'uint32' ],
  44578. [ Uint16Array, 'uint32' ], // patch for UINT16
  44579. [ Float32Array, 'float32' ]
  44580. ] );
  44581. class WebGPUAttributeUtils {
  44582. constructor( backend ) {
  44583. this.backend = backend;
  44584. }
  44585. createAttribute( attribute, usage ) {
  44586. const bufferAttribute = this._getBufferAttribute( attribute );
  44587. const backend = this.backend;
  44588. const bufferData = backend.get( bufferAttribute );
  44589. let buffer = bufferData.buffer;
  44590. if ( buffer === undefined ) {
  44591. const device = backend.device;
  44592. let array = bufferAttribute.array;
  44593. // patch for INT16 and UINT16
  44594. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  44595. const tempArray = new Uint32Array( array.length );
  44596. for ( let i = 0; i < array.length; i ++ ) {
  44597. tempArray[ i ] = array[ i ];
  44598. }
  44599. array = tempArray;
  44600. }
  44601. bufferAttribute.array = array;
  44602. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  44603. array = new array.constructor( bufferAttribute.count * 4 );
  44604. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  44605. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  44606. }
  44607. // Update BufferAttribute
  44608. bufferAttribute.itemSize = 4;
  44609. bufferAttribute.array = array;
  44610. }
  44611. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  44612. buffer = device.createBuffer( {
  44613. label: bufferAttribute.name,
  44614. size: size,
  44615. usage: usage,
  44616. mappedAtCreation: true
  44617. } );
  44618. new array.constructor( buffer.getMappedRange() ).set( array );
  44619. buffer.unmap();
  44620. bufferData.buffer = buffer;
  44621. }
  44622. }
  44623. updateAttribute( attribute ) {
  44624. const bufferAttribute = this._getBufferAttribute( attribute );
  44625. const backend = this.backend;
  44626. const device = backend.device;
  44627. const buffer = backend.get( bufferAttribute ).buffer;
  44628. const array = bufferAttribute.array;
  44629. const updateRanges = bufferAttribute.updateRanges;
  44630. if ( updateRanges.length === 0 ) {
  44631. // Not using update ranges
  44632. device.queue.writeBuffer(
  44633. buffer,
  44634. 0,
  44635. array,
  44636. 0
  44637. );
  44638. } else {
  44639. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  44640. const range = updateRanges[ i ];
  44641. device.queue.writeBuffer(
  44642. buffer,
  44643. 0,
  44644. array,
  44645. range.start * array.BYTES_PER_ELEMENT,
  44646. range.count * array.BYTES_PER_ELEMENT
  44647. );
  44648. }
  44649. bufferAttribute.clearUpdateRanges();
  44650. }
  44651. }
  44652. createShaderVertexBuffers( renderObject ) {
  44653. const attributes = renderObject.getAttributes();
  44654. const vertexBuffers = new Map();
  44655. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  44656. const geometryAttribute = attributes[ slot ];
  44657. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  44658. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  44659. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  44660. if ( vertexBufferLayout === undefined ) {
  44661. let arrayStride, stepMode;
  44662. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  44663. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  44664. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  44665. } else {
  44666. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  44667. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  44668. }
  44669. // patch for INT16 and UINT16
  44670. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  44671. arrayStride = 4;
  44672. }
  44673. vertexBufferLayout = {
  44674. arrayStride,
  44675. attributes: [],
  44676. stepMode
  44677. };
  44678. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  44679. }
  44680. const format = this._getVertexFormat( geometryAttribute );
  44681. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  44682. vertexBufferLayout.attributes.push( {
  44683. shaderLocation: slot,
  44684. offset,
  44685. format
  44686. } );
  44687. }
  44688. return Array.from( vertexBuffers.values() );
  44689. }
  44690. destroyAttribute( attribute ) {
  44691. const backend = this.backend;
  44692. const data = backend.get( this._getBufferAttribute( attribute ) );
  44693. data.buffer.destroy();
  44694. backend.delete( attribute );
  44695. }
  44696. async getArrayBufferAsync( attribute ) {
  44697. const backend = this.backend;
  44698. const device = backend.device;
  44699. const data = backend.get( this._getBufferAttribute( attribute ) );
  44700. const bufferGPU = data.buffer;
  44701. const size = bufferGPU.size;
  44702. const readBufferGPU = device.createBuffer( {
  44703. label: attribute.name,
  44704. size,
  44705. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44706. } );
  44707. const cmdEncoder = device.createCommandEncoder( {} );
  44708. cmdEncoder.copyBufferToBuffer(
  44709. bufferGPU,
  44710. 0,
  44711. readBufferGPU,
  44712. 0,
  44713. size
  44714. );
  44715. readBufferGPU.unmap();
  44716. const gpuCommands = cmdEncoder.finish();
  44717. device.queue.submit( [ gpuCommands ] );
  44718. await readBufferGPU.mapAsync( GPUMapMode.READ );
  44719. const arrayBuffer = readBufferGPU.getMappedRange();
  44720. return arrayBuffer;
  44721. }
  44722. _getVertexFormat( geometryAttribute ) {
  44723. const { itemSize, normalized } = geometryAttribute;
  44724. const ArrayType = geometryAttribute.array.constructor;
  44725. const AttributeType = geometryAttribute.constructor;
  44726. let format;
  44727. if ( itemSize == 1 ) {
  44728. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  44729. } else {
  44730. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  44731. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  44732. if ( prefix ) {
  44733. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  44734. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  44735. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  44736. if ( paddedItemSize % 1 ) {
  44737. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  44738. }
  44739. format = `${prefix}x${paddedItemSize}`;
  44740. }
  44741. }
  44742. if ( ! format ) {
  44743. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  44744. }
  44745. return format;
  44746. }
  44747. _getBufferAttribute( attribute ) {
  44748. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  44749. return attribute;
  44750. }
  44751. }
  44752. class WebGPUBindingUtils {
  44753. constructor( backend ) {
  44754. this.backend = backend;
  44755. this.bindGroupLayoutCache = new WeakMap();
  44756. }
  44757. createBindingsLayout( bindGroup ) {
  44758. const backend = this.backend;
  44759. const device = backend.device;
  44760. const entries = [];
  44761. let index = 0;
  44762. for ( const binding of bindGroup.bindings ) {
  44763. const bindingGPU = {
  44764. binding: index ++,
  44765. visibility: binding.visibility
  44766. };
  44767. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  44768. const buffer = {}; // GPUBufferBindingLayout
  44769. if ( binding.isStorageBuffer ) {
  44770. buffer.type = binding.access;
  44771. }
  44772. bindingGPU.buffer = buffer;
  44773. } else if ( binding.isSampler ) {
  44774. const sampler = {}; // GPUSamplerBindingLayout
  44775. if ( binding.texture.isDepthTexture ) {
  44776. if ( binding.texture.compareFunction !== null ) {
  44777. sampler.type = 'comparison';
  44778. }
  44779. }
  44780. bindingGPU.sampler = sampler;
  44781. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  44782. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  44783. } else if ( binding.isSampledTexture && binding.store ) {
  44784. const format = this.backend.get( binding.texture ).texture.format;
  44785. const access = binding.access;
  44786. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  44787. } else if ( binding.isSampledTexture ) {
  44788. const texture = {}; // GPUTextureBindingLayout
  44789. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  44790. texture.multisampled = true;
  44791. }
  44792. if ( binding.texture.isDepthTexture ) {
  44793. texture.sampleType = GPUTextureSampleType.Depth;
  44794. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  44795. const type = binding.texture.type;
  44796. if ( type === IntType ) {
  44797. texture.sampleType = GPUTextureSampleType.SInt;
  44798. } else if ( type === UnsignedIntType ) {
  44799. texture.sampleType = GPUTextureSampleType.UInt;
  44800. } else if ( type === FloatType ) {
  44801. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  44802. texture.sampleType = GPUTextureSampleType.Float;
  44803. } else {
  44804. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  44805. }
  44806. }
  44807. }
  44808. if ( binding.isSampledCubeTexture ) {
  44809. texture.viewDimension = GPUTextureViewDimension.Cube;
  44810. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44811. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  44812. } else if ( binding.isSampledTexture3D ) {
  44813. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  44814. }
  44815. bindingGPU.texture = texture;
  44816. } else {
  44817. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  44818. }
  44819. entries.push( bindingGPU );
  44820. }
  44821. return device.createBindGroupLayout( { entries } );
  44822. }
  44823. createBindings( bindGroup ) {
  44824. const { backend, bindGroupLayoutCache } = this;
  44825. const bindingsData = backend.get( bindGroup );
  44826. // setup (static) binding layout and (dynamic) binding group
  44827. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  44828. if ( bindLayoutGPU === undefined ) {
  44829. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  44830. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  44831. }
  44832. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  44833. bindingsData.layout = bindLayoutGPU;
  44834. bindingsData.group = bindGroupGPU;
  44835. }
  44836. updateBinding( binding ) {
  44837. const backend = this.backend;
  44838. const device = backend.device;
  44839. const buffer = binding.buffer;
  44840. const bufferGPU = backend.get( binding ).buffer;
  44841. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  44842. }
  44843. createBindGroup( bindGroup, layoutGPU ) {
  44844. const backend = this.backend;
  44845. const device = backend.device;
  44846. let bindingPoint = 0;
  44847. const entriesGPU = [];
  44848. for ( const binding of bindGroup.bindings ) {
  44849. if ( binding.isUniformBuffer ) {
  44850. const bindingData = backend.get( binding );
  44851. if ( bindingData.buffer === undefined ) {
  44852. const byteLength = binding.byteLength;
  44853. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  44854. const bufferGPU = device.createBuffer( {
  44855. label: 'bindingBuffer_' + binding.name,
  44856. size: byteLength,
  44857. usage: usage
  44858. } );
  44859. bindingData.buffer = bufferGPU;
  44860. }
  44861. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44862. } else if ( binding.isStorageBuffer ) {
  44863. const bindingData = backend.get( binding );
  44864. if ( bindingData.buffer === undefined ) {
  44865. const attribute = binding.attribute;
  44866. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  44867. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  44868. bindingData.buffer = backend.get( attribute ).buffer;
  44869. }
  44870. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44871. } else if ( binding.isSampler ) {
  44872. const textureGPU = backend.get( binding.texture );
  44873. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  44874. } else if ( binding.isSampledTexture ) {
  44875. const textureData = backend.get( binding.texture );
  44876. let resourceGPU;
  44877. if ( textureData.externalTexture !== undefined ) {
  44878. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  44879. } else {
  44880. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  44881. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  44882. resourceGPU = textureData[ propertyName ];
  44883. if ( resourceGPU === undefined ) {
  44884. const aspectGPU = GPUTextureAspect.All;
  44885. let dimensionViewGPU;
  44886. if ( binding.isSampledCubeTexture ) {
  44887. dimensionViewGPU = GPUTextureViewDimension.Cube;
  44888. } else if ( binding.isSampledTexture3D ) {
  44889. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  44890. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44891. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  44892. } else {
  44893. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  44894. }
  44895. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  44896. }
  44897. }
  44898. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  44899. }
  44900. bindingPoint ++;
  44901. }
  44902. return device.createBindGroup( {
  44903. label: 'bindGroup_' + bindGroup.name,
  44904. layout: layoutGPU,
  44905. entries: entriesGPU
  44906. } );
  44907. }
  44908. }
  44909. class WebGPUPipelineUtils {
  44910. constructor( backend ) {
  44911. this.backend = backend;
  44912. }
  44913. _getSampleCount( renderObjectContext ) {
  44914. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  44915. }
  44916. createRenderPipeline( renderObject, promises ) {
  44917. const { object, material, geometry, pipeline } = renderObject;
  44918. const { vertexProgram, fragmentProgram } = pipeline;
  44919. const backend = this.backend;
  44920. const device = backend.device;
  44921. const utils = backend.utils;
  44922. const pipelineData = backend.get( pipeline );
  44923. // bind group layouts
  44924. const bindGroupLayouts = [];
  44925. for ( const bindGroup of renderObject.getBindings() ) {
  44926. const bindingsData = backend.get( bindGroup );
  44927. bindGroupLayouts.push( bindingsData.layout );
  44928. }
  44929. // vertex buffers
  44930. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  44931. // blending
  44932. let blending;
  44933. if ( material.transparent === true && material.blending !== NoBlending ) {
  44934. blending = this._getBlending( material );
  44935. }
  44936. // stencil
  44937. let stencilFront = {};
  44938. if ( material.stencilWrite === true ) {
  44939. stencilFront = {
  44940. compare: this._getStencilCompare( material ),
  44941. failOp: this._getStencilOperation( material.stencilFail ),
  44942. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  44943. passOp: this._getStencilOperation( material.stencilZPass )
  44944. };
  44945. }
  44946. const colorWriteMask = this._getColorWriteMask( material );
  44947. const targets = [];
  44948. if ( renderObject.context.textures !== null ) {
  44949. const textures = renderObject.context.textures;
  44950. for ( let i = 0; i < textures.length; i ++ ) {
  44951. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  44952. targets.push( {
  44953. format: colorFormat,
  44954. blend: blending,
  44955. writeMask: colorWriteMask
  44956. } );
  44957. }
  44958. } else {
  44959. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44960. targets.push( {
  44961. format: colorFormat,
  44962. blend: blending,
  44963. writeMask: colorWriteMask
  44964. } );
  44965. }
  44966. const vertexModule = backend.get( vertexProgram ).module;
  44967. const fragmentModule = backend.get( fragmentProgram ).module;
  44968. const primitiveState = this._getPrimitiveState( object, geometry, material );
  44969. const depthCompare = this._getDepthCompare( material );
  44970. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44971. const sampleCount = this._getSampleCount( renderObject.context );
  44972. const pipelineDescriptor = {
  44973. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  44974. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  44975. fragment: Object.assign( {}, fragmentModule, { targets } ),
  44976. primitive: primitiveState,
  44977. depthStencil: {
  44978. format: depthStencilFormat,
  44979. depthWriteEnabled: material.depthWrite,
  44980. depthCompare: depthCompare,
  44981. stencilFront: stencilFront,
  44982. stencilBack: {}, // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  44983. stencilReadMask: material.stencilFuncMask,
  44984. stencilWriteMask: material.stencilWriteMask
  44985. },
  44986. multisample: {
  44987. count: sampleCount,
  44988. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  44989. },
  44990. layout: device.createPipelineLayout( {
  44991. bindGroupLayouts
  44992. } )
  44993. };
  44994. if ( promises === null ) {
  44995. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  44996. } else {
  44997. const p = new Promise( ( resolve /*, reject*/ ) => {
  44998. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  44999. pipelineData.pipeline = pipeline;
  45000. resolve();
  45001. } );
  45002. } );
  45003. promises.push( p );
  45004. }
  45005. }
  45006. createBundleEncoder( renderContext ) {
  45007. const backend = this.backend;
  45008. const { utils, device } = backend;
  45009. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  45010. const colorFormat = utils.getCurrentColorFormat( renderContext );
  45011. const sampleCount = this._getSampleCount( renderContext );
  45012. const descriptor = {
  45013. label: 'renderBundleEncoder',
  45014. colorFormats: [ colorFormat ],
  45015. depthStencilFormat,
  45016. sampleCount
  45017. };
  45018. return device.createRenderBundleEncoder( descriptor );
  45019. }
  45020. createComputePipeline( pipeline, bindings ) {
  45021. const backend = this.backend;
  45022. const device = backend.device;
  45023. const computeProgram = backend.get( pipeline.computeProgram ).module;
  45024. const pipelineGPU = backend.get( pipeline );
  45025. // bind group layouts
  45026. const bindGroupLayouts = [];
  45027. for ( const bindingsGroup of bindings ) {
  45028. const bindingsData = backend.get( bindingsGroup );
  45029. bindGroupLayouts.push( bindingsData.layout );
  45030. }
  45031. pipelineGPU.pipeline = device.createComputePipeline( {
  45032. compute: computeProgram,
  45033. layout: device.createPipelineLayout( {
  45034. bindGroupLayouts
  45035. } )
  45036. } );
  45037. }
  45038. _getBlending( material ) {
  45039. let color, alpha;
  45040. const blending = material.blending;
  45041. const blendSrc = material.blendSrc;
  45042. const blendDst = material.blendDst;
  45043. const blendEquation = material.blendEquation;
  45044. if ( blending === CustomBlending ) {
  45045. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  45046. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  45047. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  45048. color = {
  45049. srcFactor: this._getBlendFactor( blendSrc ),
  45050. dstFactor: this._getBlendFactor( blendDst ),
  45051. operation: this._getBlendOperation( blendEquation )
  45052. };
  45053. alpha = {
  45054. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  45055. dstFactor: this._getBlendFactor( blendDstAlpha ),
  45056. operation: this._getBlendOperation( blendEquationAlpha )
  45057. };
  45058. } else {
  45059. const premultipliedAlpha = material.premultipliedAlpha;
  45060. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  45061. color = {
  45062. srcFactor: srcRGB,
  45063. dstFactor: dstRGB,
  45064. operation: GPUBlendOperation.Add
  45065. };
  45066. alpha = {
  45067. srcFactor: srcAlpha,
  45068. dstFactor: dstAlpha,
  45069. operation: GPUBlendOperation.Add
  45070. };
  45071. };
  45072. if ( premultipliedAlpha ) {
  45073. switch ( blending ) {
  45074. case NormalBlending:
  45075. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  45076. break;
  45077. case AdditiveBlending:
  45078. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  45079. break;
  45080. case SubtractiveBlending:
  45081. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  45082. break;
  45083. case MultiplyBlending:
  45084. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  45085. break;
  45086. }
  45087. } else {
  45088. switch ( blending ) {
  45089. case NormalBlending:
  45090. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  45091. break;
  45092. case AdditiveBlending:
  45093. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  45094. break;
  45095. case SubtractiveBlending:
  45096. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  45097. break;
  45098. case MultiplyBlending:
  45099. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  45100. break;
  45101. }
  45102. }
  45103. }
  45104. if ( color !== undefined && alpha !== undefined ) {
  45105. return { color, alpha };
  45106. } else {
  45107. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  45108. }
  45109. }
  45110. _getBlendFactor( blend ) {
  45111. let blendFactor;
  45112. switch ( blend ) {
  45113. case ZeroFactor:
  45114. blendFactor = GPUBlendFactor.Zero;
  45115. break;
  45116. case OneFactor:
  45117. blendFactor = GPUBlendFactor.One;
  45118. break;
  45119. case SrcColorFactor:
  45120. blendFactor = GPUBlendFactor.Src;
  45121. break;
  45122. case OneMinusSrcColorFactor:
  45123. blendFactor = GPUBlendFactor.OneMinusSrc;
  45124. break;
  45125. case SrcAlphaFactor:
  45126. blendFactor = GPUBlendFactor.SrcAlpha;
  45127. break;
  45128. case OneMinusSrcAlphaFactor:
  45129. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  45130. break;
  45131. case DstColorFactor:
  45132. blendFactor = GPUBlendFactor.Dst;
  45133. break;
  45134. case OneMinusDstColorFactor:
  45135. blendFactor = GPUBlendFactor.OneMinusDstColor;
  45136. break;
  45137. case DstAlphaFactor:
  45138. blendFactor = GPUBlendFactor.DstAlpha;
  45139. break;
  45140. case OneMinusDstAlphaFactor:
  45141. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  45142. break;
  45143. case SrcAlphaSaturateFactor:
  45144. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  45145. break;
  45146. case BlendColorFactor:
  45147. blendFactor = GPUBlendFactor.Constant;
  45148. break;
  45149. case OneMinusBlendColorFactor:
  45150. blendFactor = GPUBlendFactor.OneMinusConstant;
  45151. break;
  45152. default:
  45153. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  45154. }
  45155. return blendFactor;
  45156. }
  45157. _getStencilCompare( material ) {
  45158. let stencilCompare;
  45159. const stencilFunc = material.stencilFunc;
  45160. switch ( stencilFunc ) {
  45161. case NeverStencilFunc:
  45162. stencilCompare = GPUCompareFunction.Never;
  45163. break;
  45164. case AlwaysStencilFunc:
  45165. stencilCompare = GPUCompareFunction.Always;
  45166. break;
  45167. case LessStencilFunc:
  45168. stencilCompare = GPUCompareFunction.Less;
  45169. break;
  45170. case LessEqualStencilFunc:
  45171. stencilCompare = GPUCompareFunction.LessEqual;
  45172. break;
  45173. case EqualStencilFunc:
  45174. stencilCompare = GPUCompareFunction.Equal;
  45175. break;
  45176. case GreaterEqualStencilFunc:
  45177. stencilCompare = GPUCompareFunction.GreaterEqual;
  45178. break;
  45179. case GreaterStencilFunc:
  45180. stencilCompare = GPUCompareFunction.Greater;
  45181. break;
  45182. case NotEqualStencilFunc:
  45183. stencilCompare = GPUCompareFunction.NotEqual;
  45184. break;
  45185. default:
  45186. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  45187. }
  45188. return stencilCompare;
  45189. }
  45190. _getStencilOperation( op ) {
  45191. let stencilOperation;
  45192. switch ( op ) {
  45193. case KeepStencilOp:
  45194. stencilOperation = GPUStencilOperation.Keep;
  45195. break;
  45196. case ZeroStencilOp:
  45197. stencilOperation = GPUStencilOperation.Zero;
  45198. break;
  45199. case ReplaceStencilOp:
  45200. stencilOperation = GPUStencilOperation.Replace;
  45201. break;
  45202. case InvertStencilOp:
  45203. stencilOperation = GPUStencilOperation.Invert;
  45204. break;
  45205. case IncrementStencilOp:
  45206. stencilOperation = GPUStencilOperation.IncrementClamp;
  45207. break;
  45208. case DecrementStencilOp:
  45209. stencilOperation = GPUStencilOperation.DecrementClamp;
  45210. break;
  45211. case IncrementWrapStencilOp:
  45212. stencilOperation = GPUStencilOperation.IncrementWrap;
  45213. break;
  45214. case DecrementWrapStencilOp:
  45215. stencilOperation = GPUStencilOperation.DecrementWrap;
  45216. break;
  45217. default:
  45218. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  45219. }
  45220. return stencilOperation;
  45221. }
  45222. _getBlendOperation( blendEquation ) {
  45223. let blendOperation;
  45224. switch ( blendEquation ) {
  45225. case AddEquation:
  45226. blendOperation = GPUBlendOperation.Add;
  45227. break;
  45228. case SubtractEquation:
  45229. blendOperation = GPUBlendOperation.Subtract;
  45230. break;
  45231. case ReverseSubtractEquation:
  45232. blendOperation = GPUBlendOperation.ReverseSubtract;
  45233. break;
  45234. case MinEquation:
  45235. blendOperation = GPUBlendOperation.Min;
  45236. break;
  45237. case MaxEquation:
  45238. blendOperation = GPUBlendOperation.Max;
  45239. break;
  45240. default:
  45241. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  45242. }
  45243. return blendOperation;
  45244. }
  45245. _getPrimitiveState( object, geometry, material ) {
  45246. const descriptor = {};
  45247. const utils = this.backend.utils;
  45248. descriptor.topology = utils.getPrimitiveTopology( object, material );
  45249. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  45250. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  45251. }
  45252. switch ( material.side ) {
  45253. case FrontSide:
  45254. descriptor.frontFace = GPUFrontFace.CCW;
  45255. descriptor.cullMode = GPUCullMode.Back;
  45256. break;
  45257. case BackSide:
  45258. descriptor.frontFace = GPUFrontFace.CCW;
  45259. descriptor.cullMode = GPUCullMode.Front;
  45260. break;
  45261. case DoubleSide:
  45262. descriptor.frontFace = GPUFrontFace.CCW;
  45263. descriptor.cullMode = GPUCullMode.None;
  45264. break;
  45265. default:
  45266. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  45267. break;
  45268. }
  45269. return descriptor;
  45270. }
  45271. _getColorWriteMask( material ) {
  45272. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  45273. }
  45274. _getDepthCompare( material ) {
  45275. let depthCompare;
  45276. if ( material.depthTest === false ) {
  45277. depthCompare = GPUCompareFunction.Always;
  45278. } else {
  45279. const depthFunc = material.depthFunc;
  45280. switch ( depthFunc ) {
  45281. case NeverDepth:
  45282. depthCompare = GPUCompareFunction.Never;
  45283. break;
  45284. case AlwaysDepth:
  45285. depthCompare = GPUCompareFunction.Always;
  45286. break;
  45287. case LessDepth:
  45288. depthCompare = GPUCompareFunction.Less;
  45289. break;
  45290. case LessEqualDepth:
  45291. depthCompare = GPUCompareFunction.LessEqual;
  45292. break;
  45293. case EqualDepth:
  45294. depthCompare = GPUCompareFunction.Equal;
  45295. break;
  45296. case GreaterEqualDepth:
  45297. depthCompare = GPUCompareFunction.GreaterEqual;
  45298. break;
  45299. case GreaterDepth:
  45300. depthCompare = GPUCompareFunction.Greater;
  45301. break;
  45302. case NotEqualDepth:
  45303. depthCompare = GPUCompareFunction.NotEqual;
  45304. break;
  45305. default:
  45306. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  45307. }
  45308. }
  45309. return depthCompare;
  45310. }
  45311. }
  45312. /*// debugger tools
  45313. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  45314. //*/
  45315. //
  45316. class WebGPUBackend extends Backend {
  45317. constructor( parameters = {} ) {
  45318. super( parameters );
  45319. this.isWebGPUBackend = true;
  45320. // some parameters require default values other than "undefined"
  45321. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  45322. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  45323. this.trackTimestamp = ( parameters.trackTimestamp === true );
  45324. this.device = null;
  45325. this.context = null;
  45326. this.colorBuffer = null;
  45327. this.defaultRenderPassdescriptor = null;
  45328. this.utils = new WebGPUUtils( this );
  45329. this.attributeUtils = new WebGPUAttributeUtils( this );
  45330. this.bindingUtils = new WebGPUBindingUtils( this );
  45331. this.pipelineUtils = new WebGPUPipelineUtils( this );
  45332. this.textureUtils = new WebGPUTextureUtils( this );
  45333. this.occludedResolveCache = new Map();
  45334. }
  45335. async init( renderer ) {
  45336. await super.init( renderer );
  45337. //
  45338. const parameters = this.parameters;
  45339. // create the device if it is not passed with parameters
  45340. let device;
  45341. if ( parameters.device === undefined ) {
  45342. const adapterOptions = {
  45343. powerPreference: parameters.powerPreference
  45344. };
  45345. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  45346. if ( adapter === null ) {
  45347. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  45348. }
  45349. // feature support
  45350. const features = Object.values( GPUFeatureName );
  45351. const supportedFeatures = [];
  45352. for ( const name of features ) {
  45353. if ( adapter.features.has( name ) ) {
  45354. supportedFeatures.push( name );
  45355. }
  45356. }
  45357. const deviceDescriptor = {
  45358. requiredFeatures: supportedFeatures,
  45359. requiredLimits: parameters.requiredLimits
  45360. };
  45361. device = await adapter.requestDevice( deviceDescriptor );
  45362. } else {
  45363. device = parameters.device;
  45364. }
  45365. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  45366. this.device = device;
  45367. this.context = context;
  45368. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  45369. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  45370. this.context.configure( {
  45371. device: this.device,
  45372. format: this.utils.getPreferredCanvasFormat(),
  45373. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  45374. alphaMode: alphaMode
  45375. } );
  45376. this.updateSize();
  45377. }
  45378. get coordinateSystem() {
  45379. return WebGPUCoordinateSystem;
  45380. }
  45381. async getArrayBufferAsync( attribute ) {
  45382. return await this.attributeUtils.getArrayBufferAsync( attribute );
  45383. }
  45384. getContext() {
  45385. return this.context;
  45386. }
  45387. _getDefaultRenderPassDescriptor() {
  45388. let descriptor = this.defaultRenderPassdescriptor;
  45389. if ( descriptor === null ) {
  45390. const renderer = this.renderer;
  45391. descriptor = {
  45392. colorAttachments: [ {
  45393. view: null
  45394. } ],
  45395. depthStencilAttachment: {
  45396. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  45397. }
  45398. };
  45399. const colorAttachment = descriptor.colorAttachments[ 0 ];
  45400. if ( this.renderer.samples > 0 ) {
  45401. colorAttachment.view = this.colorBuffer.createView();
  45402. } else {
  45403. colorAttachment.resolveTarget = undefined;
  45404. }
  45405. this.defaultRenderPassdescriptor = descriptor;
  45406. }
  45407. const colorAttachment = descriptor.colorAttachments[ 0 ];
  45408. if ( this.renderer.samples > 0 ) {
  45409. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  45410. } else {
  45411. colorAttachment.view = this.context.getCurrentTexture().createView();
  45412. }
  45413. return descriptor;
  45414. }
  45415. _getRenderPassDescriptor( renderContext ) {
  45416. const renderTarget = renderContext.renderTarget;
  45417. const renderTargetData = this.get( renderTarget );
  45418. let descriptors = renderTargetData.descriptors;
  45419. if ( descriptors === undefined ||
  45420. renderTargetData.width !== renderTarget.width ||
  45421. renderTargetData.height !== renderTarget.height ||
  45422. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  45423. renderTargetData.samples !== renderTarget.samples
  45424. ) {
  45425. descriptors = {};
  45426. renderTargetData.descriptors = descriptors;
  45427. // dispose
  45428. const onDispose = () => {
  45429. renderTarget.removeEventListener( 'dispose', onDispose );
  45430. this.delete( renderTarget );
  45431. };
  45432. renderTarget.addEventListener( 'dispose', onDispose );
  45433. }
  45434. const cacheKey = renderContext.getCacheKey();
  45435. let descriptor = descriptors[ cacheKey ];
  45436. if ( descriptor === undefined ) {
  45437. const textures = renderContext.textures;
  45438. const colorAttachments = [];
  45439. for ( let i = 0; i < textures.length; i ++ ) {
  45440. const textureData = this.get( textures[ i ] );
  45441. const textureView = textureData.texture.createView( {
  45442. baseMipLevel: renderContext.activeMipmapLevel,
  45443. mipLevelCount: 1,
  45444. baseArrayLayer: renderContext.activeCubeFace,
  45445. dimension: GPUTextureViewDimension.TwoD
  45446. } );
  45447. let view, resolveTarget;
  45448. if ( textureData.msaaTexture !== undefined ) {
  45449. view = textureData.msaaTexture.createView();
  45450. resolveTarget = textureView;
  45451. } else {
  45452. view = textureView;
  45453. resolveTarget = undefined;
  45454. }
  45455. colorAttachments.push( {
  45456. view,
  45457. resolveTarget,
  45458. loadOp: GPULoadOp.Load,
  45459. storeOp: GPUStoreOp.Store
  45460. } );
  45461. }
  45462. const depthTextureData = this.get( renderContext.depthTexture );
  45463. const depthStencilAttachment = {
  45464. view: depthTextureData.texture.createView()
  45465. };
  45466. descriptor = {
  45467. colorAttachments,
  45468. depthStencilAttachment
  45469. };
  45470. descriptors[ cacheKey ] = descriptor;
  45471. renderTargetData.width = renderTarget.width;
  45472. renderTargetData.height = renderTarget.height;
  45473. renderTargetData.samples = renderTarget.samples;
  45474. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  45475. }
  45476. return descriptor;
  45477. }
  45478. beginRender( renderContext ) {
  45479. const renderContextData = this.get( renderContext );
  45480. const device = this.device;
  45481. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45482. let occlusionQuerySet;
  45483. if ( occlusionQueryCount > 0 ) {
  45484. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  45485. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  45486. // Get a reference to the array of objects with queries. The renderContextData property
  45487. // can be changed by another render pass before the buffer.mapAsyc() completes.
  45488. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  45489. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  45490. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  45491. //
  45492. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  45493. renderContextData.occlusionQuerySet = occlusionQuerySet;
  45494. renderContextData.occlusionQueryIndex = 0;
  45495. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  45496. renderContextData.lastOcclusionObject = null;
  45497. }
  45498. let descriptor;
  45499. if ( renderContext.textures === null ) {
  45500. descriptor = this._getDefaultRenderPassDescriptor();
  45501. } else {
  45502. descriptor = this._getRenderPassDescriptor( renderContext );
  45503. }
  45504. this.initTimestampQuery( renderContext, descriptor );
  45505. descriptor.occlusionQuerySet = occlusionQuerySet;
  45506. const depthStencilAttachment = descriptor.depthStencilAttachment;
  45507. if ( renderContext.textures !== null ) {
  45508. const colorAttachments = descriptor.colorAttachments;
  45509. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  45510. const colorAttachment = colorAttachments[ i ];
  45511. if ( renderContext.clearColor ) {
  45512. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  45513. colorAttachment.loadOp = GPULoadOp.Clear;
  45514. colorAttachment.storeOp = GPUStoreOp.Store;
  45515. } else {
  45516. colorAttachment.loadOp = GPULoadOp.Load;
  45517. colorAttachment.storeOp = GPUStoreOp.Store;
  45518. }
  45519. }
  45520. } else {
  45521. const colorAttachment = descriptor.colorAttachments[ 0 ];
  45522. if ( renderContext.clearColor ) {
  45523. colorAttachment.clearValue = renderContext.clearColorValue;
  45524. colorAttachment.loadOp = GPULoadOp.Clear;
  45525. colorAttachment.storeOp = GPUStoreOp.Store;
  45526. } else {
  45527. colorAttachment.loadOp = GPULoadOp.Load;
  45528. colorAttachment.storeOp = GPUStoreOp.Store;
  45529. }
  45530. }
  45531. //
  45532. if ( renderContext.depth ) {
  45533. if ( renderContext.clearDepth ) {
  45534. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  45535. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  45536. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45537. } else {
  45538. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45539. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45540. }
  45541. }
  45542. if ( renderContext.stencil ) {
  45543. if ( renderContext.clearStencil ) {
  45544. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  45545. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  45546. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45547. } else {
  45548. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45549. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45550. }
  45551. }
  45552. //
  45553. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  45554. const currentPass = encoder.beginRenderPass( descriptor );
  45555. //
  45556. renderContextData.descriptor = descriptor;
  45557. renderContextData.encoder = encoder;
  45558. renderContextData.currentPass = currentPass;
  45559. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45560. renderContextData.renderBundles = [];
  45561. //
  45562. if ( renderContext.viewport ) {
  45563. this.updateViewport( renderContext );
  45564. }
  45565. if ( renderContext.scissor ) {
  45566. const { x, y, width, height } = renderContext.scissorValue;
  45567. currentPass.setScissorRect( x, y, width, height );
  45568. }
  45569. }
  45570. finishRender( renderContext ) {
  45571. const renderContextData = this.get( renderContext );
  45572. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45573. if ( renderContextData.renderBundles.length > 0 ) {
  45574. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  45575. }
  45576. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  45577. renderContextData.currentPass.endOcclusionQuery();
  45578. }
  45579. renderContextData.currentPass.end();
  45580. if ( occlusionQueryCount > 0 ) {
  45581. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  45582. //
  45583. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  45584. if ( queryResolveBuffer === undefined ) {
  45585. queryResolveBuffer = this.device.createBuffer(
  45586. {
  45587. size: bufferSize,
  45588. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  45589. }
  45590. );
  45591. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  45592. }
  45593. //
  45594. const readBuffer = this.device.createBuffer(
  45595. {
  45596. size: bufferSize,
  45597. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  45598. }
  45599. );
  45600. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  45601. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  45602. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  45603. renderContextData.occlusionQueryBuffer = readBuffer;
  45604. //
  45605. this.resolveOccludedAsync( renderContext );
  45606. }
  45607. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  45608. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  45609. //
  45610. if ( renderContext.textures !== null ) {
  45611. const textures = renderContext.textures;
  45612. for ( let i = 0; i < textures.length; i ++ ) {
  45613. const texture = textures[ i ];
  45614. if ( texture.generateMipmaps === true ) {
  45615. this.textureUtils.generateMipmaps( texture );
  45616. }
  45617. }
  45618. }
  45619. }
  45620. isOccluded( renderContext, object ) {
  45621. const renderContextData = this.get( renderContext );
  45622. return renderContextData.occluded && renderContextData.occluded.has( object );
  45623. }
  45624. async resolveOccludedAsync( renderContext ) {
  45625. const renderContextData = this.get( renderContext );
  45626. // handle occlusion query results
  45627. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  45628. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  45629. const occluded = new WeakSet();
  45630. renderContextData.currentOcclusionQueryObjects = null;
  45631. renderContextData.currentOcclusionQueryBuffer = null;
  45632. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  45633. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  45634. const results = new BigUint64Array( buffer );
  45635. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  45636. if ( results[ i ] !== BigInt( 0 ) ) {
  45637. occluded.add( currentOcclusionQueryObjects[ i ] );
  45638. }
  45639. }
  45640. currentOcclusionQueryBuffer.destroy();
  45641. renderContextData.occluded = occluded;
  45642. }
  45643. }
  45644. updateViewport( renderContext ) {
  45645. const { currentPass } = this.get( renderContext );
  45646. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  45647. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  45648. }
  45649. clear( color, depth, stencil, renderTargetData = null ) {
  45650. const device = this.device;
  45651. const renderer = this.renderer;
  45652. let colorAttachments = [];
  45653. let depthStencilAttachment;
  45654. let clearValue;
  45655. let supportsDepth;
  45656. let supportsStencil;
  45657. if ( color ) {
  45658. const clearColor = this.getClearColor();
  45659. if ( this.renderer.alpha === true ) {
  45660. // premultiply alpha
  45661. const a = clearColor.a;
  45662. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  45663. } else {
  45664. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  45665. }
  45666. }
  45667. if ( renderTargetData === null ) {
  45668. supportsDepth = renderer.depth;
  45669. supportsStencil = renderer.stencil;
  45670. const descriptor = this._getDefaultRenderPassDescriptor();
  45671. if ( color ) {
  45672. colorAttachments = descriptor.colorAttachments;
  45673. const colorAttachment = colorAttachments[ 0 ];
  45674. colorAttachment.clearValue = clearValue;
  45675. colorAttachment.loadOp = GPULoadOp.Clear;
  45676. colorAttachment.storeOp = GPUStoreOp.Store;
  45677. }
  45678. if ( supportsDepth || supportsStencil ) {
  45679. depthStencilAttachment = descriptor.depthStencilAttachment;
  45680. }
  45681. } else {
  45682. supportsDepth = renderTargetData.depth;
  45683. supportsStencil = renderTargetData.stencil;
  45684. if ( color ) {
  45685. for ( const texture of renderTargetData.textures ) {
  45686. const textureData = this.get( texture );
  45687. const textureView = textureData.texture.createView();
  45688. let view, resolveTarget;
  45689. if ( textureData.msaaTexture !== undefined ) {
  45690. view = textureData.msaaTexture.createView();
  45691. resolveTarget = textureView;
  45692. } else {
  45693. view = textureView;
  45694. resolveTarget = undefined;
  45695. }
  45696. colorAttachments.push( {
  45697. view,
  45698. resolveTarget,
  45699. clearValue,
  45700. loadOp: GPULoadOp.Clear,
  45701. storeOp: GPUStoreOp.Store
  45702. } );
  45703. }
  45704. }
  45705. if ( supportsDepth || supportsStencil ) {
  45706. const depthTextureData = this.get( renderTargetData.depthTexture );
  45707. depthStencilAttachment = {
  45708. view: depthTextureData.texture.createView()
  45709. };
  45710. }
  45711. }
  45712. //
  45713. if ( supportsDepth ) {
  45714. if ( depth ) {
  45715. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  45716. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  45717. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45718. } else {
  45719. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45720. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  45721. }
  45722. }
  45723. //
  45724. if ( supportsStencil ) {
  45725. if ( stencil ) {
  45726. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  45727. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  45728. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45729. } else {
  45730. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45731. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  45732. }
  45733. }
  45734. //
  45735. const encoder = device.createCommandEncoder( {} );
  45736. const currentPass = encoder.beginRenderPass( {
  45737. colorAttachments,
  45738. depthStencilAttachment
  45739. } );
  45740. currentPass.end();
  45741. device.queue.submit( [ encoder.finish() ] );
  45742. }
  45743. // compute
  45744. beginCompute( computeGroup ) {
  45745. const groupGPU = this.get( computeGroup );
  45746. const descriptor = {};
  45747. this.initTimestampQuery( computeGroup, descriptor );
  45748. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  45749. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  45750. }
  45751. compute( computeGroup, computeNode, bindings, pipeline ) {
  45752. const { passEncoderGPU } = this.get( computeGroup );
  45753. // pipeline
  45754. const pipelineGPU = this.get( pipeline ).pipeline;
  45755. passEncoderGPU.setPipeline( pipelineGPU );
  45756. // bind groups
  45757. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45758. const bindGroup = bindings[ i ];
  45759. const bindingsData = this.get( bindGroup );
  45760. passEncoderGPU.setBindGroup( i, bindingsData.group );
  45761. }
  45762. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  45763. const computeNodeData = this.get( computeNode );
  45764. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  45765. const { dispatchSize } = computeNodeData;
  45766. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  45767. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  45768. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  45769. } else {
  45770. dispatchSize.x = computeNode.dispatchCount;
  45771. }
  45772. passEncoderGPU.dispatchWorkgroups(
  45773. dispatchSize.x,
  45774. dispatchSize.y,
  45775. dispatchSize.z
  45776. );
  45777. }
  45778. finishCompute( computeGroup ) {
  45779. const groupData = this.get( computeGroup );
  45780. groupData.passEncoderGPU.end();
  45781. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  45782. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  45783. }
  45784. // render object
  45785. draw( renderObject, info ) {
  45786. const { object, context, pipeline } = renderObject;
  45787. const bindings = renderObject.getBindings();
  45788. const renderContextData = this.get( context );
  45789. const pipelineGPU = this.get( pipeline ).pipeline;
  45790. const currentSets = renderContextData.currentSets;
  45791. const passEncoderGPU = renderContextData.currentPass;
  45792. const drawParms = renderObject.getDrawParameters();
  45793. if ( drawParms === null ) return;
  45794. // pipeline
  45795. if ( currentSets.pipeline !== pipelineGPU ) {
  45796. passEncoderGPU.setPipeline( pipelineGPU );
  45797. currentSets.pipeline = pipelineGPU;
  45798. }
  45799. // bind groups
  45800. const currentBindingGroups = currentSets.bindingGroups;
  45801. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45802. const bindGroup = bindings[ i ];
  45803. const bindingsData = this.get( bindGroup );
  45804. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  45805. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  45806. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  45807. }
  45808. }
  45809. // attributes
  45810. const index = renderObject.getIndex();
  45811. const hasIndex = ( index !== null );
  45812. // index
  45813. if ( hasIndex === true ) {
  45814. if ( currentSets.index !== index ) {
  45815. const buffer = this.get( index ).buffer;
  45816. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  45817. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  45818. currentSets.index = index;
  45819. }
  45820. }
  45821. // vertex buffers
  45822. const vertexBuffers = renderObject.getVertexBuffers();
  45823. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  45824. const vertexBuffer = vertexBuffers[ i ];
  45825. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  45826. const buffer = this.get( vertexBuffer ).buffer;
  45827. passEncoderGPU.setVertexBuffer( i, buffer );
  45828. currentSets.attributes[ i ] = vertexBuffer;
  45829. }
  45830. }
  45831. // occlusion queries - handle multiple consecutive draw calls for an object
  45832. if ( renderContextData.occlusionQuerySet !== undefined ) {
  45833. const lastObject = renderContextData.lastOcclusionObject;
  45834. if ( lastObject !== object ) {
  45835. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  45836. passEncoderGPU.endOcclusionQuery();
  45837. renderContextData.occlusionQueryIndex ++;
  45838. }
  45839. if ( object.occlusionTest === true ) {
  45840. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  45841. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  45842. }
  45843. renderContextData.lastOcclusionObject = object;
  45844. }
  45845. }
  45846. // draw
  45847. if ( object.isBatchedMesh === true ) {
  45848. const starts = object._multiDrawStarts;
  45849. const counts = object._multiDrawCounts;
  45850. const drawCount = object._multiDrawCount;
  45851. const drawInstances = object._multiDrawInstances;
  45852. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  45853. for ( let i = 0; i < drawCount; i ++ ) {
  45854. const count = drawInstances ? drawInstances[ i ] : 1;
  45855. const firstInstance = count > 1 ? 0 : i;
  45856. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  45857. }
  45858. } else if ( hasIndex === true ) {
  45859. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParms;
  45860. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  45861. info.update( object, indexCount, instanceCount );
  45862. } else {
  45863. const { vertexCount, instanceCount, firstVertex } = drawParms;
  45864. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  45865. info.update( object, vertexCount, instanceCount );
  45866. }
  45867. }
  45868. // cache key
  45869. needsRenderUpdate( renderObject ) {
  45870. const data = this.get( renderObject );
  45871. const { object, material } = renderObject;
  45872. const utils = this.utils;
  45873. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  45874. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  45875. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  45876. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  45877. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  45878. let needsUpdate = false;
  45879. if ( data.material !== material || data.materialVersion !== material.version ||
  45880. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  45881. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  45882. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  45883. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  45884. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  45885. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  45886. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  45887. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  45888. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  45889. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  45890. data.primitiveTopology !== primitiveTopology ||
  45891. data.clippingContextCacheKey !== renderObject.clippingContext.cacheKey
  45892. ) {
  45893. data.material = material; data.materialVersion = material.version;
  45894. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  45895. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  45896. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  45897. data.colorWrite = material.colorWrite;
  45898. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  45899. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  45900. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  45901. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  45902. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  45903. data.sampleCount = sampleCount;
  45904. data.colorSpace = colorSpace;
  45905. data.colorFormat = colorFormat;
  45906. data.depthStencilFormat = depthStencilFormat;
  45907. data.primitiveTopology = primitiveTopology;
  45908. data.clippingContextCacheKey = renderObject.clippingContext.cacheKey;
  45909. needsUpdate = true;
  45910. }
  45911. return needsUpdate;
  45912. }
  45913. getRenderCacheKey( renderObject ) {
  45914. const { object, material } = renderObject;
  45915. const utils = this.utils;
  45916. const renderContext = renderObject.context;
  45917. return [
  45918. material.transparent, material.blending, material.premultipliedAlpha,
  45919. material.blendSrc, material.blendDst, material.blendEquation,
  45920. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  45921. material.colorWrite,
  45922. material.depthWrite, material.depthTest, material.depthFunc,
  45923. material.stencilWrite, material.stencilFunc,
  45924. material.stencilFail, material.stencilZFail, material.stencilZPass,
  45925. material.stencilFuncMask, material.stencilWriteMask,
  45926. material.side,
  45927. utils.getSampleCountRenderContext( renderContext ),
  45928. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  45929. utils.getPrimitiveTopology( object, material ),
  45930. renderObject.clippingContext.cacheKey
  45931. ].join();
  45932. }
  45933. // textures
  45934. createSampler( texture ) {
  45935. this.textureUtils.createSampler( texture );
  45936. }
  45937. destroySampler( texture ) {
  45938. this.textureUtils.destroySampler( texture );
  45939. }
  45940. createDefaultTexture( texture ) {
  45941. this.textureUtils.createDefaultTexture( texture );
  45942. }
  45943. createTexture( texture, options ) {
  45944. this.textureUtils.createTexture( texture, options );
  45945. }
  45946. updateTexture( texture, options ) {
  45947. this.textureUtils.updateTexture( texture, options );
  45948. }
  45949. generateMipmaps( texture ) {
  45950. this.textureUtils.generateMipmaps( texture );
  45951. }
  45952. destroyTexture( texture ) {
  45953. this.textureUtils.destroyTexture( texture );
  45954. }
  45955. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  45956. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  45957. }
  45958. initTimestampQuery( renderContext, descriptor ) {
  45959. if ( ! this.trackTimestamp ) return;
  45960. const renderContextData = this.get( renderContext );
  45961. if ( ! renderContextData.timeStampQuerySet ) {
  45962. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  45963. // beginning and one for the end of compute pass execution.
  45964. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  45965. const timestampWrites = {
  45966. querySet: timeStampQuerySet,
  45967. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  45968. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  45969. };
  45970. Object.assign( descriptor, {
  45971. timestampWrites,
  45972. } );
  45973. renderContextData.timeStampQuerySet = timeStampQuerySet;
  45974. }
  45975. }
  45976. // timestamp utils
  45977. prepareTimestampBuffer( renderContext, encoder ) {
  45978. if ( ! this.trackTimestamp ) return;
  45979. const renderContextData = this.get( renderContext );
  45980. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  45981. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  45982. renderContextData.currentTimestampQueryBuffers = {
  45983. resolveBuffer: this.device.createBuffer( {
  45984. label: 'timestamp resolve buffer',
  45985. size: size,
  45986. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  45987. } ),
  45988. resultBuffer: this.device.createBuffer( {
  45989. label: 'timestamp result buffer',
  45990. size: size,
  45991. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  45992. } ),
  45993. isMappingPending: false,
  45994. };
  45995. }
  45996. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  45997. if ( isMappingPending === true ) return;
  45998. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  45999. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  46000. }
  46001. async resolveTimestampAsync( renderContext, type = 'render' ) {
  46002. if ( ! this.trackTimestamp ) return;
  46003. const renderContextData = this.get( renderContext );
  46004. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  46005. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  46006. if ( isMappingPending === true ) return;
  46007. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  46008. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  46009. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  46010. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  46011. this.renderer.info.updateTimestamp( type, duration );
  46012. resultBuffer.unmap();
  46013. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  46014. } );
  46015. }
  46016. // node builder
  46017. createNodeBuilder( object, renderer ) {
  46018. return new WGSLNodeBuilder( object, renderer );
  46019. }
  46020. // program
  46021. createProgram( program ) {
  46022. const programGPU = this.get( program );
  46023. programGPU.module = {
  46024. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  46025. entryPoint: 'main'
  46026. };
  46027. }
  46028. destroyProgram( program ) {
  46029. this.delete( program );
  46030. }
  46031. // pipelines
  46032. createRenderPipeline( renderObject, promises ) {
  46033. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  46034. }
  46035. createComputePipeline( computePipeline, bindings ) {
  46036. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  46037. }
  46038. beginBundle( renderContext ) {
  46039. const renderContextData = this.get( renderContext );
  46040. renderContextData._currentPass = renderContextData.currentPass;
  46041. renderContextData._currentSets = renderContextData.currentSets;
  46042. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  46043. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  46044. }
  46045. finishBundle( renderContext, bundle ) {
  46046. const renderContextData = this.get( renderContext );
  46047. const bundleEncoder = renderContextData.currentPass;
  46048. const bundleGPU = bundleEncoder.finish();
  46049. this.get( bundle ).bundleGPU = bundleGPU;
  46050. // restore render pass state
  46051. renderContextData.currentSets = renderContextData._currentSets;
  46052. renderContextData.currentPass = renderContextData._currentPass;
  46053. }
  46054. addBundle( renderContext, bundle ) {
  46055. const renderContextData = this.get( renderContext );
  46056. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  46057. }
  46058. // bindings
  46059. createBindings( bindGroup ) {
  46060. this.bindingUtils.createBindings( bindGroup );
  46061. }
  46062. updateBindings( bindGroup ) {
  46063. this.bindingUtils.createBindings( bindGroup );
  46064. }
  46065. updateBinding( binding ) {
  46066. this.bindingUtils.updateBinding( binding );
  46067. }
  46068. // attributes
  46069. createIndexAttribute( attribute ) {
  46070. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  46071. }
  46072. createAttribute( attribute ) {
  46073. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  46074. }
  46075. createStorageAttribute( attribute ) {
  46076. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  46077. }
  46078. updateAttribute( attribute ) {
  46079. this.attributeUtils.updateAttribute( attribute );
  46080. }
  46081. destroyAttribute( attribute ) {
  46082. this.attributeUtils.destroyAttribute( attribute );
  46083. }
  46084. // canvas
  46085. updateSize() {
  46086. this.colorBuffer = this.textureUtils.getColorBuffer();
  46087. this.defaultRenderPassdescriptor = null;
  46088. }
  46089. // utils public
  46090. getMaxAnisotropy() {
  46091. return 16;
  46092. }
  46093. hasFeature( name ) {
  46094. return this.device.features.has( name );
  46095. }
  46096. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  46097. let dstX = 0;
  46098. let dstY = 0;
  46099. let dstLayer = 0;
  46100. let srcX = 0;
  46101. let srcY = 0;
  46102. let srcLayer = 0;
  46103. let srcWidth = srcTexture.image.width;
  46104. let srcHeight = srcTexture.image.height;
  46105. if ( srcRegion !== null ) {
  46106. srcX = srcRegion.x;
  46107. srcY = srcRegion.y;
  46108. srcLayer = srcRegion.z || 0;
  46109. srcWidth = srcRegion.width;
  46110. srcHeight = srcRegion.height;
  46111. }
  46112. if ( dstPosition !== null ) {
  46113. dstX = dstPosition.x;
  46114. dstY = dstPosition.y;
  46115. dstLayer = dstPosition.z || 0;
  46116. }
  46117. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  46118. const sourceGPU = this.get( srcTexture ).texture;
  46119. const destinationGPU = this.get( dstTexture ).texture;
  46120. encoder.copyTextureToTexture(
  46121. {
  46122. texture: sourceGPU,
  46123. mipLevel: level,
  46124. origin: { x: srcX, y: srcY, z: srcLayer }
  46125. },
  46126. {
  46127. texture: destinationGPU,
  46128. mipLevel: level,
  46129. origin: { x: dstX, y: dstY, z: dstLayer }
  46130. },
  46131. [
  46132. srcWidth,
  46133. srcHeight,
  46134. 1
  46135. ]
  46136. );
  46137. this.device.queue.submit( [ encoder.finish() ] );
  46138. }
  46139. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  46140. const renderContextData = this.get( renderContext );
  46141. const { encoder, descriptor } = renderContextData;
  46142. let sourceGPU = null;
  46143. if ( renderContext.renderTarget ) {
  46144. if ( texture.isDepthTexture ) {
  46145. sourceGPU = this.get( renderContext.depthTexture ).texture;
  46146. } else {
  46147. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  46148. }
  46149. } else {
  46150. if ( texture.isDepthTexture ) {
  46151. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  46152. } else {
  46153. sourceGPU = this.context.getCurrentTexture();
  46154. }
  46155. }
  46156. const destinationGPU = this.get( texture ).texture;
  46157. if ( sourceGPU.format !== destinationGPU.format ) {
  46158. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  46159. return;
  46160. }
  46161. renderContextData.currentPass.end();
  46162. encoder.copyTextureToTexture(
  46163. {
  46164. texture: sourceGPU,
  46165. origin: { x: rectangle.x, y: rectangle.y, z: 0 }
  46166. },
  46167. {
  46168. texture: destinationGPU
  46169. },
  46170. [
  46171. rectangle.z,
  46172. rectangle.w
  46173. ]
  46174. );
  46175. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  46176. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  46177. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  46178. }
  46179. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  46180. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  46181. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  46182. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  46183. }
  46184. }
  46185. class IESSpotLight extends SpotLight {
  46186. constructor( color, intensity, distance, angle, penumbra, decay ) {
  46187. super( color, intensity, distance, angle, penumbra, decay );
  46188. this.iesMap = null;
  46189. }
  46190. copy( source, recursive ) {
  46191. super.copy( source, recursive );
  46192. this.iesMap = source.iesMap;
  46193. return this;
  46194. }
  46195. }
  46196. class BasicNodeLibrary extends NodeLibrary {
  46197. constructor() {
  46198. super();
  46199. this.addLight( PointLightNode, PointLight );
  46200. this.addLight( DirectionalLightNode, DirectionalLight );
  46201. this.addLight( RectAreaLightNode, RectAreaLight );
  46202. this.addLight( SpotLightNode, SpotLight );
  46203. this.addLight( AmbientLightNode, AmbientLight );
  46204. this.addLight( HemisphereLightNode, HemisphereLight );
  46205. this.addLight( LightProbeNode, LightProbe );
  46206. this.addLight( IESSpotLightNode, IESSpotLight );
  46207. this.addToneMapping( linearToneMapping, LinearToneMapping );
  46208. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  46209. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  46210. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  46211. this.addToneMapping( agxToneMapping, AgXToneMapping );
  46212. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  46213. this.addColorSpace( linearSRGBTosRGB, getColorSpaceMethod( LinearSRGBColorSpace, SRGBColorSpace ) );
  46214. this.addColorSpace( sRGBToLinearSRGB, getColorSpaceMethod( SRGBColorSpace, LinearSRGBColorSpace ) );
  46215. }
  46216. }
  46217. class WebGPURenderer extends Renderer {
  46218. constructor( parameters = {} ) {
  46219. let BackendClass;
  46220. if ( parameters.forceWebGL ) {
  46221. BackendClass = WebGLBackend;
  46222. } else {
  46223. BackendClass = WebGPUBackend;
  46224. parameters.getFallback = () => {
  46225. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  46226. return new WebGLBackend( parameters );
  46227. };
  46228. }
  46229. const backend = new BackendClass( parameters );
  46230. super( backend, parameters );
  46231. this.nodes.library = new BasicNodeLibrary();
  46232. this.isWebGPURenderer = true;
  46233. }
  46234. }
  46235. const _material = /*@__PURE__*/ new NodeMaterial();
  46236. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  46237. class PostProcessing {
  46238. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  46239. this.renderer = renderer;
  46240. this.outputNode = outputNode;
  46241. this.outputColorTransform = true;
  46242. this.needsUpdate = true;
  46243. _material.name = 'PostProcessing';
  46244. }
  46245. render() {
  46246. this.update();
  46247. const renderer = this.renderer;
  46248. const toneMapping = renderer.toneMapping;
  46249. const outputColorSpace = renderer.outputColorSpace;
  46250. renderer.toneMapping = NoToneMapping;
  46251. renderer.outputColorSpace = LinearSRGBColorSpace;
  46252. //
  46253. _quadMesh.render( renderer );
  46254. //
  46255. renderer.toneMapping = toneMapping;
  46256. renderer.outputColorSpace = outputColorSpace;
  46257. }
  46258. update() {
  46259. if ( this.needsUpdate === true ) {
  46260. const renderer = this.renderer;
  46261. const toneMapping = renderer.toneMapping;
  46262. const outputColorSpace = renderer.outputColorSpace;
  46263. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  46264. _quadMesh.material.needsUpdate = true;
  46265. this.needsUpdate = false;
  46266. }
  46267. }
  46268. async renderAsync() {
  46269. this.update();
  46270. const renderer = this.renderer;
  46271. const toneMapping = renderer.toneMapping;
  46272. const outputColorSpace = renderer.outputColorSpace;
  46273. renderer.toneMapping = NoToneMapping;
  46274. renderer.outputColorSpace = LinearSRGBColorSpace;
  46275. //
  46276. await _quadMesh.renderAsync( renderer );
  46277. //
  46278. renderer.toneMapping = toneMapping;
  46279. renderer.outputColorSpace = outputColorSpace;
  46280. }
  46281. }
  46282. class StorageTexture extends Texture {
  46283. constructor( width = 1, height = 1 ) {
  46284. super();
  46285. this.image = { width, height };
  46286. this.magFilter = LinearFilter;
  46287. this.minFilter = LinearFilter;
  46288. this.isStorageTexture = true;
  46289. }
  46290. }
  46291. class StorageBufferAttribute extends BufferAttribute {
  46292. constructor( array, itemSize, typeClass = Float32Array ) {
  46293. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  46294. super( array, itemSize );
  46295. this.isStorageBufferAttribute = true;
  46296. }
  46297. }
  46298. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  46299. constructor( array, itemSize, typeClass = Float32Array ) {
  46300. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  46301. super( array, itemSize );
  46302. this.isStorageInstancedBufferAttribute = true;
  46303. }
  46304. }
  46305. class NodeLoader extends Loader {
  46306. constructor( manager ) {
  46307. super( manager );
  46308. this.textures = {};
  46309. this.nodes = {};
  46310. }
  46311. load( url, onLoad, onProgress, onError ) {
  46312. const loader = new FileLoader( this.manager );
  46313. loader.setPath( this.path );
  46314. loader.setRequestHeader( this.requestHeader );
  46315. loader.setWithCredentials( this.withCredentials );
  46316. loader.load( url, ( text ) => {
  46317. try {
  46318. onLoad( this.parse( JSON.parse( text ) ) );
  46319. } catch ( e ) {
  46320. if ( onError ) {
  46321. onError( e );
  46322. } else {
  46323. console.error( e );
  46324. }
  46325. this.manager.itemError( url );
  46326. }
  46327. }, onProgress, onError );
  46328. }
  46329. parseNodes( json ) {
  46330. const nodes = {};
  46331. if ( json !== undefined ) {
  46332. for ( const nodeJSON of json ) {
  46333. const { uuid, type } = nodeJSON;
  46334. nodes[ uuid ] = this.createNodeFromType( type );
  46335. nodes[ uuid ].uuid = uuid;
  46336. }
  46337. const meta = { nodes, textures: this.textures };
  46338. for ( const nodeJSON of json ) {
  46339. nodeJSON.meta = meta;
  46340. const node = nodes[ nodeJSON.uuid ];
  46341. node.deserialize( nodeJSON );
  46342. delete nodeJSON.meta;
  46343. }
  46344. }
  46345. return nodes;
  46346. }
  46347. parse( json ) {
  46348. const node = this.createNodeFromType( json.type );
  46349. node.uuid = json.uuid;
  46350. const nodes = this.parseNodes( json.nodes );
  46351. const meta = { nodes, textures: this.textures };
  46352. json.meta = meta;
  46353. node.deserialize( json );
  46354. delete json.meta;
  46355. return node;
  46356. }
  46357. setTextures( value ) {
  46358. this.textures = value;
  46359. return this;
  46360. }
  46361. setNodes( value ) {
  46362. this.nodes = value;
  46363. return this;
  46364. }
  46365. createNodeFromType( type ) {
  46366. if ( this.nodes[ type ] === undefined ) {
  46367. console.error( 'THREE.NodeLoader: Node type not found:', type );
  46368. return float();
  46369. }
  46370. return nodeObject( new this.nodes[ type ]() );
  46371. }
  46372. }
  46373. class NodeMaterialLoader extends MaterialLoader {
  46374. constructor( manager ) {
  46375. super( manager );
  46376. this.nodes = {};
  46377. this.nodeMaterials = {};
  46378. }
  46379. parse( json ) {
  46380. const material = super.parse( json );
  46381. const nodes = this.nodes;
  46382. const inputNodes = json.inputNodes;
  46383. for ( const property in inputNodes ) {
  46384. const uuid = inputNodes[ property ];
  46385. material[ property ] = nodes[ uuid ];
  46386. }
  46387. return material;
  46388. }
  46389. setNodes( value ) {
  46390. this.nodes = value;
  46391. return this;
  46392. }
  46393. setNodeMaterials( value ) {
  46394. this.nodeMaterials = value;
  46395. return this;
  46396. }
  46397. createMaterialFromType( type ) {
  46398. const materialClass = this.nodeMaterials[ type ];
  46399. if ( materialClass !== undefined ) {
  46400. return new materialClass();
  46401. }
  46402. return super.createMaterialFromType( type );
  46403. }
  46404. }
  46405. class NodeObjectLoader extends ObjectLoader {
  46406. constructor( manager ) {
  46407. super( manager );
  46408. this.nodes = {};
  46409. this.nodeMaterials = {};
  46410. this._nodesJSON = null;
  46411. }
  46412. setNodes( value ) {
  46413. this.nodes = value;
  46414. return this;
  46415. }
  46416. setNodeMaterials( value ) {
  46417. this.nodeMaterials = value;
  46418. return this;
  46419. }
  46420. parse( json, onLoad ) {
  46421. this._nodesJSON = json.nodes;
  46422. const data = super.parse( json, onLoad );
  46423. this._nodesJSON = null; // dispose
  46424. return data;
  46425. }
  46426. parseNodes( json, textures ) {
  46427. if ( json !== undefined ) {
  46428. const loader = new NodeLoader();
  46429. loader.setNodes( this.nodes );
  46430. loader.setTextures( textures );
  46431. return loader.parseNodes( json );
  46432. }
  46433. return {};
  46434. }
  46435. parseMaterials( json, textures ) {
  46436. const materials = {};
  46437. if ( json !== undefined ) {
  46438. const nodes = this.parseNodes( this._nodesJSON, textures );
  46439. const loader = new NodeMaterialLoader();
  46440. loader.setTextures( textures );
  46441. loader.setNodes( nodes );
  46442. loader.setNodeMaterials( this.nodeMaterials );
  46443. for ( let i = 0, l = json.length; i < l; i ++ ) {
  46444. const data = json[ i ];
  46445. materials[ data.uuid ] = loader.parse( data );
  46446. }
  46447. }
  46448. return materials;
  46449. }
  46450. }
  46451. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  46452. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  46453. revision: REVISION,
  46454. } } ) );
  46455. }
  46456. if ( typeof window !== 'undefined' ) {
  46457. if ( window.__THREE__ ) {
  46458. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  46459. } else {
  46460. window.__THREE__ = REVISION;
  46461. }
  46462. }
  46463. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AfterImageNode, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnaglyphPassNode, AnalyticLightNode, AnamorphicNode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrayElementNode, ArrowHelper, AssignNode, AttachedBindMode, AttributeNode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BRDF_GGX, BRDF_Lambert, BackSide, BasicDepthPacking, BasicEnvironmentNode, BasicShadowMap$1 as BasicShadowMap, BatchNode, BatchedMesh, BloomNode, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, Controls, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeTextureNode, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, DFGApprox, D_GGX, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DenoiseNode, DepthFormat, DepthOfFieldNode, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, Discard, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronGeometry, DotScreenNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, FXAANode, F_Schlick, FileLoader, FilmNode, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fn, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GTAONode, GaussianBlurNode, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, InstanceNode, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InstancedPointsNodeMaterial, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightProbeNode, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearDisplayP3ColorSpace, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, Loop, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, Lut3DNode, MOUSE, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalAnimationBlendMode, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OscNode, OutputStructNode, P3Primaries, PCFShadowMap$1 as PCFShadowMap, PCFSoftShadowMap$1 as PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, ParallaxBarrierPassNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, PixelationPassNode, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PostProcessing, PosterizeNode, PropertyBinding, PropertyMixer, PropertyNode, QuadMesh, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, 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, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGBShiftNode, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RawShaderMaterial, Ray, Raycaster, Rec709Primaries, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, Return, ReverseSubtractEquation, RingGeometry, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, SSAAPassNode, Scene, SceneNode, Schlick_to_F0, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShaderMaterial, ShaderNode, ShadowMaterial, ShadowNodeMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, SobelOperatorNode, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StereoPassNode, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, Texture3DNode, TextureLoader, TextureNode, TextureSizeNode, TimerNode, ToneMappingNode, TorusGeometry, TorusKnotGeometry, TransitionNode, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformArrayNode, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, abs, acesFilmicToneMapping, acos, add, addMethodChaining, addNodeElement, afterImage, agxToneMapping, all, alphaT, anaglyphPass, anamorphic, and, anisotropy, anisotropyB, anisotropyT, any, ao, append, arrayBuffer, asin, assign, atan, atan2, atomicAdd, atomicAnd, atomicFunc, atomicMax, atomicMin, atomicOr, atomicStore, atomicSub, atomicXor, attenuationColor, attenuationDistance, attribute, backgroundBlurriness, backgroundIntensity, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, bleach, bloom, blur, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraLogDepth, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, ceil, checker, cineonToneMapping, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToWorking, colorToDirection, compute, cond, context, convert, convertToTexture, cos, createCanvasElement, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, denoise, densityFog, depth, depthPass, difference, diffuseColor, directionToColor, dispersion, distance, div, dodge, dof, dot, dotScreen, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, film, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, fxaa, gain, gapSize, gaussianBlur, getColorSpaceMethod, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getRoughness, getShIrradianceAt, getTextureIndex, global, glsl, glslFn, grayscale, greaterThan, greaterThanEqual, hash, highPrecisionModelNormalViewMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, invocationLocalIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightPosition, lightTargetDirection, lightTargetPosition, lightViewPosition, lightingContext, lights, linearDepth, linearSRGBTosRGB, linearToneMapping, log, log2, loop, luminance, lut3D, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialAttenuationColor, materialAttenuationDistance, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIOR, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRefractionRatio, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularColor, materialSpecularIntensity, materialSpecularStrength, materialThickness, materialTransmission, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mixElement, mod, modInt, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, motionBlur, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, neutralToneMapping, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalFlat, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, notEqual, objectDirection, objectGroup, objectPosition, objectScale, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxBarrierPass, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToViewZ, pixelationPass, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionPrevious, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, reinhardToneMapping, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rgbShift, rotate, rotateUV, roughness, round, rtt, sRGBToLinearSRGB, sampler, saturate, saturation, screen, screenCoordinate, screenSize, screenUV, scriptable, scriptableValue, select, sepia, setCurrentStack, shaderStages, sharedUniformGroup, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, smoothstepElement, sobel, specularColor, specularF90, spherizeUV, split, spritesheetUV, sqrt, ssaaPass, stack, step, stereoPass, storage, storageBarrier, storageObject, storageTexture, string, sub, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBarrier, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, transformDirection, transformNormal, transformNormalToView, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transition, transmission, transpose, tri, tri3, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, uniform, uniformArray, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, velocity, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSafeUV, viewportSharedTexture, viewportSize, viewportTexture, viewportTopLeft, viewportUV, wgsl, wgslFn, workgroupArray, workgroupBarrier, workingToColorSpace, xor };